diff --git a/changelog.d/added-17032-cli-memory.md b/changelog.d/added-17032-cli-memory.md new file mode 100644 index 0000000000..b9baf2d664 --- /dev/null +++ b/changelog.d/added-17032-cli-memory.md @@ -0,0 +1 @@ +- Agents: the coding CLIs' own persistent auto-memory is now off by default. Hive seeds Claude Code's `autoMemoryEnabled: false` and Codex's `[features] memories = false` at launch, and an operator's explicit setting still wins. The new fleet block `agents.cli_memory` takes `auto_memory: true` to leave memory on and `clear_on_kick: true` to remove the agent's own memory store before every kick; stores shared with other agents are skipped ([#17032](https://github.com/hivecommons/hive/issues/17032)). diff --git a/src/crux/agent/cli_memory.go b/src/crux/agent/cli_memory.go new file mode 100644 index 0000000000..ccc2d76b6d --- /dev/null +++ b/src/crux/agent/cli_memory.go @@ -0,0 +1,306 @@ +package agent + +import ( + "errors" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// CLI auto-memory policy (agents.cli_memory, #17032). +// +// Every coding CLI hive drives keeps its own persistent memory across +// sessions, and a lane worker should not: a one-off inference written down on +// Tuesday comes back on every kick after it. The fleet policy has two halves: +// +// - auto_memory: false (the default) seeds each CLI's documented disable at +// launch — Claude Code's "autoMemoryEnabled": false, Codex's +// [features] memories = false. Merge-only, like every other hive seed: a +// value the operator already wrote is left alone. Gemini CLI and Copilot +// CLI document no local switch (Gemini's memory is plain GEMINI.md files; +// Copilot Memory is stored on GitHub), so nothing is seeded for them. +// - clear_on_kick: true removes the agent's own memory store before each +// kick (clearCLIMemoryLocked). + +// claudeAutoMemorySettingKey is the Claude Code settings key that turns auto +// memory (~/.claude/projects//memory) on or off. Honored from user +// settings and from the --settings flagSettings file. +const claudeAutoMemorySettingKey = "autoMemoryEnabled" + +// claudeAutoMemorySeed returns the settings key that turns Claude Code's auto +// memory off. +func claudeAutoMemorySeed() map[string]any { + return map[string]any{claudeAutoMemorySettingKey: false} +} + +// inferenceClaudeSettingsFiles are the two settings surfaces an inference +// agent's Claude CLI reads: userSettings in its per-agent HOME and the +// standalone --settings file (see ensureClaudeSettings). +func inferenceClaudeSettingsFiles(agentName string) []string { + return []string{ + filepath.Join(inferenceHomePath(agentName), ".claude", "settings.json"), + claudeInferenceSettingsPath, + } +} + +// ensureClaudeAutoMemoryDefault seeds "autoMemoryEnabled": false into each +// Claude settings file in paths unless the fleet policy leaves auto-memory +// on. Called on every launch so an out-of-band deletion self-heals. A missing +// parent directory is skipped rather than created: the directories belong to +// ensureClaudeSettings and the entrypoint. +func (m *Manager) ensureClaudeAutoMemoryDefault(agent *AgentProcess, paths ...string) { + if agent.Config.CLIMemory.AutoMemory { + return + } + for _, path := range paths { + if _, err := os.Lstat(filepath.Dir(path)); err != nil { + m.logger.Debug("claude settings dir absent; skipping auto-memory seed", + "agent", agent.Name, "dir", filepath.Dir(path), "error", err) + continue + } + m.seedJSONFile(agent.Name, path, claudeAutoMemorySeed()) + } +} + +// codexConfigSeeded is the config.toml hive writes into an agent's +// CODEX_HOME: the update check is always disabled, and memories are disabled +// unless the fleet policy leaves auto-memory on. +func codexConfigSeeded(existing []byte, autoMemory bool) []byte { + out := codexConfigWithUpdateCheckDisabled(existing) + if !autoMemory { + out = codexConfigWithMemoriesDisabled(out) + } + return out +} + +const ( + codexFeaturesTable = "[features]" + codexDisableMemoriesLine = "memories = false" +) + +// codexConfigWithMemoriesDisabled adds memories = false to the [features] +// table of a Codex config.toml. Any existing memories setting — under +// [features], as a top-level features.memories dotted key, or inside a +// top-level features = {...} inline table — is the operator's and is left +// untouched; writing a second one would also make the TOML invalid. +func codexConfigWithMemoriesDisabled(existing []byte) []byte { + lines := strings.SplitAfter(string(existing), "\n") + featuresHeader := -1 + table := "" + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + if strings.HasPrefix(trimmed, "[") { + header, _, _ := strings.Cut(trimmed, "#") + table = strings.TrimSpace(header) + if table == codexFeaturesTable && featuresHeader < 0 { + featuresHeader = i + } + continue + } + key, _, ok := strings.Cut(trimmed, "=") + if !ok { + continue + } + key = strings.TrimSpace(key) + switch { + case table == codexFeaturesTable && key == "memories": + return existing + case table == "" && (key == "features" || key == "features.memories"): + return existing + } + } + if featuresHeader >= 0 { + header := lines[featuresHeader] + if !strings.HasSuffix(header, "\n") { + header += "\n" + } + merged := make([]string, 0, len(lines)+1) + merged = append(merged, lines[:featuresHeader]...) + merged = append(merged, header, codexDisableMemoriesLine+"\n") + merged = append(merged, lines[featuresHeader+1:]...) + return []byte(strings.Join(merged, "")) + } + text := string(existing) + if text != "" { + if !strings.HasSuffix(text, "\n") { + text += "\n" + } + text += "\n" + } + return []byte(text + codexFeaturesTable + "\n" + codexDisableMemoriesLine + "\n") +} + +// cliMemoryRemover deletes the given memory-store paths. With a userSpec it +// runs `rm -rf` AS THE AGENT via su-exec, so a clear can never delete more +// than the agent itself could: the stores sit in agent-writable trees, and a +// recursive delete by the (often root) hive process there would follow any +// symlink the agent planted on the way (the audit F12 class). Without a +// userSpec (UID 0 agents, which run as the hive user anyway) it removes the +// paths directly. A var as a TEST SEAM. +var cliMemoryRemover = func(userSpec string, paths []string) error { + if userSpec == "" { + var errs []error + for _, p := range paths { + errs = append(errs, os.RemoveAll(p)) + } + return errors.Join(errs...) + } + args := append([]string{userSpec, "rm", "-rf", "--"}, paths...) + out, err := exec.Command("su-exec", args...).CombinedOutput() + if err != nil { + return outputErr("su-exec rm", err, out) + } + return nil +} + +// privateDirState classifies a directory a memory store lives under. +type privateDirState int + +const ( + // dirAbsent: a component is missing, so there is no store to clear. + dirAbsent privateDirState = iota + // dirPrivate: root and every component below it are real directories. + dirPrivate + // dirShared: a component is a symlink (a bridge into shared state) or + // otherwise not a plain directory, so a store below it may belong to + // other agents too. + dirShared +) + +// agentPrivateDir classifies root/rel by Lstat-ing root and each component +// of rel in turn. A symlink anywhere on the way means the directory is (or +// may be) shared state, never the agent's own. +func agentPrivateDir(root, rel string) privateDirState { + p := root + parts := []string{""} + if rel != "" { + parts = append(parts, strings.Split(filepath.ToSlash(rel), "/")...) + } + for _, part := range parts { + if part != "" { + p = filepath.Join(p, part) + } + info, err := os.Lstat(p) + if errors.Is(err, fs.ErrNotExist) { + return dirAbsent + } + if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return dirShared + } + } + return dirPrivate +} + +// cliMemoryStores returns the existing memory stores of the agent's CLI that +// are private to the agent (targets), and the directories holding a store +// that were skipped because they are shared with other agents (shared). +// +// - claude, and every inference backend (they run Claude Code): +// $HOME/.claude/projects/*/memory +// - codex: $CODEX_HOME/memories and $CODEX_HOME/memories_v2 +// - gemini: $HOME/.gemini/GEMINI.md, the global file save_memory writes +// +// A HOME that is not per-agent — UID 0 agents run out of the hive's own HOME, +// HIVE_SHARED_AGENT_HOME=1 puts every agent in /data/home — is shared by +// definition. So is a per-agent ~/.claude or ~/.gemini that is still a +// symlink bridge into /data/home (interactiveHomeBridgeDirs). +func (m *Manager) cliMemoryStores(agent *AgentProcess) (targets, shared []string) { + backend := effectiveBackend(agent) + if backend == codexBackend { + root := codexHomePath(agent.Name) + switch agentPrivateDir(root, "") { + case dirShared: + return nil, []string{root} + case dirAbsent: + return nil, nil + } + for _, name := range []string{"memories", "memories_v2"} { + p := filepath.Join(root, name) + if _, err := os.Lstat(p); err == nil { + targets = append(targets, p) + } + } + return targets, nil + } + + var dir string + switch { + case backend == "gemini": + dir = ".gemini" + case backend == "claude" || m.routableBackend(backend): + dir = filepath.Join(".claude", "projects") + default: + return nil, nil + } + home := AgentHome(agent.Name, agent.UID, backend) + if agent.UID <= 0 || home == sharedAgentHome { + if _, err := os.Lstat(filepath.Join(home, dir)); err == nil { + shared = append(shared, filepath.Join(home, dir)) + } + return nil, shared + } + switch agentPrivateDir(home, dir) { + case dirShared: + return nil, []string{filepath.Join(home, dir)} + case dirAbsent: + return nil, nil + } + if backend == "gemini" { + p := filepath.Join(home, dir, "GEMINI.md") + if _, err := os.Lstat(p); err == nil { + targets = append(targets, p) + } + return targets, nil + } + projects := filepath.Join(home, dir) + entries, err := os.ReadDir(projects) + if err != nil { + m.logger.Debug("cannot list claude projects; skipping auto-memory clear", + "agent", agent.Name, "dir", projects, "error", err) + return nil, nil + } + for _, e := range entries { + project := filepath.Join(projects, e.Name()) + memory := filepath.Join(project, "memory") + if _, err := os.Lstat(memory); err != nil { + continue + } + if e.Type()&os.ModeSymlink != 0 || !e.IsDir() { + shared = append(shared, project) + continue + } + targets = append(targets, memory) + } + return targets, shared +} + +// clearCLIMemoryLocked removes the agent's own CLI memory store before a kick +// when agents.cli_memory.clear_on_kick is on. Best-effort: a failure is +// logged and never blocks the kick. A store that is shared with other agents +// is skipped and logged once per agent, because clearing it would wipe +// every other agent's memory too. Caller holds m.mu. +func (m *Manager) clearCLIMemoryLocked(agent *AgentProcess) { + if !agent.Config.CLIMemory.ClearOnKick { + return + } + targets, shared := m.cliMemoryStores(agent) + if len(shared) > 0 && !agent.cliMemorySharedLogged { + agent.cliMemorySharedLogged = true + m.logger.Warn("cli_memory.clear_on_kick: not clearing a CLI memory store shared with other agents; it clears once the agent's CLI home is per-agent", + "agent", agent.Name, "paths", shared) + } + if len(targets) == 0 { + return + } + if err := cliMemoryRemover(m.agentExecUserSpec(agent), targets); err != nil { + m.logger.Warn("cli_memory.clear_on_kick: failed to clear CLI memory before kick", + "agent", agent.Name, "paths", targets, "error", err) + return + } + m.logger.Info("cleared CLI memory before kick", "agent", agent.Name, "paths", targets) +} diff --git a/src/crux/agent/cli_memory_test.go b/src/crux/agent/cli_memory_test.go new file mode 100644 index 0000000000..4aa7eff6d4 --- /dev/null +++ b/src/crux/agent/cli_memory_test.go @@ -0,0 +1,347 @@ +package agent + +// CLI auto-memory policy (agents.cli_memory, #17032). +// +// Invariants under test: with the default policy every hive-provisioned +// Claude settings surface and Codex config carries the documented "memory +// off" switch, an operator's explicit value is never overwritten, and +// clear_on_kick removes only memory the agent alone owns — never a store +// reached through a bridge into shared state, never transcripts or config. + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/hivecommons/hive/crux/config" +) + +func TestCodexConfigWithMemoriesDisabled(t *testing.T) { + cases := []struct { + name, in, want string + }{ + { + name: "empty config gains a features table", + in: "", + want: "[features]\nmemories = false\n", + }, + { + name: "top-level keys only: table appended after them", + in: "check_for_update_on_startup = false", + want: "check_for_update_on_startup = false\n\n[features]\nmemories = false\n", + }, + { + name: "existing features table gains the key under its header", + in: "model = \"gpt-5-codex\"\n[features] # flags\nhooks = true\n[projects.\"/data/agents/ci\"]\ntrust_level = \"trusted\"\n", + want: "model = \"gpt-5-codex\"\n[features] # flags\nmemories = false\nhooks = true\n[projects.\"/data/agents/ci\"]\ntrust_level = \"trusted\"\n", + }, + { + name: "operator's explicit memories = true is kept", + in: "[features]\nmemories = true\n", + want: "[features]\nmemories = true\n", + }, + { + name: "top-level dotted key is kept (a second key would be invalid TOML)", + in: "features.memories = true\n[projects.x]\ntrust_level = \"trusted\"\n", + want: "features.memories = true\n[projects.x]\ntrust_level = \"trusted\"\n", + }, + { + name: "top-level inline features table is kept", + in: "features = { hooks = true }\n", + want: "features = { hooks = true }\n", + }, + { + name: "memories under another table and in a comment do not count", + in: "# memories = true\n[memories]\nuse_memories = false\n", + want: "# memories = true\n[memories]\nuse_memories = false\n\n[features]\nmemories = false\n", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := string(codexConfigWithMemoriesDisabled([]byte(tc.in))) + if got != tc.want { + t.Fatalf("got:\n%q\nwant:\n%q", got, tc.want) + } + if again := string(codexConfigWithMemoriesDisabled([]byte(got))); again != got { + t.Fatalf("not idempotent: second pass rewrote\n%q\nto\n%q", got, again) + } + }) + } +} + +func TestCodexConfigSeededHonorsAutoMemory(t *testing.T) { + if got := string(codexConfigSeeded(nil, false)); !strings.Contains(got, "[features]\nmemories = false\n") || + !strings.Contains(got, codexDisableUpdateCheckLine) { + t.Fatalf("default policy seed = %q, want update check and memories disabled", got) + } + got := string(codexConfigSeeded(nil, true)) + if strings.Contains(got, "memories") { + t.Fatalf("auto_memory: true must seed nothing about memories, got %q", got) + } + if !strings.Contains(got, codexDisableUpdateCheckLine) { + t.Fatalf("update check must stay disabled regardless of the memory policy, got %q", got) + } +} + +func TestEnsureClaudeAutoMemoryDefault(t *testing.T) { + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := &AgentProcess{Name: "scanner", Config: config.AgentConfig{Backend: "claude"}} + dir := t.TempDir() + + t.Run("default policy seeds the key and keeps existing keys", func(t *testing.T) { + path := filepath.Join(dir, "default.json") + if err := os.WriteFile(path, []byte(`{"enabledPlugins":{"x":true}}`), 0o600); err != nil { + t.Fatal(err) + } + m.ensureClaudeAutoMemoryDefault(agent, path) + got := readSettingsMap(t, path) + if v, ok := got[claudeAutoMemorySettingKey]; !ok || v != false { + t.Fatalf("%s = %v (present %v), want false", claudeAutoMemorySettingKey, v, ok) + } + if _, ok := got["enabledPlugins"]; !ok { + t.Fatal("seed dropped an unrelated key") + } + }) + + t.Run("operator's explicit true survives", func(t *testing.T) { + path := filepath.Join(dir, "explicit.json") + if err := os.WriteFile(path, []byte(`{"autoMemoryEnabled":true}`), 0o600); err != nil { + t.Fatal(err) + } + m.ensureClaudeAutoMemoryDefault(agent, path) + if v := readSettingsMap(t, path)[claudeAutoMemorySettingKey]; v != true { + t.Fatalf("%s = %v, want the operator's true", claudeAutoMemorySettingKey, v) + } + }) + + t.Run("auto_memory true seeds nothing", func(t *testing.T) { + on := &AgentProcess{Name: "scanner", Config: config.AgentConfig{Backend: "claude", CLIMemory: config.CLIMemoryConfig{AutoMemory: true}}} + path := filepath.Join(dir, "on.json") + m.ensureClaudeAutoMemoryDefault(on, path) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("auto_memory: true wrote %s (stat err %v)", path, err) + } + }) + + t.Run("missing settings dir is not created", func(t *testing.T) { + path := filepath.Join(dir, "absent", "settings.json") + m.ensureClaudeAutoMemoryDefault(agent, path) + if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { + t.Fatalf("seed created %s (stat err %v)", filepath.Dir(path), err) + } + }) +} + +// recordCLIMemoryRemover swaps cliMemoryRemover for a direct delete that +// records each call, so tests exercise the selection logic without su-exec. +func recordCLIMemoryRemover(t *testing.T) *[][]string { + t.Helper() + var calls [][]string + orig := cliMemoryRemover + cliMemoryRemover = func(_ string, paths []string) error { + calls = append(calls, slices.Clone(paths)) + for _, p := range paths { + if err := os.RemoveAll(p); err != nil { + return err + } + } + return nil + } + t.Cleanup(func() { cliMemoryRemover = orig }) + return &calls +} + +func writeTestFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func assertExists(t *testing.T, path string, want bool) { + t.Helper() + _, err := os.Lstat(path) + if exists := err == nil; exists != want { + t.Fatalf("%s exists = %v, want %v", path, exists, want) + } +} + +func clearOnKickAgent(name, backend string, uid int) *AgentProcess { + return &AgentProcess{ + Name: name, + UID: uid, + Config: config.AgentConfig{ + Backend: backend, + CLIMemory: config.CLIMemoryConfig{ClearOnKick: true}, + }, + } +} + +func TestClearCLIMemory_ClaudePrivateHome(t *testing.T) { + withSharedAgentHome(t) + calls := recordCLIMemoryRemover(t) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := clearOnKickAgent("scanner", "claude", 1001) + home := AgentHome(agent.Name, agent.UID, "claude") + projects := filepath.Join(home, ".claude", "projects") + memory := filepath.Join(projects, "-data-agents-scanner", "memory") + transcript := filepath.Join(projects, "-data-agents-scanner", "session.jsonl") + writeTestFile(t, filepath.Join(memory, "MEMORY.md"), "user works with PHI\n") + writeTestFile(t, transcript, "{}\n") + writeTestFile(t, filepath.Join(home, ".claude", "settings.json"), "{}") + // A project dir symlinked in from elsewhere is not this agent's to clear. + foreign := filepath.Join(t.TempDir(), "other-agent-project") + writeTestFile(t, filepath.Join(foreign, "memory", "MEMORY.md"), "someone else's\n") + if err := os.Symlink(foreign, filepath.Join(projects, "-linked")); err != nil { + t.Fatal(err) + } + + m.clearCLIMemoryLocked(agent) + + assertExists(t, memory, false) + assertExists(t, transcript, true) + assertExists(t, filepath.Join(home, ".claude", "settings.json"), true) + assertExists(t, filepath.Join(foreign, "memory", "MEMORY.md"), true) + if len(*calls) != 1 || !slices.Equal((*calls)[0], []string{memory}) { + t.Fatalf("remover calls = %v, want exactly [[%s]]", *calls, memory) + } +} + +func TestClearCLIMemory_SkipsSharedClaudeBridge(t *testing.T) { + shared := withSharedAgentHome(t) + calls := recordCLIMemoryRemover(t) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := clearOnKickAgent("scanner", "claude", 1001) + home := AgentHome(agent.Name, agent.UID, "claude") + // Today's interactive layout: ~/.claude is a bridge to /data/home/.claude, + // so every claude agent's memory lives in one shared tree. + sharedMemory := filepath.Join(shared, ".claude", "projects", "-data-agents-reviewer", "memory", "MEMORY.md") + writeTestFile(t, sharedMemory, "reviewer's notes\n") + if err := os.MkdirAll(home, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(shared, ".claude"), filepath.Join(home, ".claude")); err != nil { + t.Fatal(err) + } + + m.clearCLIMemoryLocked(agent) + m.clearCLIMemoryLocked(agent) + + assertExists(t, sharedMemory, true) + if len(*calls) != 0 { + t.Fatalf("remover called through a shared bridge: %v", *calls) + } + if !agent.cliMemorySharedLogged { + t.Fatal("skipping a shared store must be logged") + } +} + +func TestClearCLIMemory_SkipsSharedHomes(t *testing.T) { + shared := withSharedAgentHome(t) + calls := recordCLIMemoryRemover(t) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + sharedMemory := filepath.Join(shared, ".claude", "projects", "p", "memory", "MEMORY.md") + writeTestFile(t, sharedMemory, "fleet-wide\n") + + // HIVE_SHARED_AGENT_HOME=1: every per-UID agent runs out of /data/home. + t.Setenv("HIVE_SHARED_AGENT_HOME", "1") + m.clearCLIMemoryLocked(clearOnKickAgent("scanner", "claude", 1001)) + // UID 0 agents share the hive's own HOME. + t.Setenv("HOME", shared) + m.clearCLIMemoryLocked(clearOnKickAgent("scanner", "claude", 0)) + + assertExists(t, sharedMemory, true) + if len(*calls) != 0 { + t.Fatalf("remover called on a shared HOME: %v", *calls) + } +} + +func TestClearCLIMemory_Codex(t *testing.T) { + calls := recordCLIMemoryRemover(t) + orig := codexHomePrefix + codexHomePrefix = filepath.Join(t.TempDir(), ".codex-") + t.Cleanup(func() { codexHomePrefix = orig }) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := clearOnKickAgent("coder", codexBackend, 1002) + root := codexHomePath(agent.Name) + writeTestFile(t, filepath.Join(root, "memories", "summary.md"), "x") + writeTestFile(t, filepath.Join(root, "memories_v2", "summary.md"), "x") + writeTestFile(t, filepath.Join(root, "config.toml"), "[features]\nmemories = true\n") + + m.clearCLIMemoryLocked(agent) + + assertExists(t, filepath.Join(root, "memories"), false) + assertExists(t, filepath.Join(root, "memories_v2"), false) + assertExists(t, filepath.Join(root, "config.toml"), true) + if len(*calls) != 1 { + t.Fatalf("remover calls = %v, want one batched call", *calls) + } +} + +func TestClearCLIMemory_GeminiPrivateHome(t *testing.T) { + withSharedAgentHome(t) + calls := recordCLIMemoryRemover(t) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := clearOnKickAgent("scanner", "gemini", 1001) + home := AgentHome(agent.Name, agent.UID, "gemini") + memory := filepath.Join(home, ".gemini", "GEMINI.md") + writeTestFile(t, memory, "## Gemini Added Memories\n- one-off\n") + writeTestFile(t, filepath.Join(home, ".gemini", "settings.json"), "{}") + + m.clearCLIMemoryLocked(agent) + + assertExists(t, memory, false) + assertExists(t, filepath.Join(home, ".gemini", "settings.json"), true) + if len(*calls) != 1 { + t.Fatalf("remover calls = %v, want 1", *calls) + } +} + +func TestClearCLIMemory_OffByDefault(t *testing.T) { + withSharedAgentHome(t) + calls := recordCLIMemoryRemover(t) + m := NewManager(map[string]config.AgentConfig{}, discardLogger(), ProjectContext{}) + agent := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}} + memory := filepath.Join(AgentHome(agent.Name, agent.UID, "claude"), ".claude", "projects", "p", "memory") + writeTestFile(t, filepath.Join(memory, "MEMORY.md"), "kept\n") + + m.clearCLIMemoryLocked(agent) + + assertExists(t, memory, true) + if len(*calls) != 0 { + t.Fatalf("clear_on_kick: false must not clear, remover calls = %v", *calls) + } +} + +// The clear runs on the kick path before any input reaches the pane, so the +// kick (and the /clear before it) never sees the old memory. +func TestDeliverKickLocked_ClearsCLIMemoryBeforeInput(t *testing.T) { + withSharedAgentHome(t) + m, agent, _ := kickLogTestManager(t, "") + agent.UID = 1001 + agent.Config.CLIMemory.ClearOnKick = true + memory := filepath.Join(AgentHome(agent.Name, agent.UID, "claude"), ".claude", "projects", "p", "memory") + writeTestFile(t, filepath.Join(memory, "MEMORY.md"), "stale\n") + + var events []string + orig := cliMemoryRemover + cliMemoryRemover = func(_ string, paths []string) error { + events = append(events, "clear-memory") + return nil + } + t.Cleanup(func() { cliMemoryRemover = orig }) + termSeams(m).sendKeys = func(_ *AgentProcess, keys ...string) { + events = append(events, "sendkeys:"+strings.Join(keys, "+")) + } + + m.deliverKickLocked(agent, "next task", "send-kick") + + if len(events) < 2 || events[0] != "clear-memory" { + t.Fatalf("events = %v, want the memory clear before any pane input", events) + } +} diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 147b93d4d3..b89e09b2d0 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -382,9 +382,10 @@ type AgentProcess struct { // SessionRSSMB is the last sampled RSS of the CLI process tree (MiB); // SessionRecycles counts #14842 policy recycles; lastSessionRecycle // enforces the per-agent backoff after one. - SessionRSSMB int - SessionRecycles int - lastSessionRecycle time.Time + SessionRSSMB int + SessionRecycles int + lastSessionRecycle time.Time + cliMemorySharedLogged bool // clearCLIMemoryLocked already warned the store is shared (#17032) // busyNoActivityRestartAt is when busyNoActivityStall last restarted this // agent, and busyNoActivityRestarts how many times it has in the current // episode. Both survive the restart's busy-visibility reset and clear on diff --git a/src/crux/agent/manager_homes.go b/src/crux/agent/manager_homes.go index b8d8dcb65d..f1f47b9e89 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 := codexConfigSeeded(configBytes, agent.Config.CLIMemory.AutoMemory) 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, codexConfigSeeded(nil, agent.Config.CLIMemory.AutoMemory)); 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 diff --git a/src/crux/agent/manager_kick.go b/src/crux/agent/manager_kick.go index 6c951ff28d..1a7766b62a 100644 --- a/src/crux/agent/manager_kick.go +++ b/src/crux/agent/manager_kick.go @@ -269,6 +269,10 @@ func (m *Manager) deliverKickLocked(agent *AgentProcess, message, trigger string // input touches the pane, so each archived kick log is cleanly delimited // (#4296). Must be the first thing this function does. m.rotateKickLogOnKickLocked(agent) + // agents.cli_memory.clear_on_kick (#17032): drop the CLI's persistent + // memory before any input, for every backend path below, so the kick + // starts from the prompt rather than from what an earlier kick inferred. + m.clearCLIMemoryLocked(agent) // The caller has already waited for input readiness. Codex can exit on // Ctrl+C at that prompt, leaving the subsequent task to be executed by diff --git a/src/crux/agent/manager_launch.go b/src/crux/agent/manager_launch.go index 31713b6d74..cb2b4519fa 100644 --- a/src/crux/agent/manager_launch.go +++ b/src/crux/agent/manager_launch.go @@ -115,6 +115,7 @@ func (m *Manager) launchInTmux(ctx context.Context, agent *AgentProcess) error { if isInference { binary = "claude" m.ensureClaudeSettings(agent.Name, agent.UID) + m.ensureClaudeAutoMemoryDefault(agent, inferenceClaudeSettingsFiles(agent.Name)...) if m.inferenceRouteCallback != nil { // inference-model-passthrough: the model set here becomes the // outbound OpenAI "model" field that the gateway checks for @@ -131,6 +132,7 @@ func (m *Manager) launchInTmux(ctx context.Context, agent *AgentProcess) error { } if backend == "claude" && !isInference { m.ensureClaudeRemoteControlDefault(agent) + m.ensureClaudeAutoMemoryDefault(agent, sharedClaudeSettingsFile()) } if agent.Config.CavemanMode != "" { diff --git a/src/crux/config/agent_config.go b/src/crux/config/agent_config.go index 9f64cd4352..0865c51e6d 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 CLI auto-memory policy (#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,13 @@ 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 is the fleet agents.cli_memory policy as resolved for this + // agent (#17032). Never read from a per-agent block: EnabledAgents() + // stamps the fleet value onto every agent, because the CLI settings the + // policy seeds are shared across agents. + CLIMemory CLIMemoryConfig `yaml:"-" json:"-"` + 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..6ff483b38a --- /dev/null +++ b/src/crux/config/cli_memory.go @@ -0,0 +1,29 @@ +package config + +// CLIMemoryConfig is the fleet policy for the coding CLIs' own persistent +// auto-memory (#17032): Claude Code's ~/.claude/projects//memory, +// Codex's $CODEX_HOME/memories, Gemini's global ~/.gemini/GEMINI.md. A hive +// agent is a lane worker that should start every kick from the kick prompt, +// beads and the knowledge primer — not from inferences its CLI wrote down on +// an earlier kick. Written under agents.cli_memory; fleet-wide only, because +// the settings files the disable is seeded into are shared across agents. +// The zero value is the default. +type CLIMemoryConfig struct { + // AutoMemory leaves each CLI's auto-memory at the CLI's own default. + // False (the default) seeds each CLI's documented "auto-memory off" + // setting at launch. The seed is merge-only: a value already present in + // the CLI's settings — an operator's explicit choice — is never + // overwritten, so turning auto-memory back on after a seeded launch means + // setting this true AND removing the seeded key. + AutoMemory bool `yaml:"auto_memory,omitempty" json:"auto_memory,omitempty"` + // ClearOnKick removes the agent's own CLI memory store before every + // kick. Only stores inside a directory private to the agent are cleared; + // a store reached through a symlink into shared state is skipped (and + // logged once), so a clear never touches another agent's memory. + ClearOnKick bool `yaml:"clear_on_kick,omitempty" json:"clear_on_kick,omitempty"` +} + +// IsZero reports whether the block sets nothing, so the YAML encoder omits it. +func (c CLIMemoryConfig) IsZero() bool { + return !c.AutoMemory && !c.ClearOnKick +} diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index cca74fa301..5277e02210 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -85,6 +85,8 @@ The reference is organized into the sections below. Existing links to this page - [Self-reported issues](operator-reference/runtime-and-quota.md#self-reported-issues) - [Agent CLI session recycling](operator-reference/runtime-and-quota.md#agent-cli-session-recycling) + +- [Agent CLI auto-memory](operator-reference/runtime-and-quota.md#agent-cli-auto-memory) - [GitHub API quota](operator-reference/runtime-and-quota.md#github-api-quota) diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 0803386188..3c1e830681 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -229,7 +229,7 @@ The keys the agent runtime owns — the part of Hive being carved out as **Crux* | Struct | Embedded in | YAML keys (unchanged position) | |---|---|---| -| `AgentRuntimeConfig` (`pkg/config/agent_config.go`) | `Config` | `agents` (including the `agents.github_api_hourly_cap` scalar and the `agents.session_recycle` block), `backends`, `providers`, `tool_approval`, `agent_sandbox`, `turn` | +| `AgentRuntimeConfig` (`pkg/config/agent_config.go`) | `Config` | `agents` (including the `agents.github_api_hourly_cap` scalar and the `agents.session_recycle` and `agents.cli_memory` blocks), `backends`, `providers`, `tool_approval`, `agent_sandbox`, `turn` | | `AgentRuntimeGovernorConfig` (`pkg/config/agent_config.go`) | `GovernorConfig` | `governor.watchdog`, `governor.litellm`, `governor.vllm`, `governor.llm-d`, `governor.bob`, `governor.trajectory`, `governor.kick_limits`, `governor.gateways`, `governor.rotation`, `governor.provider_budget` | Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through field promotion; only composite literals name the embedded struct (`config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: …}}`). `pkg/config/testdata/agent_runtime_golden.{yaml,json}` pins the parse of a representative file so the boundary cannot drift the schema. diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index fb7109f510..ab9b06edf1 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -79,6 +79,49 @@ The sampled value is shown as **Session RSS** (with the session age and a `↻N` recycle count) in the agent detail panel. The log line is `agent session recycled` with `rss_mb`, `age` and `reason`. +## Agent CLI auto-memory + +Claude Code, Codex and Gemini CLI each keep their own persistent memory +across sessions, separate from the conversation `/clear` resets +(`agents..clear_on_kick`). A hive agent is a lane worker that should +start every kick from the kick prompt, its beads and the knowledge primer, +not from an inference its CLI wrote down on an earlier kick, so the fleet +policy turns that memory off by default: + +```yaml +agents: + cli_memory: # fleet-wide only; there is no per-agent override + auto_memory: false # default: seed each CLI's documented "auto-memory off" setting + clear_on_kick: false # true: remove the agent's own memory store before every kick +``` + +`auto_memory: false` is applied on every launch, merge-only: a value already +present is left alone, so an operator's explicit setting wins. + +| CLI | Setting hive seeds | Memory store `clear_on_kick` removes | +|---|---|---| +| Claude Code (`claude` and inference backends) | `"autoMemoryEnabled": false` in the shared `/data/home/.claude/settings.json` (interactive agents) or the inference agent's `~/.claude/settings.json` and `--settings` file | `$HOME/.claude/projects/*/memory` | +| Codex | `memories = false` in the `[features]` table of `$CODEX_HOME/config.toml` | `$CODEX_HOME/memories`, `$CODEX_HOME/memories_v2` | +| Gemini CLI | none: it documents no switch, it edits `GEMINI.md` files | `$HOME/.gemini/GEMINI.md` | +| Copilot CLI | none: Copilot Memory is stored on GitHub, not on disk; use `/memory off` or the account and repository settings | none | + +Setting `auto_memory: true` stops the seeding but does not remove a key an +earlier launch already wrote; delete `autoMemoryEnabled` from the Claude +settings file and `memories` from each `$CODEX_HOME/config.toml` to hand the +choice back to the CLI defaults. + +`clear_on_kick` only removes a store inside a directory private to the +agent, and runs the removal as the agent's own UID. A store reached through +a symlink into shared state is skipped, so a clear never removes another +agent's memory. The agent's HOME is shared when the agent runs as UID 0 or +under `HIVE_SHARED_AGENT_HOME=1`. Its `~/.claude` and `~/.gemini` are shared +while they are still symlinks to `/data/home`, which is today's layout for +interactive agents. In those cases the log shows +`cli_memory.clear_on_kick: not clearing a CLI memory store shared with other +agents` once per agent. Codex homes and inference-agent homes are per-agent, +so their stores are cleared. Each clear is logged as `cleared CLI memory +before kick` with the removed `paths`. + ## GitHub API quota Agents reach `api.github.com` through the Hive GitHub proxy, which injects the diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 6c7dd13751..5790415d62 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -230,6 +230,9 @@ ioscan: # for known agent names. New/custom agents should set these fields explicitly. agents: # github_api_hourly_cap: 300 # Per-agent charged GitHub API responses/hour through the proxy; 0 disables. + # cli_memory: # Fleet-wide CLI auto-memory policy (no per-agent override). + # auto_memory: false # false (default): seed each CLI's "auto-memory off" setting at launch. + # clear_on_kick: false # true: remove the agent's own CLI memory store before every kick. scanner: # id: scan-01 # Stable internal key (defaults to YAML key) enabled: true diff --git a/src/internal/settingsparity/settingsparity.go b/src/internal/settingsparity/settingsparity.go index 32d2aa8af1..017bbf34b7 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..b3380a8895 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/internal/tools/settingsparity/main_test.go b/src/internal/tools/settingsparity/main_test.go index febd8eced7..9dac367c9d 100644 --- a/src/internal/tools/settingsparity/main_test.go +++ b/src/internal/tools/settingsparity/main_test.go @@ -67,6 +67,8 @@ func TestRunMarkdown(t *testing.T) { want := strings.Join([]string{ "| key | type | default | exposed-in-UI | where | notes |", "| --- | --- | --- | --- | --- | --- |", + "| `agents.cli_memory.auto_memory` | `bool` | | none | | |", + "| `agents.cli_memory.clear_on_kick` | `bool` | | none | | |", "| `agents.github_api_hourly_cap` | `int` | | none | | may require restart or reconnect |", "| `agents.session_recycle.enabled` | `*bool` | | none | | |", "| `agents.session_recycle.max_age` | `time.Duration` | | none | | |", @@ -93,12 +95,12 @@ func TestRunJSON(t *testing.T) { if err := json.Unmarshal(stdout.Bytes(), &rows); err != nil { t.Fatalf("decode JSON output: %v\n%s", err, stdout.String()) } - if len(rows) != 9 { - t.Fatalf("got %d rows, want 9: %+v", len(rows), rows) + if len(rows) != 11 { + t.Fatalf("got %d rows, want 11: %+v", len(rows), rows) } want := row{Key: "hub.url", Type: "string", Default: "https://hub.example", UI: "read/write", Where: "Settings dialog reference", Notes: "may require restart or reconnect"} - if rows[6] != want { - t.Fatalf("rows[6] = %+v, want %+v", rows[6], want) + if rows[8] != want { + t.Fatalf("rows[8] = %+v, want %+v", rows[8], want) } } diff --git a/src/pkg/config/cli_memory_test.go b/src/pkg/config/cli_memory_test.go new file mode 100644 index 0000000000..df8461dbf0 --- /dev/null +++ b/src/pkg/config/cli_memory_test.go @@ -0,0 +1,96 @@ +package config + +import ( + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestCLIMemoryFleetBlockDecodesAndStampsAgents(t *testing.T) { + raw := ` +agents: + cli_memory: + auto_memory: true + clear_on_kick: true + scanner: + enabled: true + quality: + enabled: true + disabled: + enabled: false +` + var cfg Config + if err := yaml.NewDecoder(strings.NewReader(raw)).Decode(&cfg); err != nil { + t.Fatalf("Decode: %v", err) + } + want := CLIMemoryConfig{AutoMemory: true, ClearOnKick: true} + if cfg.AgentsCLIMemory != want { + t.Fatalf("fleet block = %+v, want %+v", cfg.AgentsCLIMemory, want) + } + if _, leaked := cfg.Agents["cli_memory"]; leaked { + t.Fatal("cli_memory leaked into the agents map as an agent") + } + enabled := cfg.EnabledAgents() + if len(enabled) != 2 { + t.Fatalf("enabled agents = %d, want 2", len(enabled)) + } + for name, ac := range enabled { + if ac.CLIMemory != want { + t.Fatalf("%s did not inherit the fleet block: %+v", name, ac.CLIMemory) + } + } +} + +func TestCLIMemoryAbsentBlockIsDefaultOff(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) + } + if got := cfg.EnabledAgents()["scanner"].CLIMemory; got != (CLIMemoryConfig{}) { + t.Fatalf("absent block resolved to %+v, want auto-memory off and no clear", got) + } +} + +func TestCLIMemoryInvalidBlockIsAnError(t *testing.T) { + var cfg Config + err := yaml.NewDecoder(strings.NewReader("agents:\n cli_memory:\n clear_on_kick: sometimes\n")).Decode(&cfg) + if err == nil || !strings.Contains(err.Error(), "agents.cli_memory") { + t.Fatalf("Decode err = %v, want an agents.cli_memory error", err) + } +} + +func TestCLIMemoryRoundTripsThroughMarshal(t *testing.T) { + cfg := Config{AgentRuntimeConfig: AgentRuntimeConfig{ + Agents: map[string]AgentConfig{"scanner": {Enabled: true}}, + AgentsCLIMemory: CLIMemoryConfig{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), "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 != (CLIMemoryConfig{ClearOnKick: true}) { + 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") + } + + // The default block encodes nothing under agents. + 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("default block encoded:\n%s", out) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 85a446d85d..ae8c5cdaf8 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 memoryNode yaml.Node + if err := memoryNode.Encode(c.AgentsCLIMemory); err != nil { + return nil, err + } + agents.Content = append(agents.Content, + &yaml.Node{Kind: yaml.ScalarNode, Value: "cli_memory"}, + &memoryNode) + } 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), and every agent carries the agents.cli_memory policy (#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,7 @@ func (c *Config) EnabledAgents() map[string]AgentConfig { fleet := c.AgentsSessionRecycle agent.SessionRecycle = &fleet } + agent.CLIMemory = c.AgentsCLIMemory 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..5c6cad331b 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -147,6 +147,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 # fleet CLI auto-memory policy (#17032); yaml-only +agents.cli_memory.clear_on_kick # fleet CLI auto-memory policy (#17032); yaml-only agents.github_api_hourly_cap # TODO #11854 agents.session_recycle.enabled # TODO #11854 agents.session_recycle.max_age # TODO #11854