From f52e7c847164ca52e2e6971a191daf27cf4a8acc Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:42:12 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20agents:=20CLI=20auto-memory=20o?= =?UTF-8?q?ff=20by=20default;=20clear=5Fmemory=5Fon=5Fkick=20wipes=20per-a?= =?UTF-8?q?gent=20memory=20before=20each=20kick?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds agents.cli_memory {auto_memory, clear_on_kick} with per-agent override, seeds the vendor off-switches (Claude env var, Codex [features] memories, Copilot settings.json memory) and removes the agent's own memory stores next to the /clear kick when clear_on_kick is set. Fixes #17032 Signed-off-by: Andrew Anderson --- changelog.d/added-agent-cli-memory-config.md | 1 + src/crux/agent/cli_memory.go | 237 ++++++++++++++++++ src/crux/agent/cli_memory_test.go | 215 ++++++++++++++++ src/crux/agent/interactive_home.go | 1 + src/crux/agent/manager_env.go | 1 + src/crux/agent/manager_homes.go | 11 +- src/crux/agent/manager_kick.go | 6 + src/crux/agent/manager_test.go | 7 +- src/crux/config/agent_config.go | 12 +- src/crux/config/cli_memory.go | 46 ++++ src/docs/agent-configuration.md | 21 ++ src/internal/settingsparity/settingsparity.go | 2 + .../settingsparity/settingsparity_test.go | 2 + src/pkg/config/cli_memory_test.go | 95 +++++++ src/pkg/config/config.go | 23 +- src/pkg/config/crux_aliases.go | 1 + .../dashboard/settings_parity_allowlist.txt | 4 + 17 files changed, 677 insertions(+), 8 deletions(-) create mode 100644 changelog.d/added-agent-cli-memory-config.md create mode 100644 src/crux/agent/cli_memory.go create mode 100644 src/crux/agent/cli_memory_test.go create mode 100644 src/crux/config/cli_memory.go create mode 100644 src/pkg/config/cli_memory_test.go diff --git a/changelog.d/added-agent-cli-memory-config.md b/changelog.d/added-agent-cli-memory-config.md new file mode 100644 index 0000000000..eb3be2be7c --- /dev/null +++ b/changelog.d/added-agent-cli-memory-config.md @@ -0,0 +1 @@ +- New `agents.cli_memory` block (per-agent `cli_memory:` override): `auto_memory` (default false) pins Claude Code / Codex / Copilot CLI auto-memory off via `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`, `[features] memories = false` and `"memory": false`; `clear_on_kick` wipes that agent's `~/.claude/projects/*/memory`, `$CODEX_HOME/memories*` and `~/.gemini/GEMINI.md` before each non-resume kick (hivecommons/hive#17032). diff --git a/src/crux/agent/cli_memory.go b/src/crux/agent/cli_memory.go new file mode 100644 index 0000000000..dc1ef6acc6 --- /dev/null +++ b/src/crux/agent/cli_memory.go @@ -0,0 +1,237 @@ +package agent + +import ( + "encoding/json" + "errors" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// Persistent CLI memory policy (hivecommons/hive#17032). See +// config.CLIMemoryConfig for the operator-facing knobs. Each CLI's switch is +// the one its vendor documents: +// +// - Claude Code: auto-memory lives in ~/.claude/projects//memory/ and +// is disabled with the CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 environment +// variable (equivalently "autoMemoryEnabled": false in settings.json). +// https://code.claude.com/docs/en/memory — the env var is used because it +// is per process, so a per-agent override needs no second settings file. +// - Codex: memories are a feature flag, [features] memories = true|false in +// $CODEX_HOME/config.toml, stored under $CODEX_HOME/memories/ (and the +// memories_v2/ layout). https://developers.openai.com/codex/memories and +// https://developers.openai.com/codex/config-reference +// - Copilot CLI: the "memory" key in ~/.copilot/settings.json ("whether to +// enable agentic memory", `copilot help config`; /memory on|off writes +// it). The memory itself is server-side (Copilot Memory), so there is no +// local store to wipe. +// - Gemini CLI: no automatic memory; save_memory / `/memory add` write +// ~/.gemini/GEMINI.md, which the wipe removes. +const ( + claudeDisableAutoMemoryEnv = "CLAUDE_CODE_DISABLE_AUTO_MEMORY" + codexMemoriesFeatureKey = "memories" + codexFeaturesTableHeader = "[features]" + copilotSettingsFileName = "settings.json" + copilotMemorySettingKey = "memory" +) + +// claudeCLIBackend reports whether backend launches the Claude Code CLI +// (subscription or inference-routed), i.e. whether Claude's auto-memory +// switch applies. +func claudeCLIBackend(backend string) bool { + return backend == "claude" || IsInferenceBackend(backend) +} + +// cliMemoryEnvPairs returns the launch environment that pins the CLI's +// auto-memory off for this agent when the policy says so. +func cliMemoryEnvPairs(agent *AgentProcess, backend string) []agentEnvPair { + if agent.Config.CLIMemory.AutoMemoryEnabled() || !claudeCLIBackend(backend) { + return nil + } + return []agentEnvPair{{claudeDisableAutoMemoryEnv, "1", false}} +} + +// codexConfigWithMemoriesPinned returns existing with `memories = ` +// set inside the [features] table, adding the table at the end when absent +// and replacing an existing memories line in place. Content outside that one +// key is preserved byte for byte, like codexConfigWithUpdateCheckDisabled. +func codexConfigWithMemoriesPinned(existing []byte, enabled bool) []byte { + line := codexMemoriesFeatureKey + " = " + boolTOML(enabled) + lines := strings.SplitAfter(string(existing), "\n") + if len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + tableStart := -1 + for i, l := range lines { + if strings.TrimSpace(l) == codexFeaturesTableHeader { + tableStart = i + break + } + } + if tableStart < 0 { + text := strings.Join(lines, "") + if text != "" && !strings.HasSuffix(text, "\n") { + text += "\n" + } + if text != "" { + text += "\n" + } + return []byte(text + codexFeaturesTableHeader + "\n" + line + "\n") + } + end := len(lines) + for i := tableStart + 1; i < len(lines); i++ { + if strings.HasPrefix(strings.TrimSpace(lines[i]), "[") { + end = i + break + } + } + for i := tableStart + 1; i < end; i++ { + trimmed := strings.TrimSpace(lines[i]) + if strings.HasPrefix(trimmed, "#") { + continue + } + if key, _, ok := strings.Cut(trimmed, "="); ok && strings.TrimSpace(key) == codexMemoriesFeatureKey { + lines[i] = line + lineEnding(lines[i]) + return []byte(strings.Join(lines, "")) + } + } + // Insert as the last entry of the table, before any trailing blank lines + // that separate it from the next table. + insert := end + for insert > tableStart+1 && strings.TrimSpace(lines[insert-1]) == "" { + insert-- + } + if !strings.HasSuffix(lines[insert-1], "\n") { + lines[insert-1] += "\n" + } + merged := make([]string, 0, len(lines)+1) + merged = append(merged, lines[:insert]...) + merged = append(merged, line+"\n") + merged = append(merged, lines[insert:]...) + return []byte(strings.Join(merged, "")) +} + +func boolTOML(b bool) string { + if b { + return "true" + } + return "false" +} + +// seedCopilotMemorySetting pins the Copilot CLI "memory" setting in the +// agent's per-agent ~/.copilot/settings.json to the policy value. Unlike +// seedJSONFile this OVERWRITES the key: the policy owns it, so flipping +// agents.cli_memory.auto_memory takes effect on the next launch instead of +// being shadowed by the value an earlier launch wrote. Other keys are kept. +func (m *Manager) seedCopilotMemorySetting(agent *AgentProcess, home string) { + dir := filepath.Join(home, copilotHomeDirName) + if info, err := os.Lstat(dir); err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return + } + path := filepath.Join(dir, copilotSettingsFileName) + want := agent.Config.CLIMemory.AutoMemoryEnabled() + existing := map[string]any{} + if data, err := readInferenceConfigFile(path); err == nil { + if jsonErr := json.Unmarshal(data, &existing); jsonErr != nil { + m.logger.Warn("copilot settings unparseable, rewriting", + "agent", agent.Name, "path", path, "error", jsonErr) + existing = map[string]any{} + } + } + if cur, ok := existing[copilotMemorySettingKey].(bool); ok && cur == want { + return + } + existing[copilotMemorySettingKey] = want + data, err := json.Marshal(existing) + if err != nil { + m.logger.Warn("failed to marshal copilot settings", "agent", agent.Name, "path", path, "error", err) + return + } + if err := writeInferenceConfigFile(path, data); err != nil { + m.logger.Warn("failed to write copilot settings", "agent", agent.Name, "path", path, "error", err) + return + } + if agent.UID > 0 { + // Best-effort: unprivileged deployments cannot chown, and the file + // mode already keeps it usable there. + _ = os.Chown(path, agent.UID, -1) + } +} + +// cliMemoryStorePaths lists the persistent memory stores of every CLI this +// agent might have run, under its own HOME and CODEX_HOME only. Shared-home +// paths are never returned: under HIVE_SHARED_AGENT_HOME=1 (or a UID-0 +// agent) the stores are fleet-shared and wiping them for one agent's kick +// would erase every other agent's memory too. +func cliMemoryStorePaths(agent *AgentProcess, backend string) []string { + if agent.UID <= 0 || sharedAgentHomeForced() { + return nil + } + home := AgentHome(agent.Name, agent.UID, backend) + var paths []string + for _, spec := range perAgentCLIHomes { + for _, rel := range spec.memoryRel { + matches, err := filepath.Glob(filepath.Join(home, spec.dir, filepath.FromSlash(rel))) + if err != nil { + continue + } + paths = append(paths, matches...) + } + } + for _, rel := range codexMemoryDirs { + p := filepath.Join(codexHomePath(agent.Name), rel) + if _, err := os.Lstat(p); err == nil { + paths = append(paths, p) + } + } + return paths +} + +// codexMemoryDirs are the Codex memory layouts under $CODEX_HOME +// (https://developers.openai.com/codex/memories). +var codexMemoryDirs = []string{"memories", "memories_v2"} + +// clearCLIMemoryForKick removes the agent's persistent CLI memory stores +// before a kick when agents.cli_memory.clear_on_kick is set, so the new turn +// starts from the kick template and the shared knowledge system alone. It is +// best-effort: a store that cannot be removed is logged and the kick still +// proceeds, since a stale memory is a quality defect, not a safety one. +func (m *Manager) clearCLIMemoryForKick(agent *AgentProcess, backend string) { + if !agent.Config.CLIMemory.ClearMemoryOnKick() { + return + } + paths := cliMemoryStorePaths(agent, backend) + if len(paths) == 0 { + return + } + userSpec := m.agentExecUserSpec(agent) + var removed []string + for _, p := range paths { + if err := m.removeAgentPath(p, userSpec); err != nil { + m.logger.Warn("failed to clear CLI memory before kick", + "agent", agent.Name, "path", p, "error", err) + continue + } + removed = append(removed, p) + } + if len(removed) > 0 { + m.logger.Info("cleared CLI persistent memory before kick", + "agent", agent.Name, "paths", removed) + } +} + +// removeAgentPath removes path (recursively) from the manager's own identity, +// falling back to `su-exec rm -rf` when the tree is owned by the +// agent UID and the manager is not privileged to delete it. +func (m *Manager) removeAgentPath(path, userSpec string) error { + err := os.RemoveAll(path) + if err == nil || !errors.Is(err, fs.ErrPermission) || userSpec == "" { + return err + } + if out, rerr := exec.Command("su-exec", userSpec, "rm", "-rf", "--", path).CombinedOutput(); rerr != nil { + return outputErr("removing "+path+" as "+userSpec, rerr, out) + } + return nil +} diff --git a/src/crux/agent/cli_memory_test.go b/src/crux/agent/cli_memory_test.go new file mode 100644 index 0000000000..8b5f50be19 --- /dev/null +++ b/src/crux/agent/cli_memory_test.go @@ -0,0 +1,215 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +func envValue(pairs []agentEnvPair, key string) (string, bool) { + for _, p := range pairs { + if p.Key == key { + return p.Value, true + } + } + return "", false +} + +// Default policy: Claude Code's auto-memory is pinned off for every Claude +// CLI launch (subscription and inference-routed), not for other CLIs. +func TestAgentEnvPairs_CLIMemoryPinsClaudeAutoMemoryOffByDefault(t *testing.T) { + m := NewManager(map[string]config.AgentConfig{"scanner": {Backend: "claude"}}, discardLogger(), ProjectContext{}) + for _, backend := range []string{"claude", "vllm"} { + ap := &AgentProcess{Name: "scanner", Config: config.AgentConfig{Backend: backend, Model: "sonnet"}} + if v, ok := envValue(m.agentEnvPairs(ap), claudeDisableAutoMemoryEnv); !ok || v != "1" { + t.Errorf("backend %s: %s=%q ok=%v, want 1", backend, claudeDisableAutoMemoryEnv, v, ok) + } + } + ap := &AgentProcess{Name: "scanner", Config: config.AgentConfig{Backend: "codex"}} + if _, ok := envValue(m.agentEnvPairs(ap), claudeDisableAutoMemoryEnv); ok { + t.Errorf("%s exported to a non-Claude CLI", claudeDisableAutoMemoryEnv) + } +} + +func TestAgentEnvPairs_CLIMemoryOptInLeavesClaudeDefault(t *testing.T) { + m := NewManager(map[string]config.AgentConfig{"scanner": {Backend: "claude"}}, discardLogger(), ProjectContext{}) + ap := &AgentProcess{Name: "scanner", Config: config.AgentConfig{ + Backend: "claude", + CLIMemory: &config.CLIMemoryConfig{AutoMemory: boolPtr(true)}, + }} + if v, ok := envValue(m.agentEnvPairs(ap), claudeDisableAutoMemoryEnv); ok { + t.Errorf("auto_memory: true still exported %s=%q", claudeDisableAutoMemoryEnv, v) + } +} + +func TestCodexConfigWithMemoriesPinned(t *testing.T) { + cases := []struct { + name string + in string + enabled bool + want string + }{ + { + name: "empty adds table", + want: "[features]\nmemories = false\n", + }, + { + name: "top-level keys kept, table appended", + in: "check_for_update_on_startup = false\nmodel = \"gpt-5-codex\"\n", + want: "check_for_update_on_startup = false\nmodel = \"gpt-5-codex\"\n\n[features]\nmemories = false\n", + }, + { + name: "existing table gets the key", + in: "model = \"x\"\n\n[features]\nweb_search = true\n\n[projects.\"/data/agents/ci\"]\ntrust_level = \"trusted\"\n", + want: "model = \"x\"\n\n[features]\nweb_search = true\nmemories = false\n\n[projects.\"/data/agents/ci\"]\ntrust_level = \"trusted\"\n", + }, + { + name: "existing key replaced in place", + in: "[features]\nmemories = true\nweb_search = true\n", + want: "[features]\nmemories = false\nweb_search = true\n", + }, + { + name: "opt-in writes true", + in: "[features]\nmemories = false\n", + enabled: true, + want: "[features]\nmemories = true\n", + }, + { + name: "memories key in another table is not ours", + in: "[projects.\"/x\"]\nmemories = true\n", + want: "[projects.\"/x\"]\nmemories = true\n\n[features]\nmemories = false\n", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := string(codexConfigWithMemoriesPinned([]byte(c.in), c.enabled)); got != c.want { + t.Errorf("merged config = %q, want %q", got, c.want) + } + }) + } + // The combined seed carries both hive pins. + if got := string(codexConfigSeed(nil, false)); got != "check_for_update_on_startup = false\n\n[features]\nmemories = false\n" { + t.Errorf("codexConfigSeed(nil) = %q", got) + } +} + +func TestSeedCopilotMemorySetting_OwnsTheKey(t *testing.T) { + withSharedAgentHome(t) + m := interactiveHomeTestManager(t) + ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "copilot"}} + + m.setupInteractiveHome(ap, "copilot") + + path := filepath.Join(interactiveHomePath("scanner"), ".copilot", copilotSettingsFileName) + read := func() map[string]any { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read settings: %v", err) + } + var got map[string]any + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("parse settings: %v", err) + } + return got + } + if got := read(); got[copilotMemorySettingKey] != false { + t.Fatalf("default launch: %s = %v, want false", copilotMemorySettingKey, got[copilotMemorySettingKey]) + } + + // An operator key the CLI wrote itself is preserved; the policy flips + // only its own key when the operator opts in. + if err := os.WriteFile(path, []byte(`{"memory":false,"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + ap.Config.CLIMemory = &config.CLIMemoryConfig{AutoMemory: boolPtr(true)} + m.setupInteractiveHome(ap, "copilot") + got := read() + if got[copilotMemorySettingKey] != true || got["theme"] != "dark" { + t.Fatalf("opt-in: %v", got) + } +} + +func TestClearCLIMemoryForKick_WipesOnlyThisAgentsStores(t *testing.T) { + shared := withSharedAgentHome(t) + prev := codexHomePrefix + codexHomePrefix = filepath.Join(t.TempDir(), ".codex-") + t.Cleanup(func() { codexHomePrefix = prev }) + + m := interactiveHomeTestManager(t) + ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{ + Backend: "claude", + CLIMemory: &config.CLIMemoryConfig{ClearOnKick: true}, + }} + home := interactiveHomePath("scanner") + mustWrite := func(p string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + claudeMem := filepath.Join(home, ".claude", "projects", "-data-agents-scanner", "memory", "MEMORY.md") + claudeTranscript := filepath.Join(home, ".claude", "projects", "-data-agents-scanner", "abc.jsonl") + geminiMem := filepath.Join(home, ".gemini", geminiMemoryFileName) + geminiSettings := filepath.Join(home, ".gemini", "settings.json") + codexMem := filepath.Join(codexHomePath("scanner"), "memories", "notes.md") + codexMemV2 := filepath.Join(codexHomePath("scanner"), "memories_v2", "index.json") + codexConfig := filepath.Join(codexHomePath("scanner"), "config.toml") + otherAgentMem := filepath.Join(interactiveHomePath("reviewer"), ".claude", "projects", "-data-agents-reviewer", "memory", "MEMORY.md") + sharedMem := filepath.Join(shared, ".claude", "projects", "-data-agents-coder", "memory", "MEMORY.md") + for _, p := range []string{claudeMem, claudeTranscript, geminiMem, geminiSettings, codexMem, codexMemV2, codexConfig, otherAgentMem, sharedMem} { + mustWrite(p) + } + + m.clearCLIMemoryForKick(ap, "claude") + + for _, p := range []string{claudeMem, geminiMem, codexMem, codexMemV2} { + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Errorf("%s should have been wiped (err=%v)", p, err) + } + } + for _, p := range []string{claudeTranscript, geminiSettings, codexConfig, otherAgentMem, sharedMem} { + if _, err := os.Lstat(p); err != nil { + t.Errorf("%s must survive the wipe: %v", p, err) + } + } + + // Idempotent on an already-clean home. + m.clearCLIMemoryForKick(ap, "claude") +} + +func TestClearCLIMemoryForKick_OffByDefaultAndNeverSharedHome(t *testing.T) { + withSharedAgentHome(t) + m := interactiveHomeTestManager(t) + home := interactiveHomePath("scanner") + mem := filepath.Join(home, ".claude", "projects", "-data-agents-scanner", "memory", "MEMORY.md") + if err := os.MkdirAll(filepath.Dir(mem), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(mem, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + + // No policy: nothing is touched. + m.clearCLIMemoryForKick(&AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}}, "claude") + if _, err := os.Stat(mem); err != nil { + t.Fatalf("default policy wiped memory: %v", err) + } + + // Shared-home escape hatch: the store is fleet-shared, so no wipe even + // when the policy asks for one. + t.Setenv("HIVE_SHARED_AGENT_HOME", "1") + on := &config.CLIMemoryConfig{ClearOnKick: true} + if got := cliMemoryStorePaths(&AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{CLIMemory: on}}, "claude"); got != nil { + t.Errorf("shared home returned stores to wipe: %v", got) + } + if got := cliMemoryStorePaths(&AgentProcess{Name: "scanner", UID: 0, Config: config.AgentConfig{CLIMemory: on}}, "claude"); got != nil { + t.Errorf("uid 0 returned stores to wipe: %v", got) + } +} diff --git a/src/crux/agent/interactive_home.go b/src/crux/agent/interactive_home.go index 07621a1298..4c4a15c84a 100644 --- a/src/crux/agent/interactive_home.go +++ b/src/crux/agent/interactive_home.go @@ -275,6 +275,7 @@ func (m *Manager) setupInteractiveHome(agent *AgentProcess, backend string) { m.retireSharedGitConfigBridge(agent.Name, home) m.setupAgentXDGDirs(agent.Name, home, agent.UID) m.setupPerAgentCLIHomes(agent.Name, home, agent.UID) + m.seedCopilotMemorySetting(agent, home) m.seedClaudeSessionForAgent(agent, home) m.tightenInteractiveHome(agent.Name, home, agent.UID) m.sweepOrphanedClaudeTmp(agent.Name) diff --git a/src/crux/agent/manager_env.go b/src/crux/agent/manager_env.go index 17c2188b1b..c930d652aa 100644 --- a/src/crux/agent/manager_env.go +++ b/src/crux/agent/manager_env.go @@ -363,6 +363,7 @@ func (m *Manager) agentEnvPairs(agent *AgentProcess) []agentEnvPair { } vars = append(vars, agentEnvPair{claudeAutoModeServerEnv, claudeAutoModeServerOff, false}) } + vars = append(vars, cliMemoryEnvPairs(agent, backend)...) if m.copilotAuthToken != "" { vars = append(vars, agentEnvPair{copilotTokenEnvVar, m.copilotAuthToken, true}) } diff --git a/src/crux/agent/manager_homes.go b/src/crux/agent/manager_homes.go index b8d8dcb65d..f730f4485c 100644 --- a/src/crux/agent/manager_homes.go +++ b/src/crux/agent/manager_homes.go @@ -100,13 +100,13 @@ func (m *Manager) setupCodexHome(agent *AgentProcess) { if readFailed { // Preserve unknown existing content rather than overwrite it blindly. } else if configBytes != nil || salvagedConfig != nil { - mergedConfig := codexConfigWithUpdateCheckDisabled(configBytes) + mergedConfig := codexConfigSeed(configBytes, agent.Config.CLIMemory.AutoMemoryEnabled()) if string(mergedConfig) != string(configBytes) || salvagedConfig != nil { if err := writeFileAsUser(agentUser, configPath, mergedConfig); err != nil { m.logger.Warn("failed to seed codex config", "agent", agent.Name, "dir", dir, "error", err) } } - } else if err := writeFileAsUser(agentUser, configPath, codexConfigWithUpdateCheckDisabled(nil)); err != nil { + } else if err := writeFileAsUser(agentUser, configPath, codexConfigSeed(nil, agent.Config.CLIMemory.AutoMemoryEnabled())); err != nil { m.logger.Warn("failed to seed codex config", "agent", agent.Name, "dir", dir, "error", err) } // Bridge auth: symlink the per-agent auth.json to the shared login file so a @@ -121,6 +121,13 @@ func (m *Manager) setupCodexHome(agent *AgentProcess) { const codexDisableUpdateCheckLine = "check_for_update_on_startup = false" +// codexConfigSeed applies every hive-owned pin to a $CODEX_HOME/config.toml: +// the startup update check off, and the memories feature pinned to the +// agents.cli_memory.auto_memory policy (hivecommons/hive#17032). +func codexConfigSeed(existing []byte, autoMemory bool) []byte { + return codexConfigWithMemoriesPinned(codexConfigWithUpdateCheckDisabled(existing), autoMemory) +} + func codexConfigWithUpdateCheckDisabled(existing []byte) []byte { if len(existing) == 0 { return []byte(codexDisableUpdateCheckLine + "\n") diff --git a/src/crux/agent/manager_kick.go b/src/crux/agent/manager_kick.go index 6c951ff28d..ef44072c2e 100644 --- a/src/crux/agent/manager_kick.go +++ b/src/crux/agent/manager_kick.go @@ -293,6 +293,12 @@ func (m *Manager) deliverKickLocked(agent *AgentProcess, message, trigger string time.Sleep(staleCheckDelay) } + // Persistent CLI memory (hivecommons/hive#17032) is wiped before the + // conversation /clear below, and skipped on the same resume kicks: a + // resumed session is continuing prior work, not starting a fresh turn. + if !skipClear { + m.clearCLIMemoryForKick(agent, backend) + } if agent.Config.ClearOnKick && !skipClear { if err := m.tmuxSendLiteralForAgent(agent, "/clear"); err != nil { return m.kickDeliveryFailedLocked(agent, "send text", err) diff --git a/src/crux/agent/manager_test.go b/src/crux/agent/manager_test.go index 657143fc0a..73c1c92afd 100644 --- a/src/crux/agent/manager_test.go +++ b/src/crux/agent/manager_test.go @@ -591,10 +591,11 @@ func TestAgentEnvPairs_BDDirFromBeadsDir(t *testing.T) { t.Error("BD_DIR should be present when BeadsDir is configured") } - // Count should be baseEnvVarCount + 1 for BD_DIR - const expectedWithBDDir = baseEnvVarCount + 1 + // Count should be baseEnvVarCount + 1 for BD_DIR + 1 for the Claude CLI's + // CLAUDE_CODE_DISABLE_AUTO_MEMORY pin (hivecommons/hive#17032). + const expectedWithBDDir = baseEnvVarCount + 2 if len(pairs) != expectedWithBDDir { - t.Errorf("testEnvPairs() returned %d vars, want %d (base + BD_DIR)", len(pairs), expectedWithBDDir) + t.Errorf("testEnvPairs() returned %d vars, want %d (base + BD_DIR + auto-memory pin)", len(pairs), expectedWithBDDir) } } diff --git a/src/crux/config/agent_config.go b/src/crux/config/agent_config.go index 9f64cd4352..42c7f1a2e3 100644 --- a/src/crux/config/agent_config.go +++ b/src/crux/config/agent_config.go @@ -135,6 +135,10 @@ type AgentRuntimeConfig struct { // recycle policy (#14842). It is encoded under agents.session_recycle by // Config's YAML hooks, like AgentsGitHubAPIHourlyCap. AgentsSessionRecycle SessionRecycleConfig `yaml:"-" json:"-"` + // AgentsCLIMemory is the fleet default for the CLI persistent-memory + // policy (hivecommons/hive#17032), encoded under agents.cli_memory by + // Config's YAML hooks, like AgentsSessionRecycle. + AgentsCLIMemory CLIMemoryConfig `yaml:"-" json:"-"` // Backends is the spoke-wide backend allow/deny list (#11310), enforced // at pack apply and by PUT /api/config/agent/{name}/models. Backends BackendsConfig `yaml:"backends,omitempty" json:"backends,omitempty"` @@ -322,8 +326,12 @@ type AgentConfig struct { // stamps the fleet block into nil pointers so the agent manager sees one // resolved policy per agent. SessionRecycle *SessionRecycleConfig `yaml:"session_recycle,omitempty" json:"session_recycle,omitempty"` - DisplayName string `yaml:"display_name" json:"display_name,omitempty"` - Description string `yaml:"description" json:"description,omitempty"` + // CLIMemory overrides the fleet agents.cli_memory policy for this agent + // (hivecommons/hive#17032). Nil inherits the fleet value, which + // EnabledAgents() stamps into nil pointers like SessionRecycle. + CLIMemory *CLIMemoryConfig `yaml:"cli_memory,omitempty" json:"cli_memory,omitempty"` + DisplayName string `yaml:"display_name" json:"display_name,omitempty"` + Description string `yaml:"description" json:"description,omitempty"` // Bob holds bob-backend-only per-agent options. Empty is default-off. Bob AgentBobConfig `yaml:"bob,omitempty" json:"bob,omitempty"` // BobDisplayName is the legacy flat spelling for Bob.SessionLabel. It is diff --git a/src/crux/config/cli_memory.go b/src/crux/config/cli_memory.go new file mode 100644 index 0000000000..79ff1547ee --- /dev/null +++ b/src/crux/config/cli_memory.go @@ -0,0 +1,46 @@ +package config + +// CLIMemoryConfig governs the persistent, cross-session "memory" the agent +// CLIs keep for themselves under the per-agent HOME (hivecommons/hive#17032): +// Claude Code's auto-memory (~/.claude/projects//memory/), Codex +// memories ($CODEX_HOME/memories*), Copilot CLI's agentic memory, and the +// Gemini CLI's saved ~/.gemini/GEMINI.md. It is written fleet-wide under +// agents.cli_memory and may be overridden per agent under +// agents..cli_memory. +// +// Hive agents are stateless workers driven by kick templates, beads and the +// knowledge system; a hidden per-CLI notebook that survives /clear is a +// second, unaudited memory that was observed drifting into false and stale +// "facts" (hivecommons/hive#17031). It is therefore OFF unless the operator +// opts in, and may additionally be wiped before every kick. +type CLIMemoryConfig struct { + // AutoMemory lets the CLI keep its own persistent notes across sessions. + // Nil or false pins the CLI's auto-memory feature off at launch + // (CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, codex [features] memories=false, + // copilot settings.json memory=false); true leaves the CLI's own default + // (and un-pins codex/copilot). + AutoMemory *bool `yaml:"auto_memory,omitempty" json:"auto_memory,omitempty"` + // ClearOnKick wipes the agent's persistent memory store before every + // kick, alongside the /clear that resets the conversation, so each turn + // starts from the kick template and the shared knowledge system only. + ClearOnKick bool `yaml:"clear_on_kick,omitempty" json:"clear_on_kick,omitempty"` +} + +// IsZero reports whether no field was set, so an absent block encodes as +// nothing and a per-agent nil pointer inherits the fleet value. +func (c CLIMemoryConfig) IsZero() bool { + return c.AutoMemory == nil && !c.ClearOnKick +} + +// AutoMemoryEnabled reports whether the CLI may keep persistent memory. The +// receiver may be nil (no per-agent override and no fleet block): the +// default is off. +func (c *CLIMemoryConfig) AutoMemoryEnabled() bool { + return c != nil && c.AutoMemory != nil && *c.AutoMemory +} + +// ClearMemoryOnKick reports whether the memory store is wiped before each +// kick. The receiver may be nil: the default is off. +func (c *CLIMemoryConfig) ClearMemoryOnKick() bool { + return c != nil && c.ClearOnKick +} diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 37cbcd875f..758d19a3b9 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -317,6 +317,9 @@ spec omits `launch_cmd`, Hive still builds the backend command normally. max_rss_mb: 1536 # policy: recycle this agent's CLI session (a normal max_age: 6h # restart) once idle at the prompt and over the RSS min_idle: 2m # or age budget; enabled: false turns it off + cli_memory: # optional override of the fleet agents.cli_memory + auto_memory: false # policy: CLI auto-memory (Claude MEMORY.md, Codex + clear_on_kick: false # memories, Copilot memory) off; wipe before each kick restart_strategy: immediate # how to bring a dead session back beads_dir: /data/beads/scanner # work-record (bead) storage; default per-agent replicas: 3 # materialize scanner, scanner-2, scanner-3 (max 5) @@ -628,6 +631,24 @@ Each per-UID agent runs with its own durable `HOME` under `/data/home/agents//memory/MEMORY.md`, per-agent by path) was writable by every other agent and persisted on the PVC forever. Provisioning now retires those whole-directory bridges on the next launch, keeps only the login/settings entries above, and never deletes or moves anything under `/data/home`: a pre-existing shared memory store is left in place and logged once (`shared CLI home still holds a persistent memory store …`) so you can review or drain it ([#17033](https://github.com/hivecommons/hive/issues/17033)) before removing it by hand. The dashboard's token/cost scanners (`data.claude_sessions_dir`, `data.bob_sessions_dir`, `data.copilot_sessions_dir`) walk the shared path **and** every `/data/home/agents/*/…` sibling, attributing each per-agent tree to its owner, so cost accounting does not regress. `HIVE_SHARED_AGENT_HOME=1` restores the legacy single shared `HOME` for every agent (and with it the shared memory). +### CLI auto-memory (`agents.cli_memory`) + +Subscription CLIs keep their own long-lived "memory" next to the transcripts: Claude Code's auto-memory (`~/.claude/projects/-data-agents-/memory/MEMORY.md`), Codex memories (`$CODEX_HOME/memories/`), Copilot CLI's `memory` setting, and Gemini's `~/.gemini/GEMINI.md`. Hive agents already get their durable context from beads, the knowledge store, and the kick prompt, so a hidden per-CLI notebook mostly accumulates stale one-off inferences ([#17032](https://github.com/hivecommons/hive/issues/17032)). The `agents.cli_memory` block controls it fleet-wide, and each agent may override it with its own `cli_memory:` block: + +```yaml +agents: + cli_memory: + auto_memory: false # default false: pin every CLI's auto-memory feature off + clear_on_kick: false # default false: true wipes this agent's memory stores before each kick +``` + +| Key | Default | Effect | +|---|---|---| +| `auto_memory` | `false` | When false hive pins the vendor switch off at launch: Claude Code gets `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in its environment ([docs](https://code.claude.com/docs/en/memory)); Codex gets `[features] memories = false` merged into `$CODEX_HOME/config.toml` ([docs](https://developers.openai.com/codex/memories)); Copilot CLI gets `"memory": false` in its per-agent `~/.copilot/settings.json` (`copilot help config`). `true` writes the opposite pin so an operator's own setting is never silently shadowed. Gemini CLI has no equivalent switch. | +| `clear_on_kick` | `false` | Before every non-resume kick (next to the `/clear` sent by `clear_on_kick`), remove this agent's `~/.claude/projects/*/memory/`, `$CODEX_HOME/memories*/`, and `~/.gemini/GEMINI.md`. Only the per-agent home under `/data/home/agents/` is touched; nothing under the shared `/data/home` is removed, and agents running with `HIVE_SHARED_AGENT_HOME=1` or as uid 0 are skipped. Copilot memory is server-side and has no local store. | + +Set `auto_memory: true` on a single agent to let it keep a private notebook while the rest of the fleet stays stateless between kicks. The two knobs are independent: `auto_memory: true` with `clear_on_kick: true` gives a memory that lives for exactly one kick. + Every Model Gateway (and the bob backend) also accepts an optional `key_name` — a human-chosen LABEL for the configured key, e.g. `key_name: openrouter-prod-key`. It is safe-to-show metadata, not a secret: the dashboard's gateway row displays it as "Using key: ``", or "(unnamed)" when no label is set, so operators can tell keys apart without ever seeing the value. For gateway keys, the row and settings/status APIs also expose `keySHA256`, the lowercase SHA-256 of the exact effective key string Hive will inject through the inference proxy; this lets operators compare Hive with LiteLLM/OpenRouter key-hash displays without revealing the secret. Saving a replacement key refreshes live inference proxy routes for running agents, so the next kick uses the new key without an agent restart. See [`inference-backends.md`](../../docs/inference-backends.md) for a full YAML example. ### Claude Managed Agents hosted execution diff --git a/src/internal/settingsparity/settingsparity.go b/src/internal/settingsparity/settingsparity.go index 32d2aa8af1..b148e2361b 100644 --- a/src/internal/settingsparity/settingsparity.go +++ b/src/internal/settingsparity/settingsparity.go @@ -149,6 +149,8 @@ func ConfigLeaves(repoRoot string) ([]Leaf, error) { Leaf{Path: "agents.session_recycle.max_rss_mb", Type: "int"}, Leaf{Path: "agents.session_recycle.max_age", Type: "time.Duration"}, Leaf{Path: "agents.session_recycle.min_idle", Type: "time.Duration"}, + Leaf{Path: "agents.cli_memory.auto_memory", Type: "*bool"}, + Leaf{Path: "agents.cli_memory.clear_on_kick", Type: "bool"}, ) byPath := map[string]Leaf{} for _, leaf := range leaves { diff --git a/src/internal/settingsparity/settingsparity_test.go b/src/internal/settingsparity/settingsparity_test.go index 8ad7b7d102..d496470b85 100644 --- a/src/internal/settingsparity/settingsparity_test.go +++ b/src/internal/settingsparity/settingsparity_test.go @@ -97,6 +97,8 @@ func TestConfigLeaves(t *testing.T) { } want := []Leaf{ {Path: "agents..model", Type: "string"}, + {Path: "agents.cli_memory.auto_memory", Type: "*bool"}, + {Path: "agents.cli_memory.clear_on_kick", Type: "bool"}, {Path: "agents.github_api_hourly_cap", Type: "int"}, {Path: "agents.session_recycle.enabled", Type: "*bool"}, {Path: "agents.session_recycle.max_age", Type: "time.Duration"}, diff --git a/src/pkg/config/cli_memory_test.go b/src/pkg/config/cli_memory_test.go new file mode 100644 index 0000000000..6b6b777dac --- /dev/null +++ b/src/pkg/config/cli_memory_test.go @@ -0,0 +1,95 @@ +package config + +import ( + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestCLIMemoryFleetBlockDecodesAndStampsAgents(t *testing.T) { + raw := ` +agents: + cli_memory: + clear_on_kick: true + scanner: + enabled: true + archivist: + enabled: true + cli_memory: + auto_memory: true + disabled: + enabled: false +` + var cfg Config + if err := yaml.NewDecoder(strings.NewReader(raw)).Decode(&cfg); err != nil { + t.Fatalf("Decode: %v", err) + } + if !cfg.AgentsCLIMemory.ClearOnKick || cfg.AgentsCLIMemory.AutoMemory != nil { + t.Fatalf("fleet block = %+v", cfg.AgentsCLIMemory) + } + if _, leaked := cfg.Agents["cli_memory"]; leaked { + t.Fatal("cli_memory leaked into the agents map as an agent") + } + enabled := cfg.EnabledAgents() + scanner := enabled["scanner"].CLIMemory + if scanner == nil || !scanner.ClearMemoryOnKick() || scanner.AutoMemoryEnabled() { + t.Fatalf("scanner did not inherit the fleet block: %+v", scanner) + } + archivist := enabled["archivist"].CLIMemory + if archivist == nil || !archivist.AutoMemoryEnabled() || archivist.ClearMemoryOnKick() { + t.Fatalf("archivist override lost: %+v", archivist) + } + scanner.ClearOnKick = false + if !cfg.AgentsCLIMemory.ClearOnKick { + t.Fatal("stamped pointer aliases the fleet value") + } +} + +func TestCLIMemoryDefaultsOffWhenAbsent(t *testing.T) { + var cfg Config + if err := yaml.NewDecoder(strings.NewReader("agents:\n scanner:\n enabled: true\n")).Decode(&cfg); err != nil { + t.Fatalf("Decode: %v", err) + } + got := cfg.EnabledAgents()["scanner"].CLIMemory + if got != nil { + t.Fatalf("absent fleet block stamped %+v", got) + } + if got.AutoMemoryEnabled() || got.ClearMemoryOnKick() { + t.Fatal("nil policy must read as auto-memory off, no wipe") + } +} + +func TestCLIMemoryRoundTripsThroughMarshal(t *testing.T) { + on := true + cfg := Config{AgentRuntimeConfig: AgentRuntimeConfig{ + Agents: map[string]AgentConfig{"scanner": {Enabled: true}}, + AgentsCLIMemory: CLIMemoryConfig{AutoMemory: &on, ClearOnKick: true}, + }} + cfg.Project.Org = "org" + out, err := yaml.Marshal(cfg) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if !strings.Contains(string(out), "cli_memory:") || !strings.Contains(string(out), "auto_memory: true") || !strings.Contains(string(out), "clear_on_kick: true") { + t.Fatalf("fleet block not encoded:\n%s", out) + } + var back Config + if err := yaml.Unmarshal(out, &back); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if !back.AgentsCLIMemory.AutoMemoryEnabled() || !back.AgentsCLIMemory.ClearOnKick { + t.Fatalf("round trip = %+v", back.AgentsCLIMemory) + } + if _, leaked := back.Agents["cli_memory"]; leaked { + t.Fatal("cli_memory decoded as an agent after round trip") + } + cfg.AgentsCLIMemory = CLIMemoryConfig{} + out, err = yaml.Marshal(cfg) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if strings.Contains(string(out), "cli_memory") { + t.Fatalf("zero fleet block encoded:\n%s", out) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 85a446d85d..e9a5b7feb0 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -265,6 +265,7 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { type plain Config node := cloneYAMLNode(value) var recycle SessionRecycleConfig + var cliMemory CLIMemoryConfig if agents := mappingValueNode(&node, "agents"); agents != nil && agents.Kind == yaml.MappingNode { for i := 0; i < len(agents.Content)-1; { switch agents.Content[i].Value { @@ -281,6 +282,11 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { return fmt.Errorf("agents.session_recycle: %w", err) } agents.Content = append(agents.Content[:i], agents.Content[i+2:]...) + case "cli_memory": + if err := agents.Content[i+1].Decode(&cliMemory); err != nil { + return fmt.Errorf("agents.cli_memory: %w", err) + } + agents.Content = append(agents.Content[:i], agents.Content[i+2:]...) default: i += 2 } @@ -295,6 +301,7 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { c.AgentsGitHubAPIHourlyCap = cap c.AgentsGitHubAPIHourlyCapSet = capSet c.AgentsSessionRecycle = recycle + c.AgentsCLIMemory = cliMemory if governor := mappingValueNode(&node, "governor"); governor != nil { if stall := mappingValueNode(governor, "merge_train_stall_warn_s"); stall != nil && stall.Tag != "!!null" { c.Governor.mergeTrainStallWarnSet = true @@ -7210,13 +7217,23 @@ func (c Config) MarshalYAML() (interface{}, error) { &yaml.Node{Kind: yaml.ScalarNode, Value: "session_recycle"}, &recycleNode) } + if !c.AgentsCLIMemory.IsZero() && agents.Kind == yaml.MappingNode { + var memNode yaml.Node + if err := memNode.Encode(c.AgentsCLIMemory); err != nil { + return nil, err + } + agents.Content = append(agents.Content, + &yaml.Node{Kind: yaml.ScalarNode, Value: "cli_memory"}, + &memNode) + } return &node, nil } // EnabledAgents returns the enabled agents with fleet-level defaults that // the agent manager needs resolved onto each definition: an agent without // its own session_recycle block carries the agents.session_recycle value -// (#14842), so the manager never has to reach back into Config. +// (#14842), likewise agents.cli_memory (hivecommons/hive#17032), so the +// manager never has to reach back into Config. func (c *Config) EnabledAgents() map[string]AgentConfig { result := make(map[string]AgentConfig) for name, agent := range c.Agents { @@ -7225,6 +7242,10 @@ func (c *Config) EnabledAgents() map[string]AgentConfig { fleet := c.AgentsSessionRecycle agent.SessionRecycle = &fleet } + if agent.CLIMemory == nil && !c.AgentsCLIMemory.IsZero() { + fleet := c.AgentsCLIMemory + agent.CLIMemory = &fleet + } result[name] = agent } } diff --git a/src/pkg/config/crux_aliases.go b/src/pkg/config/crux_aliases.go index 60bfbfa272..e4a1151a1f 100644 --- a/src/pkg/config/crux_aliases.go +++ b/src/pkg/config/crux_aliases.go @@ -7,6 +7,7 @@ type ( AgentConfig = cruxconfig.AgentConfig AgentRuntimeConfig = cruxconfig.AgentRuntimeConfig SessionRecycleConfig = cruxconfig.SessionRecycleConfig + CLIMemoryConfig = cruxconfig.CLIMemoryConfig AgentRuntimeGovernorConfig = cruxconfig.AgentRuntimeGovernorConfig AgentSandboxConfig = cruxconfig.AgentSandboxConfig AgentSandboxOverride = cruxconfig.AgentSandboxOverride diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index bc41381782..e891b10d83 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -119,6 +119,8 @@ agents..sandbox.runtime # TODO #11854 agents..sandbox.timeout_s # TODO #11854 agents..sandbox.publish.verify[] # TODO #14999 (policy-file knob; Settings control pending) agents..sandbox.publish.verify_timeout_s # TODO #14999 (policy-file knob; Settings control pending) +agents..cli_memory.auto_memory # TODO #11854 +agents..cli_memory.clear_on_kick # TODO #11854 agents..session_recycle.enabled # TODO #11854 agents..session_recycle.max_age # TODO #11854 agents..session_recycle.max_rss_mb # TODO #11854 @@ -147,6 +149,8 @@ agents..variables..scope # TODO #11854 agents..variables..type # TODO #11854 agents..variables..url # TODO #11854 agents..variables..value # TODO #11854 +agents.cli_memory.auto_memory # TODO #11854 +agents.cli_memory.clear_on_kick # TODO #11854 agents.github_api_hourly_cap # TODO #11854 agents.session_recycle.enabled # TODO #11854 agents.session_recycle.max_age # TODO #11854 From 0940aab2839c966be8974692f5d2e06d56194b30 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:55:15 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=8C=B1=20agents:=20keep=20manager=5Fh?= =?UTF-8?q?omes.go=20inside=20its=20ratchet=20baseline;=20document=20cli?= =?UTF-8?q?=5Fmemory=20in=20agent-knowledge-and-memory.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/crux/agent/cli_memory.go | 7 +++++++ src/crux/agent/manager_homes.go | 7 ------- src/docs/agent-knowledge-and-memory.md | 29 ++++++++++++++++---------- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/crux/agent/cli_memory.go b/src/crux/agent/cli_memory.go index dc1ef6acc6..f4a772a4da 100644 --- a/src/crux/agent/cli_memory.go +++ b/src/crux/agent/cli_memory.go @@ -53,6 +53,13 @@ func cliMemoryEnvPairs(agent *AgentProcess, backend string) []agentEnvPair { return []agentEnvPair{{claudeDisableAutoMemoryEnv, "1", false}} } +// codexConfigSeed applies every hive-owned pin to a $CODEX_HOME/config.toml: +// the startup update check off, and the memories feature pinned to the +// agents.cli_memory.auto_memory policy (hivecommons/hive#17032). +func codexConfigSeed(existing []byte, autoMemory bool) []byte { + return codexConfigWithMemoriesPinned(codexConfigWithUpdateCheckDisabled(existing), autoMemory) +} + // codexConfigWithMemoriesPinned returns existing with `memories = ` // set inside the [features] table, adding the table at the end when absent // and replacing an existing memories line in place. Content outside that one diff --git a/src/crux/agent/manager_homes.go b/src/crux/agent/manager_homes.go index f730f4485c..6303f47d4c 100644 --- a/src/crux/agent/manager_homes.go +++ b/src/crux/agent/manager_homes.go @@ -121,13 +121,6 @@ func (m *Manager) setupCodexHome(agent *AgentProcess) { const codexDisableUpdateCheckLine = "check_for_update_on_startup = false" -// codexConfigSeed applies every hive-owned pin to a $CODEX_HOME/config.toml: -// the startup update check off, and the memories feature pinned to the -// agents.cli_memory.auto_memory policy (hivecommons/hive#17032). -func codexConfigSeed(existing []byte, autoMemory bool) []byte { - return codexConfigWithMemoriesPinned(codexConfigWithUpdateCheckDisabled(existing), autoMemory) -} - func codexConfigWithUpdateCheckDisabled(existing []byte) []byte { if len(existing) == 0 { return []byte(codexDisableUpdateCheckLine + "\n") diff --git a/src/docs/agent-knowledge-and-memory.md b/src/docs/agent-knowledge-and-memory.md index a35f10b5ff..c2e6853490 100644 --- a/src/docs/agent-knowledge-and-memory.md +++ b/src/docs/agent-knowledge-and-memory.md @@ -160,11 +160,18 @@ conversation. `/clear` empties the chat; it does not touch anything on disk. transcripts, history and memory stay on the host. This is the one place memory is isolated by construction. -**No memory handling.** Nothing in Hive sets a CLI's "disable auto-memory" -option (`inferenceSettingsSeed` seeds permissions/onboarding/remote-control -keys only), prunes a `memory/` directory, or clears memory on kick, `/clear` -or restart. What each CLI remembers, it remembers across kicks and pod -restarts — but, since #17031, not across agents. +**Memory policy** (`agents.cli_memory`, `cli_memory.go`, +[#17032](https://github.com/hivecommons/hive/issues/17032)). `auto_memory` +defaults to **false**: Claude Code is launched with +`CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`, Codex gets `[features] memories = false` +in `$CODEX_HOME/config.toml`, Copilot CLI gets `"memory": false` in its +per-agent `~/.copilot/settings.json`; Gemini has no equivalent switch. +`clear_on_kick` (default false) removes this agent's +`~/.claude/projects/*/memory/`, `$CODEX_HOME/memories*/` and +`~/.gemini/GEMINI.md` before each non-resume kick, next to the `/clear`. Both +keys can be overridden per agent. With both off, what each CLI remembers it +remembers across kicks and pod restarts — but, since #17031, not across +agents. See [agent-configuration.md](agent-configuration.md#cli-auto-memory-agentscli_memory). ### What persists across what @@ -176,10 +183,10 @@ not visible. |---|---|---|---|---| | **Knowledge** (`# Relevant Knowledge`, AGENTS.md, skills) | re-selected for *this* kick's issues | n/a — re-injected next kick | ✓ vaults on `/data` | ✓ same stores, filtered by its own `agent_scopes` | | **Conversation** — all CLIs | ✗ (`/clear` first, unless `clear_on_kick: false` or a resume kick) | ✗ | ✗ (CLI relaunched) | ✗ | -| **Claude Code memory** (`~/.claude/projects/-data-agents-/memory/`, `~/.claude/CLAUDE.md`, `history.jsonl`) | ✓ | ✓ | ✓ (`/data/home/agents//.claude` is persistent) | ✗ per-agent dir (#17031); only `.credentials.json` / `settings.json` shared. Before #17031 the whole tree was one bridged copy any agent could read or rewrite | -| **Codex memory** (`$CODEX_HOME`) | ✓ | ✓ | ✓ (`/data/home/.codex-`) | ✗ per-agent dir; only `auth.json` shared | +| **Claude Code memory** (`~/.claude/projects/-data-agents-/memory/`, `~/.claude/CLAUDE.md`, `history.jsonl`) | ✓ unless `cli_memory.clear_on_kick` (and off by default: `auto_memory: false`) | ✓ | ✓ (`/data/home/agents//.claude` is persistent) | ✗ per-agent dir (#17031); only `.credentials.json` / `settings.json` shared. Before #17031 the whole tree was one bridged copy any agent could read or rewrite | +| **Codex memory** (`$CODEX_HOME`) | ✓ unless `cli_memory.clear_on_kick` (off by default) | ✓ | ✓ (`/data/home/.codex-`) | ✗ per-agent dir; only `auth.json` shared | | **Copilot CLI memory/sessions** (`~/.copilot`) | ✓ | ✓ | ✓ | ✗ per-agent dir (#9444); only `config.json` shared | -| **Gemini memory** (`~/.gemini/GEMINI.md`, state) | ✓ | ✓ | ✓ | ✗ per-agent dir (#17031); only sign-in files, `settings.json`, `antigravity-cli/` shared | +| **Gemini memory** (`~/.gemini/GEMINI.md`, state) | ✓ unless `cli_memory.clear_on_kick` | ✓ | ✓ | ✗ per-agent dir (#17031); only sign-in files, `settings.json`, `antigravity-cli/` shared | | **Bob memory/settings** (`~/.bob`) | ✓ | ✓ | ✓ | ✗ per-agent dir (#17031); only `settings.json` / `settings/` shared | The dashboard's cost accounting reads `data.claude_sessions_dir` (default @@ -199,9 +206,9 @@ Do not treat the following as current behaviour; follow the links. `.claude`/`.gemini`/`.bob`, described above). Hives upgraded from before it still hold the old shared store under `/data/home/.claude/projects`; it is left in place and logged once, remove or drain it by hand. -- [#17032](https://github.com/hivecommons/hive/issues/17032) — disable CLI - auto-memory by default and add a `clear_memory_on_kick` option alongside - `clear_on_kick`. +- [#17032](https://github.com/hivecommons/hive/issues/17032) — done: + `agents.cli_memory.auto_memory` (default off) and + `agents.cli_memory.clear_on_kick`, described above. - [#17033](https://github.com/hivecommons/hive/issues/17033) — drain CLI auto-memory into beads/knowledge at session end instead of a hidden `MEMORY.md` (revives open question 5 of