From e6296e37c789ea03ad544c5ceb7876cb35db5b6b Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:30:01 -0500 Subject: [PATCH 1/4] =?UTF-8?q?=F0=9F=90=9B=20agents:=20give=20each=20agen?= =?UTF-8?q?t=20its=20own=20CLI=20memory=20=E2=80=94=20stop=20bridging=20.c?= =?UTF-8?q?laude/.gemini/.bob=20state=20to=20the=20shared=20home?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit interactiveHomeBridgeDirs symlinked ~/.claude, ~/.gemini and ~/.bob whole into /data/home, so every Claude Code agent on a hive read and rewrote the same projects//memory/MEMORY.md (and shared transcripts/todos), Gemini agents shared GEMINI.md and bob agents shared chat recordings. Make those three REAL per-agent directories following the .copilot pattern (#9444): only the login/settings entries are bridged (.credentials.json + settings.json for claude; antigravity-cli/, settings.json, oauth_creds.json, google_accounts.json, installation_id for gemini; settings.json + settings/ for bob). Legacy whole-dir bridges are retired on launch; nothing under /data/home is deleted — an existing shared memory store is logged once for operator review. Dashboard token scanners (claude_sessions_dir, bob_sessions_dir) now also walk /data/home/agents/*/.claude/projects and /.bob, attributing each per-agent tree to its owner, mirroring CopilotSessionTrees. Fixes #17031 Signed-off-by: Andrew Anderson --- .../fixed-agent-cli-memory-isolation.md | 1 + src/crux/agent/claude_remote_control.go | 8 +- src/crux/agent/interactive_home.go | 216 ++++++++++++++---- src/crux/agent/interactive_home_test.go | 149 +++++++++++- src/crux/agent/manager.go | 5 + src/docs/agent-configuration.md | 19 ++ src/docs/operator-reference/README.md | 2 +- src/docs/token-tracking.md | 4 +- src/pkg/tokens/agent_home_trees.go | 87 +++++++ src/pkg/tokens/agent_home_trees_test.go | 177 ++++++++++++++ src/pkg/tokens/bob_scanner.go | 26 ++- src/pkg/tokens/claude_scanner.go | 24 ++ src/pkg/tokens/collector.go | 45 ++-- src/pkg/tokens/copilot_scanner.go | 35 +-- src/pkg/tokens/error_streak.go | 8 +- 15 files changed, 696 insertions(+), 110 deletions(-) create mode 100644 changelog.d/fixed-agent-cli-memory-isolation.md create mode 100644 src/pkg/tokens/agent_home_trees.go create mode 100644 src/pkg/tokens/agent_home_trees_test.go diff --git a/changelog.d/fixed-agent-cli-memory-isolation.md b/changelog.d/fixed-agent-cli-memory-isolation.md new file mode 100644 index 0000000000..19eabad731 --- /dev/null +++ b/changelog.d/fixed-agent-cli-memory-isolation.md @@ -0,0 +1 @@ +- Each per-UID agent now gets its own real `~/.claude`, `~/.gemini` and `~/.bob` with only the login/settings files bridged to the shared home, so Claude Code auto-memory, transcripts and todos are no longer shared across every agent on a hive; the dashboard token scanners also walk the per-agent `/data/home/agents/*` trees (hivecommons/hive#17031). diff --git a/src/crux/agent/claude_remote_control.go b/src/crux/agent/claude_remote_control.go index d383a8e836..9057361e49 100644 --- a/src/crux/agent/claude_remote_control.go +++ b/src/crux/agent/claude_remote_control.go @@ -38,11 +38,11 @@ func claudeBypassConsentSeed() map[string]any { } // sharedClaudeSettingsFile is the userSettings file every interactive -// claude-backend agent reads: the per-agent homes symlink ~/.claude to -// sharedAgentHome/.claude (interactiveHomeBridgeDirs), so one file governs -// the whole fleet. +// claude-backend agent reads: each per-agent ~/.claude is a REAL directory +// (perAgentCLIHomes) whose settings.json symlinks to +// sharedAgentHome/.claude/settings.json, so one file governs the whole fleet. func sharedClaudeSettingsFile() string { - return filepath.Join(sharedAgentHome, ".claude", "settings.json") + return filepath.Join(sharedAgentHome, claudeHomeDirName, claudeSettingsFileName) } // ensureClaudeRemoteControlDefault re-asserts, before a claude-backend launch, diff --git a/src/crux/agent/interactive_home.go b/src/crux/agent/interactive_home.go index 8b419012cf..f492f1d171 100644 --- a/src/crux/agent/interactive_home.go +++ b/src/crux/agent/interactive_home.go @@ -43,14 +43,13 @@ func sharedAgentHomeForced() bool { // the dirs the entrypoint pre-creates group-writable and the permissions // watcher reconciles — sharing them is deliberate: // -// - .claude — holds .credentials.json (the shared OAuth token) and -// settings.json. One login authenticates the fleet. -// - .config / .codex / .bob / .gemini — per-tool auth+config the fleet -// shared safely before this change (none are rewritten wholesale by -// rename the way .claude.json is). .config is also $XDG_CONFIG_HOME: gh's -// hosts.yml and goose's config.yaml (provider keys) live there, so it -// stays shared on purpose — it is credential/config state, not session -// state. +// - .config / .codex — per-tool auth+config the fleet shared safely before +// the per-agent layout (neither is rewritten wholesale by rename the way +// .claude.json is, and neither holds per-session or memory state: codex +// runs under a per-agent CODEX_HOME, see setupCodexHome). .config is also +// $XDG_CONFIG_HOME: gh's hosts.yml and goose's config.yaml (provider keys) +// live there, so it stays shared on purpose — it is credential/config +// state, not session state. // - .cache — tool caches; per-agent copies would cold-start every cache on // every new agent for no isolation benefit. // @@ -59,14 +58,18 @@ func sharedAgentHomeForced() bool { // .npm (per-agent npm caches avoid the cross-UID EACCES collisions the shared // cache suffered — see installCavemanForAgent), .local (#6238 — the // $XDG_DATA_HOME / $XDG_STATE_HOME root; see setupAgentXDGDirs for why it is -// a REAL per-agent directory with one narrow bridge inside it), and .copilot -// (hivecommons/hive#9444 — bridging the whole directory shared -// .copilot/session-state, the CLI's per-run chat transcripts, across every -// per-UID agent: any agent's session directory became visible, and mtime- -// newest, through every OTHER agent's symlinked home. See setupCopilotHome -// for why it is a REAL per-agent directory with one narrow bridge inside it). +// a REAL per-agent directory with one narrow bridge inside it), and the CLI +// state directories .copilot (hivecommons/hive#9444), .claude, .gemini and +// .bob (hivecommons/hive#17031): each holds BOTH the fleet-shared login and +// the CLI's per-session transcripts and persistent cross-session memory. +// Bridging the whole directory made every agent's memory the SAME physical +// file — Claude Code's ~/.claude/projects//memory/MEMORY.md was read +// and rewritten by every claude agent on the hive, so one agent's false +// inference became fleet-wide and a reviewer read the coder's notes. See +// perAgentCLIHomes for the REAL per-agent directories with narrow, +// credential-only bridges inside them. var interactiveHomeBridgeDirs = []string{ - ".claude", ".config", ".codex", ".bob", ".gemini", + ".config", ".codex", ".cache", } @@ -77,6 +80,80 @@ var interactiveHomeBridgeDirs = []string{ // .copilot/session-state (hivecommons/hive#9444). const copilotConfigFileName = "config.json" +// perAgentCLIHome describes one CLI state directory under $HOME that is a +// REAL per-agent directory, with only the named entries bridged back to the +// same path under sharedAgentHome. The bridge list is the allowlist: it names +// exactly the login/settings files one operator sign-in must propagate to the +// fleet, and nothing else — transcripts, todos, history and auto-memory stay +// per agent (hivecommons/hive#17031). This is the contributor-container +// posture (CLAUDE_STAGE_ALLOWLIST in the Justfile, hivecommons/hive#7836) +// applied to the hive's own agents. +type perAgentCLIHome struct { + // dir is the directory name under $HOME (".claude"). + dir string + // bridges are the entries inside dir that symlink to the shared copy. + // Files are linked even when the shared target does not exist yet (the + // link goes live on first login, like interactiveHomeBridgeFiles); + // directories are linked only when the shared target exists, because a + // CLI's `mkdir -p` through a dangling directory symlink fails with EEXIST. + bridges []string + // memoryRel are the per-agent paths, relative to dir, that hold the + // CLI's persistent cross-session memory. Glob patterns are allowed. + // Used by the launch-time shared-memory warning and by the memory wipe. + memoryRel []string +} + +// perAgentCLIHomes are the CLI state directories provisioned by +// setupPerAgentCLIHomes. Order is irrelevant; each is independent. +// +// - .claude — .credentials.json is the shared OAuth token and settings.json +// the fleet-wide user settings hive itself seeds (claude_remote_control.go, +// and the auto-memory pin). projects/ (transcripts AND +// projects//memory/), todos/, history.jsonl, session-env/, +// shell-snapshots/ and statsig/ are per agent. +// - .gemini — antigravity-cli/ holds agy's OAuth token and onboarding cache +// (the entrypoint pre-creates and guards it); settings.json, +// oauth_creds.json, google_accounts.json and installation_id are the +// Gemini CLI login/settings. GEMINI.md (the CLI's saved global memory) and +// tmp/ (checkpoints, session logs) are per agent. +// - .bob — settings.json (bobshell 1.x) and settings/ (bobshell 2.x) carry +// the auth-method/provider pins ensureBobAuthSettings asserts; they must +// stay one file so the pin reaches every bob agent. tmp/ (chat +// recordings), installation_id and trustedFolders.json are per agent. +// - .copilot — config.json only (hivecommons/hive#9444). +var perAgentCLIHomes = []perAgentCLIHome{ + { + dir: claudeHomeDirName, + bridges: []string{claudeCredentialsFileName, claudeSettingsFileName}, + memoryRel: []string{filepath.Join("projects", "*", "memory")}, + }, + { + dir: geminiHomeDirName, + bridges: []string{"antigravity-cli", "settings.json", "oauth_creds.json", "google_accounts.json", "installation_id"}, + memoryRel: []string{geminiMemoryFileName}, + }, + { + dir: bobHomeDirName, + bridges: []string{"settings.json", "settings"}, + }, + { + dir: copilotHomeDirName, + bridges: []string{copilotConfigFileName}, + }, +} + +const ( + claudeHomeDirName = ".claude" + claudeCredentialsFileName = ".credentials.json" + claudeSettingsFileName = "settings.json" + geminiHomeDirName = ".gemini" + // geminiMemoryFileName is the Gemini CLI's global memory file, written by + // its save_memory tool / `/memory add` under ~/.gemini. + geminiMemoryFileName = "GEMINI.md" + bobHomeDirName = ".bob" + copilotHomeDirName = ".copilot" +) + // xdgDataHomeRel / xdgStateHomeRel are the XDG Base Directory defaults // relative to $HOME. They are exported EXPLICITLY (not left to the spec // default) so a CLI that resolves XDG_* before HOME, or a wrapper that @@ -195,7 +272,7 @@ func (m *Manager) setupInteractiveHome(agent *AgentProcess, backend string) { m.bridgeInteractiveHome(agent.Name, home) m.retireSharedGitConfigBridge(agent.Name, home) m.setupAgentXDGDirs(agent.Name, home, agent.UID) - m.setupCopilotHome(agent.Name, home, agent.UID) + m.setupPerAgentCLIHomes(agent.Name, home, agent.UID) m.seedClaudeSessionForAgent(agent, home) m.tightenInteractiveHome(agent.Name, home, agent.UID) m.sweepOrphanedClaudeTmp(agent.Name) @@ -294,46 +371,97 @@ func (m *Manager) setupAgentXDGDirs(agentName, home string, uid int) { } } -// setupCopilotHome makes $HOME/.copilot a REAL per-agent directory, retiring -// the legacy whole-directory symlink bridge to the shared /data/home/.copilot -// when one is found, then re-bridging only config.json back into the shared -// tree (hivecommons/hive#9444). +// setupPerAgentCLIHomes provisions every perAgentCLIHomes entry: makes +// $HOME/ a REAL per-agent directory, retiring the legacy whole-directory +// symlink bridge to the shared /data/home/ when one is found, then +// re-bridges only the named login/settings entries back into the shared tree. +// +// The pattern was introduced for .copilot (hivecommons/hive#9444): before it, +// .copilot rode interactiveHomeBridgeDirs as a bare symlink — correct for a +// directory that holds ONLY credential/config state, but Copilot CLI also +// keeps its per-run chat transcripts under .copilot/session-state, so every +// agent's session-state tree was the SAME physical directory. .claude, .gemini +// and .bob had the identical defect with higher stakes (hivecommons/hive#17031): +// Claude Code's auto-memory (projects//memory/MEMORY.md) is loaded into +// every session, so a shared ~/.claude meant one agent's one-off inference was +// recalled by every other agent on the hive, forever (it lives on the PVC). // -// Before this, .copilot rode interactiveHomeBridgeDirs as a bare symlink — -// same as .claude / .config — which is correct for a directory that holds -// ONLY credential/config state, but Copilot CLI also keeps its per-run chat -// transcripts under .copilot/session-state. Bridging the whole directory -// therefore made every agent's session-state tree the SAME physical -// directory: any agent's session, and its mtime, showed up while listing -// ANY other agent's .copilot/session-state — exactly the cross-contamination -// the issue reports (sec-check/quality sessions found under the scanner's -// home). Only config.json (the fleet-shared token map read by -// copilotConfigHasTokens / the auth probe) still needs to be shared; nothing -// else under .copilot does. -func (m *Manager) setupCopilotHome(agentName, home string, uid int) { - dir := filepath.Join(home, ".copilot") +// Every step is best-effort and idempotent: a real directory that already +// exists is kept (it may hold live per-agent state), only a SYMLINK is +// replaced, and nothing under the shared tree is moved or deleted — a +// pre-existing shared memory store is left in place and reported once. +func (m *Manager) setupPerAgentCLIHomes(agentName, home string, uid int) { + for _, spec := range perAgentCLIHomes { + m.setupPerAgentCLIHome(agentName, home, uid, spec) + } +} + +func (m *Manager) setupPerAgentCLIHome(agentName, home string, uid int, spec perAgentCLIHome) { + dir := filepath.Join(home, spec.dir) + shared := filepath.Join(sharedAgentHome, spec.dir) if info, err := os.Lstat(dir); err == nil && info.Mode()&os.ModeSymlink != 0 { - // Legacy whole-directory bridge from before this fix. Removing the - // link touches nothing it pointed at (the shared session-state and - // config.json live on, reachable by every other agent's own link - // until they are re-provisioned too). + // Legacy whole-directory bridge. Removing the link touches nothing it + // pointed at (the shared state lives on, reachable by every other + // agent's own link until they are re-provisioned too). if rerr := os.Remove(dir); rerr != nil { - m.logger.Warn("failed to retire legacy shared .copilot bridge; session-state stays shared for this agent", + m.logger.Warn("failed to retire legacy shared CLI home bridge; session state and memory stay shared for this agent", "agent", agentName, "link", dir, "error", rerr) return } - m.logger.Info("retired legacy shared .copilot bridge in favour of a per-agent session-state dir", - "agent", agentName, "home", home) + m.logger.Info("retired legacy shared CLI home bridge in favour of a per-agent directory", + "agent", agentName, "dir", dir, "shared", shared) + m.warnSharedCLIMemoryOnce(spec, shared) } if err := mkdirAllNoFollow(sharedAgentHome, dir, interactiveHomeDirMode); err != nil { - m.logger.Warn("failed to create per-agent .copilot dir", + m.logger.Warn("failed to create per-agent CLI home dir", "agent", agentName, "dir", dir, "error", err) return } m.ownAgentDir(agentName, dir, uid) - m.bridgeHomeEntry(agentName, - filepath.Join(dir, copilotConfigFileName), - filepath.Join(sharedAgentHome, ".copilot", copilotConfigFileName)) + for _, name := range spec.bridges { + link := filepath.Join(dir, name) + target := filepath.Join(shared, name) + if _, err := os.Stat(target); err != nil && isPerAgentCLIBridgeDir(spec.dir, name) { + // Absent target: a dangling FILE link goes live on first login; a + // dangling DIRECTORY link would make the CLI's own mkdir -p fail, + // so a directory-shaped bridge waits for the entrypoint to create it. + m.logger.Debug("shared CLI dir absent; per-agent bridge deferred", + "agent", agentName, "link", link, "target", target) + continue + } + m.bridgeHomeEntry(agentName, link, target) + } +} + +// perAgentCLIBridgeDirs names the bridge entries that are directories (not +// files) in the shared tree, so an absent target is deferred rather than +// linked dangling. Keyed by "/". +var perAgentCLIBridgeDirs = map[string]bool{ + geminiHomeDirName + "/antigravity-cli": true, + bobHomeDirName + "/settings": true, +} + +func isPerAgentCLIBridgeDir(dir, entry string) bool { + return perAgentCLIBridgeDirs[dir+"/"+entry] +} + +// warnSharedCLIMemoryOnce logs, once per process, that the shared CLI home +// still holds a persistent memory store that every agent used to read and +// write. The data is the operator's and is deliberately NOT deleted or moved; +// the log names the path so the operator can review or drain it +// (hivecommons/hive#17033) and then remove it by hand. +func (m *Manager) warnSharedCLIMemoryOnce(spec perAgentCLIHome, shared string) { + for _, rel := range spec.memoryRel { + matches, err := filepath.Glob(filepath.Join(shared, filepath.FromSlash(rel))) + if err != nil || len(matches) == 0 { + continue + } + m.sharedCLIMemoryWarnOnce.Do(func() { + m.logger.Warn("shared CLI home still holds a persistent memory store that was shared by every agent; it is no longer read by per-agent homes and was left in place for review", + "dir", shared, "memory", matches, "see", "hivecommons/hive#17031") + }) + return + } } // retireSharedGitConfigBridge removes the legacy ~/.gitconfig symlink that diff --git a/src/crux/agent/interactive_home_test.go b/src/crux/agent/interactive_home_test.go index 79cfde95d6..b2bed5233a 100644 --- a/src/crux/agent/interactive_home_test.go +++ b/src/crux/agent/interactive_home_test.go @@ -324,6 +324,147 @@ func TestSetupCopilotHome_RetiresLegacyBridgeAndIsolatesSessionState(t *testing. } } +// --- per-agent CLI homes: .claude / .gemini / .bob (hivecommons/hive#17031) -- + +// Regression for hivecommons/hive#17031: ~/.claude, ~/.gemini and ~/.bob were +// whole-directory bridges to the shared home, so Claude Code's auto-memory +// (projects//memory/MEMORY.md), its transcripts and todos — and Gemini's +// GEMINI.md and bob's chat recordings — were ONE physical tree for every +// agent. Each must now be a real per-agent directory with only the login / +// settings entries bridged. +func TestSetupInteractiveHome_CLIHomesArePerAgentWithCredentialBridges(t *testing.T) { + shared := withSharedAgentHome(t) + m := interactiveHomeTestManager(t) + ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}} + // Directory-shaped bridges only link when the shared target exists. + for _, d := range []string{ + filepath.Join(shared, ".gemini", "antigravity-cli"), + filepath.Join(shared, ".bob", "settings"), + } { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + + m.setupInteractiveHome(ap, "claude") + + home := interactiveHomePath("scanner") + for _, spec := range perAgentCLIHomes { + dir := filepath.Join(home, spec.dir) + if info, err := os.Lstat(dir); err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + t.Errorf("%s should be a real per-agent dir: info=%v err=%v", spec.dir, info, err) + continue + } + for _, name := range spec.bridges { + link := filepath.Join(dir, name) + target, err := os.Readlink(link) + if err != nil { + t.Errorf("%s/%s bridge missing: %v", spec.dir, name, err) + continue + } + if want := filepath.Join(shared, spec.dir, name); target != want { + t.Errorf("%s/%s -> %q, want %q", spec.dir, name, target, want) + } + } + } + // A memory write through the per-agent home lands in the per-agent tree, + // not the shared one. + mem := filepath.Join(home, ".claude", "projects", "-data-agents-scanner", "memory") + if err := os.MkdirAll(mem, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(mem, "MEMORY.md"), []byte("# notes"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(shared, ".claude", "projects")); !os.IsNotExist(err) { + t.Errorf("per-agent claude projects leaked into shared home (err=%v)", err) + } + // Nothing else inside .claude is bridged — todos/history stay per agent. + for _, name := range []string{"projects", "todos", "history.jsonl"} { + if info, err := os.Lstat(filepath.Join(home, ".claude", name)); err == nil && info.Mode()&os.ModeSymlink != 0 { + t.Errorf(".claude/%s must not be a bridge", name) + } + } +} + +func TestSetupPerAgentCLIHomes_RetiresLegacyBridgeAndKeepsSharedMemory(t *testing.T) { + shared := withSharedAgentHome(t) + m := interactiveHomeTestManager(t) + ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}} + home := interactiveHomePath("scanner") + + // Pre-#17031 layout: ~/.claude is a whole-directory bridge and the shared + // tree already holds a fleet-wide MEMORY.md plus the login. + sharedMem := filepath.Join(shared, ".claude", "projects", "-data-agents-coder", "memory") + if err := os.MkdirAll(sharedMem, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sharedMem, "MEMORY.md"), []byte("# stale"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(shared, ".claude", ".credentials.json"), []byte(`{}`), 0o600); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(home, 0o755); err != nil { + t.Fatal(err) + } + for _, d := range []string{".claude", ".gemini", ".bob"} { + if err := os.Symlink(filepath.Join(shared, d), filepath.Join(home, d)); err != nil { + t.Fatal(err) + } + } + + m.setupInteractiveHome(ap, "claude") + + for _, d := range []string{".claude", ".gemini", ".bob"} { + if info, err := os.Lstat(filepath.Join(home, d)); err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + t.Errorf("legacy %s bridge not retired: info=%v err=%v", d, info, err) + } + } + // The other agent's memory is NOT visible through this agent's home... + if _, err := os.Stat(filepath.Join(home, ".claude", "projects", "-data-agents-coder")); !os.IsNotExist(err) { + t.Errorf("shared memory leaked into per-agent .claude (err=%v)", err) + } + // ...but the shared store is left in place (operator data, see #17033). + if _, err := os.Stat(filepath.Join(sharedMem, "MEMORY.md")); err != nil { + t.Errorf("shared MEMORY.md was disturbed: %v", err) + } + // Login still reaches the shared credential. + if target, err := os.Readlink(filepath.Join(home, ".claude", ".credentials.json")); err != nil || target != filepath.Join(shared, ".claude", ".credentials.json") { + t.Errorf(".credentials.json bridge: target=%q err=%v", target, err) + } + // Directory-shaped bridges whose shared target is absent are deferred, not + // left dangling (a dangling dir symlink breaks the CLI's mkdir -p). + if _, err := os.Lstat(filepath.Join(home, ".bob", "settings")); !os.IsNotExist(err) { + t.Errorf(".bob/settings should not be a dangling bridge (err=%v)", err) + } + // Idempotent. + m.setupInteractiveHome(ap, "claude") + if info, err := os.Lstat(filepath.Join(home, ".claude")); err != nil || info.Mode()&os.ModeSymlink != 0 { + t.Errorf(".claude regressed to a bridge on re-provision: info=%v err=%v", info, err) + } +} + +func TestSetupPerAgentCLIHomes_KeepsExistingRealDir(t *testing.T) { + withSharedAgentHome(t) + m := interactiveHomeTestManager(t) + ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}} + home := interactiveHomePath("scanner") + live := filepath.Join(home, ".claude", "projects", "-data-agents-scanner", "memory", "MEMORY.md") + if err := os.MkdirAll(filepath.Dir(live), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(live, []byte("# mine"), 0o644); err != nil { + t.Fatal(err) + } + + m.setupInteractiveHome(ap, "claude") + + if got, err := os.ReadFile(live); err != nil || string(got) != "# mine" { + t.Errorf("live per-agent memory disturbed: %q err=%v", got, err) + } +} + func TestSetupAgentXDGDirs_KeepsExistingRealLocal(t *testing.T) { withSharedAgentHome(t) m := interactiveHomeTestManager(t) @@ -354,7 +495,7 @@ func TestSetupInteractiveHome_IdempotentAndRepairsStaleLink(t *testing.T) { home := interactiveHomePath("scanner") // Sabotage one bridge with a wrong target, then re-provision. - stale := filepath.Join(home, ".claude") + stale := filepath.Join(home, ".config") if err := os.Remove(stale); err != nil { t.Fatal(err) } @@ -363,7 +504,7 @@ func TestSetupInteractiveHome_IdempotentAndRepairsStaleLink(t *testing.T) { } m.setupInteractiveHome(ap, "claude") target, err := os.Readlink(stale) - if err != nil || target != filepath.Join(shared, ".claude") { + if err != nil || target != filepath.Join(shared, ".config") { t.Errorf("stale bridge not repaired: target=%q err=%v", target, err) } } @@ -374,7 +515,7 @@ func TestSetupInteractiveHome_NeverClobbersRealDir(t *testing.T) { ap := &AgentProcess{Name: "scanner", UID: 1001, Config: config.AgentConfig{Backend: "claude"}} home := interactiveHomePath("scanner") - realDir := filepath.Join(home, ".claude") + realDir := filepath.Join(home, ".config") if err := os.MkdirAll(realDir, 0o755); err != nil { t.Fatal(err) } @@ -387,7 +528,7 @@ func TestSetupInteractiveHome_NeverClobbersRealDir(t *testing.T) { info, err := os.Lstat(realDir) if err != nil || info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { - t.Fatalf("real .claude dir was clobbered: %v %v", info, err) + t.Fatalf("real .config dir was clobbered: %v %v", info, err) } if _, err := os.Stat(marker); err != nil { t.Errorf("marker lost: %v", err) diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 147b93d4d3..60939a994f 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -550,6 +550,11 @@ type Manager struct { rateLimitRelaunchMu sync.Mutex lastRateLimitRelaunch time.Time + // sharedCLIMemoryWarnOnce gates the one-per-process warning that the + // shared /data/home still holds a pre-isolation CLI memory store + // (hivecommons/hive#17031); see warnSharedCLIMemoryOnce. + sharedCLIMemoryWarnOnce sync.Once + // thrashMu guards thrash — its own mutex, NEVER m.mu: the breaker runs on // the output-capture goroutines, and taking m.mu there risks startup // re-entrancy deadlocks. diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index beee8386f9..606de479b1 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -609,6 +609,25 @@ Two rules of thumb: Only `POST /v1/messages` is translated into an OpenAI `/v1/chat/completions` call. The Claude CLI also talks to its Anthropic host for housekeeping — telemetry batches (`/api/event_logging/...`), error reports, `POST /v1/messages/count_tokens` — and none of that has a meaning to an OpenAI-compatible gateway; forwarding it used to cost a gateway `400 Missing required parameter: 'messages'` per call, charged against the provider's request rate limit (roughly two failures per real completion in practice). The translator and the MITM reroute now answer those locally: `count_tokens` returns a chars-based estimate, anything under `/api/` returns `{}`, and any other path is a 404 in Anthropic error shape with a `WARN` log line naming the method and path, so a new CLI endpoint shows up in the hive log rather than as gateway noise. Inference-routed `claude` sessions are additionally launched with `DISABLE_TELEMETRY=1`, `DISABLE_ERROR_REPORTING=1`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`, and `CLAUDE_CODE_AUTO_MODE_SERVER=0`; subscription sessions are not. The last one matters for Claude Code's [auto-mode classifier](https://code.claude.com/docs/en/auto-mode-classifier-billing): the CLI otherwise asks the inference host for a server-side safety verdict (`safeguards` field in, `safeguard_results` out) that an OpenAI-compatible gateway can never return, then halts the session on an interactive "this session isn't eligible because your requests go through 127.0.0.1:18444 … Enter to continue" notice. With the variable set the CLI runs its own classifier requests through the translator like any other call. Should the notice still appear (for example from a settings file that re-enables the server check), the lifetime prompt watcher presses Enter for it. +### Per-agent homes: what is shared and what is private + +Each per-UID agent runs with its own durable `HOME` under `/data/home/agents/`. "One login authenticates the fleet" is implemented by *bridging* — symlinks from the per-agent home back to the same path under the shared `/data/home` — and the bridge list is deliberately narrow: + +| Path under the agent home | Kind | Shared? | Why | +|---|---|---|---| +| `.config/`, `.codex/`, `.cache/` | whole directory | yes | credential/config state only (gh `hosts.yml`, goose keys, codex auth) and tool caches; codex session state lives under a per-agent `CODEX_HOME` | +| `.claude/.credentials.json`, `.claude/settings.json` | file | yes | the Claude OAuth token and the fleet-wide settings hive seeds | +| `.claude/projects/`, `.claude/todos/`, `.claude/history.jsonl` | per-agent | **no** | transcripts, todos, and Claude Code's auto-memory (`projects//memory/MEMORY.md`) | +| `.gemini/antigravity-cli/`, `.gemini/settings.json`, `oauth_creds.json`, `google_accounts.json`, `installation_id` | dir / file | yes | agy and Gemini CLI sign-in and settings | +| `.gemini/GEMINI.md`, `.gemini/tmp/` | per-agent | **no** | Gemini's saved memory and session checkpoints | +| `.bob/settings.json`, `.bob/settings/` | file / dir | yes | the auth-method/provider pins hive asserts for every bob agent | +| `.bob/tmp/`, `.bob/trustedFolders.json` | per-agent | **no** | chat recordings and folder trust | +| `.copilot/config.json` | file | yes | the Copilot CLI token map | +| `.copilot/session-state/` | per-agent | **no** | Copilot CLI transcripts | +| `.claude.json`, `.bash_history`, `.npm/`, `.local/`, `.gitconfig` | per-agent | **no** | contended session identity, shell history, npm cache, XDG data/state, git identity | + +Before [#17031](https://github.com/hivecommons/hive/issues/17031) `.claude`, `.gemini` and `.bob` were bridged whole, so every Claude Code agent on a hive read and rewrote the **same** `MEMORY.md` for the shared checkout path: one agent's one-off inference was recalled by every other agent, forever, and a reviewer loaded the coder's notes. 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). + 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/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 0803386188..517fc6cf9e 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -301,7 +301,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `knowledge.bead_synthesizer.publish` | Off (`enabled: false`). | Publishes synthesized facts into a repository through one PR on `hive/bead-synth-knowledge`: `enabled`, `repo` (empty = `project.primary_repo`), `path` (default `docs/knowledge/`; `.hive/knowledge/` is the alternative; relative, no `..`), `base_branch` (empty = repo default branch), `mode` (`pr` default or `commit`), `cadence` (`per_run` default or `daily`). ACMM L<=4 hives publish via PR only; `commit` is warned about and still opens a PR. See [knowledge-curator.md](../knowledge-curator.md#repository-publish-knowledgebead_synthesizerpublish). | | `variables.security.*` | Deny by default. | `allow_exec`, `allow_http`, and GitHub prompt-source allowlists are honored only from the trusted seed, not dashboard overlays. | | `agents..prompt_source` (size cap) | 96 KiB (`promptsrc.DefaultMaxPromptBytes`); `HIVE_PROMPT_SOURCE_MAX_BYTES` overrides it. | A fetched kick template over the cap is **rejected whole, not truncated** ([#12130](https://github.com/hivecommons/hive/issues/12130)): the kick uses the last successfully fetched copy if there is one, otherwise the ordinary `kick_template` → pack → convention → embedded-default chain, and the scheduler logs `prompt from GitHub exceeds size cap; REJECTED whole (not truncated), falling back` with `repo`, `path`, `size_bytes` and `cap_bytes`. Saving an agent whose source is over the cap fails in the dashboard with the same sizes rather than baking a cut-off policy. A half-policy is a policy with its closing rules missing; no remote policy is the safer failure. Every shipped template fits with >2× headroom (`TestShippedTemplatesFitUnderCap`). | -| `data.claude_sessions_dir` | `/data/home/.claude/projects` | Where the dashboard reads Claude Code session JSONL for per-agent token/cost accounting. Point it at the agents' real session directory if you relocate `HOME`. | +| `data.claude_sessions_dir` | `/data/home/.claude/projects` | Where the dashboard reads Claude Code session JSONL for per-agent token/cost accounting. When it has the canonical `/.claude/projects` shape the scan also covers every per-agent `/agents/*/.claude/projects` ([#17031](https://github.com/hivecommons/hive/issues/17031)); `data.bob_sessions_dir` and `data.copilot_sessions_dir` behave the same way. Point it at the agents' real session directory if you relocate `HOME`. | | `data.copilot_sessions_dir` | `/data/home/.copilot/session-state` | Same, for the Copilot CLI backend's session state. | ### Label-driven approval diff --git a/src/docs/token-tracking.md b/src/docs/token-tracking.md index b1da909811..01a9dc3b62 100644 --- a/src/docs/token-tracking.md +++ b/src/docs/token-tracking.md @@ -7,9 +7,9 @@ Hive tracks token usage for local budgeting, dashboard cost estimates, and hub-l The collector starts from `data.metrics_dir` and rescans every 30 seconds. It merges: - Hive JSONL session files in `data.metrics_dir` (`*.jsonl`) using the flat `SessionEntry` schema. -- Claude Code session JSONL under `data.claude_sessions_dir` when configured. It reads assistant `message.usage` blocks from recent files (30-day mtime window). +- Claude Code session JSONL under `data.claude_sessions_dir` when configured, plus every per-agent `/data/home/agents//.claude/projects` beside it (each per-UID agent's `~/.claude` is a real directory since [#17031](https://github.com/hivecommons/hive/issues/17031)); sessions in a per-agent tree are attributed to that agent when the project directory name carries no work-dir hint. It reads assistant `message.usage` blocks from recent files (30-day mtime window). - Copilot CLI `events.jsonl` under `data.copilot_sessions_dir` when configured. It reads `session.shutdown.modelMetrics` and avoids double-counting sessions already captured live by the proxy. -- Bob CLI chat recordings under `data.bob_sessions_dir` (default `/data/home/.bob`) when configured. It reads `tmp/*/chats/*.json`, maps Bob project hashes back to trusted agent folders, and records explicit `tokens` fields (falling back to content-size estimates only when a recording has no token data). +- Bob CLI chat recordings under `data.bob_sessions_dir` (default `/data/home/.bob`) and every per-agent `/data/home/agents//.bob` beside it, when configured. It reads `tmp/*/chats/*.json`, maps Bob project hashes back to trusted agent folders (falling back to the owning agent of a per-agent tree), and records explicit `tokens` fields (falling back to content-size estimates only when a recording has no token data). - In the optional Claude Managed Agents hosted path, `pkg/tokens/managed_agents_ledger.go` writes `managed-agents-*.jsonl` after deduplicating vendor `span.model_request_end` IDs. Its `managed-agents-ledger.json` sidecar keeps diff --git a/src/pkg/tokens/agent_home_trees.go b/src/pkg/tokens/agent_home_trees.go new file mode 100644 index 0000000000..5323286b46 --- /dev/null +++ b/src/pkg/tokens/agent_home_trees.go @@ -0,0 +1,87 @@ +package tokens + +import ( + "os" + "path/filepath" + "sort" + "strings" +) + +// perAgentHomesDirName is the directory under the shared HOME root that holds +// the per-agent HOMEs (crux/agent interactiveHomeRootName): each per-UID agent +// runs with HOME=/agents/. +const perAgentHomesDirName = "agents" + +// claudeProjectsRel is Claude Code's session+memory tree under a HOME. +const claudeProjectsRel = ".claude/projects" + +// bobHomeRel is bobshell's state tree under a HOME. +const bobHomeRel = ".bob" + +// SessionTree is one CLI session-state directory to scan plus the agent that +// owns it ("" for the legacy shared directory, where ownership is inferred +// per file). +type SessionTree struct { + Dir string + Agent string +} + +// perAgentSessionTrees returns sharedDir plus every per-agent tree beside it. +// rel is the CLI's state path under a HOME (".claude/projects"); the per-agent +// trees are derived only when sharedDir ends in rel, so an operator pointing +// the scanner at an arbitrary directory gets exactly that directory. +// +// Since hivecommons/hive#9444 (.copilot) and hivecommons/hive#17031 +// (.claude / .gemini / .bob) each per-UID agent's CLI state is a REAL +// directory under its own HOME rather than a symlink into the shared one, so +// a scan of the shared path alone would miss every new session. +func perAgentSessionTrees(sharedDir, rel string) []SessionTree { + if sharedDir == "" { + return nil + } + trees := []SessionTree{{Dir: sharedDir}} + rel = filepath.FromSlash(rel) + clean := filepath.Clean(sharedDir) + if !strings.HasSuffix(clean, string(filepath.Separator)+rel) { + return trees + } + home := filepath.Clean(strings.TrimSuffix(clean, string(filepath.Separator)+rel)) + matches, err := filepath.Glob(filepath.Join(home, perAgentHomesDirName, "*", rel)) + if err != nil { + return trees + } + sort.Strings(matches) + // The CLI's top-level state dir under the agent HOME (".claude" of + // ".claude/projects"): when it is still a legacy symlink bridge into the + // shared home, the match IS the shared tree and scanning it again would + // double-count every shared session under the wrong owner. + top := rel + if i := strings.Index(rel, string(filepath.Separator)); i >= 0 { + top = rel[:i] + } + for _, m := range matches { + agentHome := strings.TrimSuffix(m, string(filepath.Separator)+rel) + agent := filepath.Base(agentHome) + if agent == "" || agent == "." || strings.HasPrefix(agent, ".") { + continue + } + if info, err := os.Lstat(filepath.Join(agentHome, top)); err != nil || info.Mode()&os.ModeSymlink != 0 { + continue + } + trees = append(trees, SessionTree{Dir: m, Agent: agent}) + } + return trees +} + +// ClaudeSessionTrees returns the configured claude_sessions_dir plus every +// per-agent /agents//.claude/projects beside it +// (hivecommons/hive#17031). +func ClaudeSessionTrees(sharedDir string) []SessionTree { + return perAgentSessionTrees(sharedDir, claudeProjectsRel) +} + +// BobSessionTrees returns the configured bob_sessions_dir plus every +// per-agent /agents//.bob beside it (hivecommons/hive#17031). +func BobSessionTrees(sharedDir string) []SessionTree { + return perAgentSessionTrees(sharedDir, bobHomeRel) +} diff --git a/src/pkg/tokens/agent_home_trees_test.go b/src/pkg/tokens/agent_home_trees_test.go new file mode 100644 index 0000000000..13716cae7c --- /dev/null +++ b/src/pkg/tokens/agent_home_trees_test.go @@ -0,0 +1,177 @@ +package tokens + +import ( + "os" + "path/filepath" + "strconv" + "testing" + "time" +) + +// Since hivecommons/hive#17031 every per-UID agent's ~/.claude and ~/.bob are +// REAL directories under /agents/, not bridges into the shared +// home, so the dashboard's claude_sessions_dir / bob_sessions_dir scans must +// also walk the per-agent trees or every new session goes uncounted. + +func TestClaudeSessionTrees_DerivesPerAgentHomes(t *testing.T) { + home := t.TempDir() + shared := filepath.Join(home, ".claude", "projects") + for _, a := range []string{"scanner", "reviewer", ".hidden"} { + if err := os.MkdirAll(filepath.Join(home, "agents", a, ".claude", "projects"), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(shared, 0o755); err != nil { + t.Fatal(err) + } + // A per-agent home still carrying the legacy whole-directory bridge + // resolves to the shared tree and must not be scanned a second time + // (and under the wrong owner); a home with no .claude must not appear. + if err := os.MkdirAll(filepath.Join(home, "agents", "legacy"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(home, ".claude"), filepath.Join(home, "agents", "legacy", ".claude")); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(home, "agents", "inference-only"), 0o755); err != nil { + t.Fatal(err) + } + + trees := ClaudeSessionTrees(shared) + if len(trees) != 3 { + t.Fatalf("trees = %+v, want shared + reviewer + scanner", trees) + } + if trees[0].Dir != shared || trees[0].Agent != "" { + t.Errorf("trees[0] = %+v, want shared dir with no agent", trees[0]) + } + if trees[1].Agent != "reviewer" || trees[2].Agent != "scanner" { + t.Errorf("per-agent trees = %+v", trees[1:]) + } + if trees[2].Dir != filepath.Join(home, "agents", "scanner", ".claude", "projects") { + t.Errorf("scanner dir = %q", trees[2].Dir) + } +} + +func TestClaudeSessionTrees_NonCanonicalDirIsSharedOnly(t *testing.T) { + if got := ClaudeSessionTrees(""); got != nil { + t.Errorf("empty dir → %+v, want nil", got) + } + got := ClaudeSessionTrees("/some/custom/projects") + if len(got) != 1 || got[0].Dir != "/some/custom/projects" { + t.Errorf("custom dir → %+v", got) + } +} + +func TestBobSessionTrees_DerivesPerAgentHomes(t *testing.T) { + home := t.TempDir() + shared := filepath.Join(home, ".bob") + for _, a := range []string{"quality", "scanner"} { + if err := os.MkdirAll(filepath.Join(home, "agents", a, ".bob"), 0o755); err != nil { + t.Fatal(err) + } + } + trees := BobSessionTrees(shared) + if len(trees) != 3 || trees[0].Dir != shared || trees[1].Agent != "quality" || trees[2].Agent != "scanner" { + t.Fatalf("trees = %+v", trees) + } +} + +// A Claude session in a per-agent tree is attributed to that agent even when +// its project directory name encodes no agent work dir (a worktree cwd), and +// the dashboard sees sessions from BOTH the shared and per-agent trees. +func TestCollectorScansPerAgentClaudeHomes(t *testing.T) { + metricsDir := t.TempDir() + home := t.TempDir() + shared := filepath.Join(home, ".claude", "projects") + if err := os.MkdirAll(shared, 0o755); err != nil { + t.Fatal(err) + } + now := time.Now().UTC().Format(time.RFC3339) + line := func(in, out int64) string { + return `{"type":"human","timestamp":"` + now + `","message":{"text":"please continue"}}` + "\n" + + `{"type":"assistant","timestamp":"` + now + `","message":{"model":"claude-opus-5.5","usage":{"input_tokens":` + + strconv.FormatInt(in, 10) + `,"output_tokens":` + strconv.FormatInt(out, 10) + `}}}` + "\n" + } + write := func(projectsDir, proj, session, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(projectsDir, proj), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(projectsDir, proj, session+".jsonl"), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + // Legacy shared tree: agent from the project-dir path hint. + write(shared, "-data-agents-coder", "c1", line(100, 10)) + // Per-agent reviewer tree, worktree cwd: no path hint and no keyword, so + // the home it sits in owns it (the shared scan would have said "unknown"). + write(filepath.Join(home, "agents", "reviewer", ".claude", "projects"), "-home-wt-pr-1", "r1", line(200, 20)) + // Per-agent scanner tree, canonical cwd: path hint and owner agree. + write(filepath.Join(home, "agents", "scanner", ".claude", "projects"), "-data-agents-scanner", "s1", line(300, 30)) + + c := NewCollector(metricsDir, testLogger()) + c.SetPersistPath(filepath.Join(metricsDir, "token-summary.json")) + c.SetClaudeSessionsDir(shared) + c.scan() + + summary := c.Summary() + if summary == nil { + t.Fatal("nil summary") + } + want := map[string]int64{"coder": 110, "reviewer": 220, "scanner": 330} + for agent, tokens := range want { + if got := summary.ByAgent[agent]; got != tokens { + t.Errorf("ByAgent[%s] = %d, want %d (ByAgent=%v)", agent, got, tokens, summary.ByAgent) + } + } +} + +// A bob recording in a per-agent ~/.bob whose project hash is not in that +// tree's trustedFolders.json is attributed to the tree owner, not "bob", and +// its error streak is reported under that agent. +func TestCollectorScansPerAgentBobHomes(t *testing.T) { + metricsDir := t.TempDir() + home := t.TempDir() + shared := filepath.Join(home, ".bob") + if err := os.MkdirAll(shared, 0o755); err != nil { + t.Fatal(err) + } + now := time.Now() + base := now.Add(-2 * time.Hour) + qualityHome := filepath.Join(home, "agents", "quality", ".bob") + if err := os.MkdirAll(qualityHome, 0o755); err != nil { + t.Fatal(err) + } + writeBobChat(t, qualityHome, "/home/wt/pr-7", "s1", map[string]any{ + "sessionId": "s1", + "startTime": ts(base, 0), + "lastUpdated": ts(base, 90), + "messages": []map[string]any{ + {"type": "user", "timestamp": ts(base, 0), "content": "kick 1"}, + {"type": "bob-shell", "timestamp": ts(base, 1), "model": "premium", + "tokens": map[string]int64{"input": 100, "output": 20}}, + {"type": "user", "timestamp": ts(base, 30), "content": "kick 2"}, + {"type": "bob-shell", "timestamp": ts(base, 31), "model": "premium", + "tokens": map[string]int64{"input": 0, "output": 0}}, + }, + }) + + c := NewCollector(metricsDir, testLogger()) + c.SetPersistPath(filepath.Join(metricsDir, "token-summary.json")) + c.SetBobSessionsDir(shared) + c.scan() + + summary := c.Summary() + if summary == nil { + t.Fatal("nil summary") + } + if got := summary.ByAgent["quality"]; got != 120 { + t.Errorf("ByAgent[quality] = %d, want 120 (ByAgent=%v)", got, summary.ByAgent) + } + if _, leaked := summary.ByAgent[bobUnknownAgent]; leaked { + t.Errorf("per-agent recording fell back to %q: %v", bobUnknownAgent, summary.ByAgent) + } + if streaks := c.AgentErrorStreaks(); streaks["quality"] != 1 { + t.Errorf("AgentErrorStreaks = %v, want quality:1", streaks) + } +} diff --git a/src/pkg/tokens/bob_scanner.go b/src/pkg/tokens/bob_scanner.go index a827270338..2fec6cfd22 100644 --- a/src/pkg/tokens/bob_scanner.go +++ b/src/pkg/tokens/bob_scanner.go @@ -95,10 +95,19 @@ const maxBobSessionAge = 30 * 24 * time.Hour // given directory (typically /data/home/.bob or ~/.bob) and returns an // AggregateSummary. It walks tmp/*/chats/*.json looking for session recordings. func ScanBobSessionsWithLogger(bobHomeDir string, logger *slog.Logger) (*AggregateSummary, error) { - return scanBobSessions(bobHomeDir, logger) + return scanBobSessions(bobHomeDir, "", logger) } -func scanBobSessions(bobHomeDir string, logger *slog.Logger) (*AggregateSummary, error) { +// ScanBobSessionTree is ScanBobSessionsWithLogger for one tree whose owner is +// already known: defaultAgent, when non-empty, is the agent whose per-agent +// HOME holds bobHomeDir (hivecommons/hive#17031) and replaces the generic +// "bob" fallback for recordings whose project hash is not in that tree's +// trustedFolders.json. +func ScanBobSessionTree(bobHomeDir, defaultAgent string, logger *slog.Logger) (*AggregateSummary, error) { + return scanBobSessions(bobHomeDir, defaultAgent, logger) +} + +func scanBobSessions(bobHomeDir, defaultAgent string, logger *slog.Logger) (*AggregateSummary, error) { agg := &AggregateSummary{ ByAgent: make(map[string]int64), ByModel: make(map[string]int64), @@ -211,7 +220,7 @@ func scanBobSessions(bobHomeDir string, logger *slog.Logger) (*AggregateSummary, if projectHash == "" { projectHash = extractBobProjectHash(path) } - agentName := bobAgentName(projectHash, agentsByHash) + agentName := bobAgentName(projectHash, agentsByHash, defaultAgent) agg.TotalTokens += total agg.TotalMessages += messageCount agg.SessionCount++ @@ -338,11 +347,18 @@ func hexLower(b []byte) string { return string(out) } -func bobAgentName(projectHash string, agentsByHash map[string]string) string { +// bobUnknownAgent is the attribution for a recording whose project hash is +// not trusted-folder-mapped and whose tree has no known owner. +const bobUnknownAgent = "bob" + +func bobAgentName(projectHash string, agentsByHash map[string]string, defaultAgent string) string { if agent := agentsByHash[strings.TrimSpace(projectHash)]; agent != "" { return agent } - return "bob" + if defaultAgent != "" { + return defaultAgent + } + return bobUnknownAgent } func extractBobProjectHash(path string) string { diff --git a/src/pkg/tokens/claude_scanner.go b/src/pkg/tokens/claude_scanner.go index f3946e2128..ebd1b1306d 100644 --- a/src/pkg/tokens/claude_scanner.go +++ b/src/pkg/tokens/claude_scanner.go @@ -313,12 +313,33 @@ func HiveAgentDetector(filePath string) func(string) string { } } +// treeAgentDetector is HiveAgentDetector with the tree owner as the fallback +// instead of the keyword guess: the path hint still wins when present (a +// session started from another agent's work dir is attributed there). +func treeAgentDetector(filePath, defaultAgent string) func(string) string { + return func(string) string { + if agent := AgentFromTmuxEnv(filePath); agent != "" { + return agent + } + return defaultAgent + } +} + // ScanClaudeSessionsWithPathDetection reads Claude Code's native session JSONL // files from the given projects directory (typically ~/.claude/projects), // using the file path to help determine which agent owns each session. It // scans all *.jsonl files in all subdirectories (project hashes), plus any // subagent files in */subagents/*.jsonl. func ScanClaudeSessionsWithPathDetection(projectsDir string) (*AggregateSummary, error) { + return ScanClaudeSessionTree(projectsDir, "") +} + +// ScanClaudeSessionTree is ScanClaudeSessionsWithPathDetection for one tree +// whose owner is already known: defaultAgent, when non-empty, is the agent +// whose per-agent HOME holds projectsDir (hivecommons/hive#17031) and is used +// whenever the project-directory name does not itself encode an agent work +// dir, instead of the keyword guess from the first user message. +func ScanClaudeSessionTree(projectsDir, defaultAgent string) (*AggregateSummary, error) { agg := &AggregateSummary{ ByAgent: make(map[string]int64), ByModel: make(map[string]int64), @@ -354,6 +375,9 @@ func ScanClaudeSessionsWithPathDetection(projectsDir string) (*AggregateSummary, } detector := HiveAgentDetector(file) + if defaultAgent != "" { + detector = treeAgentDetector(file, defaultAgent) + } summary, err := parseClaudeSessionFile(file, detector) if err != nil || summary == nil || summary.TotalTokens == 0 { continue diff --git a/src/pkg/tokens/collector.go b/src/pkg/tokens/collector.go index d2d98d8181..3cb0a0ca7a 100644 --- a/src/pkg/tokens/collector.go +++ b/src/pkg/tokens/collector.go @@ -338,12 +338,17 @@ func (c *Collector) scan() { c.mergeClineUsage(agg) if c.claudeSessionsDir != "" { - claudeAgg, err := ScanClaudeSessionsWithPathDetection(c.claudeSessionsDir) - if err != nil { - c.logger.Warn("claude session scan failed", "error", err) - diag.LastClaudeScanError = err.Error() - } else if claudeAgg != nil && claudeAgg.SessionCount > 0 { - MergeAggregates(agg, claudeAgg) + // Shared tree plus every per-agent ~/.claude/projects: since + // hivecommons/hive#17031 each agent's transcripts live under its own + // HOME, so the shared path alone would miss every new session. + for _, tree := range ClaudeSessionTrees(c.claudeSessionsDir) { + claudeAgg, err := ScanClaudeSessionTree(tree.Dir, tree.Agent) + if err != nil { + c.logger.Warn("claude session scan failed", "dir", tree.Dir, "error", err) + diag.LastClaudeScanError = err.Error() + } else if claudeAgg != nil && claudeAgg.SessionCount > 0 { + MergeAggregates(agg, claudeAgg) + } } } @@ -369,18 +374,26 @@ func (c *Collector) scan() { } if c.bobSessionsDir != "" { - bobAgg, err := ScanBobSessionsWithLogger(c.bobSessionsDir, c.logger) - if err != nil { - c.logger.Warn("bob session scan failed", "error", err) - diag.LastBobScanError = err.Error() - } else if bobAgg != nil && bobAgg.SessionCount > 0 { - MergeAggregates(agg, bobAgg) - } // Per-agent consecutive model-call failure streaks (#5577/#5338), - // derived from the same recordings this scan just walked. Always - // stored non-nil after a scan, so AgentErrorStreaks can distinguish + // derived from the same recordings this scan walks. Always stored + // non-nil after a scan, so AgentErrorStreaks can distinguish // "measured, none failing" (empty) from "never scanned" (nil). - streaks := BobAgentErrorStreaks(c.bobSessionsDir, time.Now()) + streaks := make(map[string]int) + now := time.Now() + for _, tree := range BobSessionTrees(c.bobSessionsDir) { + bobAgg, err := ScanBobSessionTree(tree.Dir, tree.Agent, c.logger) + if err != nil { + c.logger.Warn("bob session scan failed", "dir", tree.Dir, "error", err) + diag.LastBobScanError = err.Error() + } else if bobAgg != nil && bobAgg.SessionCount > 0 { + MergeAggregates(agg, bobAgg) + } + for agent, n := range BobAgentErrorStreaksForTree(tree.Dir, tree.Agent, now) { + if n > streaks[agent] { + streaks[agent] = n + } + } + } c.mu.Lock() c.errorStreaks = streaks c.mu.Unlock() diff --git a/src/pkg/tokens/copilot_scanner.go b/src/pkg/tokens/copilot_scanner.go index 895225949b..cfef6ff557 100644 --- a/src/pkg/tokens/copilot_scanner.go +++ b/src/pkg/tokens/copilot_scanner.go @@ -5,7 +5,6 @@ import ( "encoding/json" "os" "path/filepath" - "sort" "strings" "time" ) @@ -109,16 +108,9 @@ type CopilotScanOptions struct { // copilotSessionStateRel is the Copilot CLI session-state path under a HOME. const copilotSessionStateRel = ".copilot/session-state" -// copilotPerAgentHomesDirName is the directory under the shared HOME root that -// holds the per-agent HOMEs (pkg/agent interactiveHomeRootName). -const copilotPerAgentHomesDirName = "agents" - // CopilotSessionTree is one Copilot session-state directory to scan plus the // agent that owns it ("" for the legacy shared directory). -type CopilotSessionTree struct { - Dir string - Agent string -} +type CopilotSessionTree = SessionTree // CopilotSessionTrees returns the configured shared session-state directory // plus every per-agent tree beside it. Since hivecommons/hive#9444 each @@ -129,30 +121,7 @@ type CopilotSessionTree struct { // The per-agent trees are derived only when sharedDir has the canonical // /.copilot/session-state shape. func CopilotSessionTrees(sharedDir string) []CopilotSessionTree { - if sharedDir == "" { - return nil - } - trees := []CopilotSessionTree{{Dir: sharedDir}} - rel := filepath.FromSlash(copilotSessionStateRel) - if !strings.HasSuffix(filepath.Clean(sharedDir), rel) { - return trees - } - home := strings.TrimSuffix(filepath.Clean(sharedDir), rel) - home = filepath.Clean(home) - matches, err := filepath.Glob(filepath.Join(home, copilotPerAgentHomesDirName, "*", rel)) - if err != nil { - return trees - } - sort.Strings(matches) - for _, m := range matches { - agentHome := strings.TrimSuffix(m, string(filepath.Separator)+rel) - agent := filepath.Base(agentHome) - if agent == "" || agent == "." || strings.HasPrefix(agent, ".") { - continue - } - trees = append(trees, CopilotSessionTree{Dir: m, Agent: agent}) - } - return trees + return perAgentSessionTrees(sharedDir, copilotSessionStateRel) } // ScanCopilotSessions reads Copilot CLI session files from one session-state diff --git a/src/pkg/tokens/error_streak.go b/src/pkg/tokens/error_streak.go index def673e23e..9ba0728251 100644 --- a/src/pkg/tokens/error_streak.go +++ b/src/pkg/tokens/error_streak.go @@ -73,6 +73,12 @@ type bobTurn struct { // result is always non-nil (an empty map means "measured, no streaks") so // callers can tell a clean fleet from a scan that never ran. func BobAgentErrorStreaks(bobHomeDir string, now time.Time) map[string]int { + return BobAgentErrorStreaksForTree(bobHomeDir, "", now) +} + +// BobAgentErrorStreaksForTree is BobAgentErrorStreaks for one tree whose +// owner is already known (see ScanBobSessionTree). +func BobAgentErrorStreaksForTree(bobHomeDir, defaultAgent string, now time.Time) map[string]int { out := make(map[string]int) if bobHomeDir == "" { return out @@ -120,7 +126,7 @@ func BobAgentErrorStreaks(bobHomeDir string, now time.Time) map[string]int { if projectHash == "" { projectHash = extractBobProjectHash(path) } - agentName := bobAgentName(projectHash, agentsByHash) + agentName := bobAgentName(projectHash, agentsByHash, defaultAgent) rec := sessRec{agent: agentName, start: bobSessionFirstActive(sess)} for i := range sess.Messages { From 588c73fea54a9b214060a061f8ecbaa2119e711f Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:42:29 -0500 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=93=96=20agents:=20correct=20the=20sh?= =?UTF-8?q?ared-memory=20wording=20=E2=80=94=20MEMORY.md=20is=20per-agent?= =?UTF-8?q?=20by=20cwd,=20the=20tree=20is=20what=20was=20shared?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude keys auto-memory by cwd (/data/agents/), so MEMORY.md was never one physical file; the user-level CLAUDE.md, history.jsonl and todos/ were. The bridged tree being readable and writable by every agent is the bug. Signed-off-by: Andrew Anderson --- changelog.d/fixed-agent-cli-memory-isolation.md | 2 +- src/crux/agent/interactive_home.go | 17 ++++++++++------- src/crux/agent/interactive_home_test.go | 2 +- src/docs/agent-configuration.md | 4 ++-- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/changelog.d/fixed-agent-cli-memory-isolation.md b/changelog.d/fixed-agent-cli-memory-isolation.md index 19eabad731..b08b1b009c 100644 --- a/changelog.d/fixed-agent-cli-memory-isolation.md +++ b/changelog.d/fixed-agent-cli-memory-isolation.md @@ -1 +1 @@ -- Each per-UID agent now gets its own real `~/.claude`, `~/.gemini` and `~/.bob` with only the login/settings files bridged to the shared home, so Claude Code auto-memory, transcripts and todos are no longer shared across every agent on a hive; the dashboard token scanners also walk the per-agent `/data/home/agents/*` trees (hivecommons/hive#17031). +- Each per-UID agent now gets its own real `~/.claude`, `~/.gemini` and `~/.bob` with only the login/settings files bridged to the shared home, so Claude Code auto-memory, transcripts, user-level CLAUDE.md, history and todos are no longer readable and writable by every agent on a hive; the dashboard token scanners also walk the per-agent `/data/home/agents/*` trees (hivecommons/hive#17031). diff --git a/src/crux/agent/interactive_home.go b/src/crux/agent/interactive_home.go index f492f1d171..07621a1298 100644 --- a/src/crux/agent/interactive_home.go +++ b/src/crux/agent/interactive_home.go @@ -62,10 +62,12 @@ func sharedAgentHomeForced() bool { // state directories .copilot (hivecommons/hive#9444), .claude, .gemini and // .bob (hivecommons/hive#17031): each holds BOTH the fleet-shared login and // the CLI's per-session transcripts and persistent cross-session memory. -// Bridging the whole directory made every agent's memory the SAME physical -// file — Claude Code's ~/.claude/projects//memory/MEMORY.md was read -// and rewritten by every claude agent on the hive, so one agent's false -// inference became fleet-wide and a reviewer read the coder's notes. See +// Bridging the whole directory put every agent's state in ONE tree that any +// agent could read and rewrite: Claude Code's user-level ~/.claude/CLAUDE.md, +// history.jsonl and todos/ were a single shared copy, and each agent's +// auto-memory (~/.claude/projects/-data-agents-/memory/MEMORY.md — +// keyed by cwd, so per-agent by path) sat beside every other agent's, +// writable by all of them (and by anything running as the shared uid). See // perAgentCLIHomes for the REAL per-agent directories with narrow, // credential-only bridges inside them. var interactiveHomeBridgeDirs = []string{ @@ -382,9 +384,10 @@ func (m *Manager) setupAgentXDGDirs(agentName, home string, uid int) { // keeps its per-run chat transcripts under .copilot/session-state, so every // agent's session-state tree was the SAME physical directory. .claude, .gemini // and .bob had the identical defect with higher stakes (hivecommons/hive#17031): -// Claude Code's auto-memory (projects//memory/MEMORY.md) is loaded into -// every session, so a shared ~/.claude meant one agent's one-off inference was -// recalled by every other agent on the hive, forever (it lives on the PVC). +// Claude Code's user-level CLAUDE.md, history.jsonl and todos/ were one +// shared copy, and every agent's cwd-keyed auto-memory +// (projects/-data-agents-/memory/MEMORY.md) lived in a tree any other +// agent could read or rewrite, forever (it lives on the PVC). // // Every step is best-effort and idempotent: a real directory that already // exists is kept (it may hold live per-agent state), only a SYMLINK is diff --git a/src/crux/agent/interactive_home_test.go b/src/crux/agent/interactive_home_test.go index b2bed5233a..dd9ef8e4d7 100644 --- a/src/crux/agent/interactive_home_test.go +++ b/src/crux/agent/interactive_home_test.go @@ -394,7 +394,7 @@ func TestSetupPerAgentCLIHomes_RetiresLegacyBridgeAndKeepsSharedMemory(t *testin home := interactiveHomePath("scanner") // Pre-#17031 layout: ~/.claude is a whole-directory bridge and the shared - // tree already holds a fleet-wide MEMORY.md plus the login. + // tree already holds another agent's MEMORY.md plus the login. sharedMem := filepath.Join(shared, ".claude", "projects", "-data-agents-coder", "memory") if err := os.MkdirAll(sharedMem, 0o755); err != nil { t.Fatal(err) diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 606de479b1..37cbcd875f 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -617,7 +617,7 @@ Each per-UID agent runs with its own durable `HOME` under `/data/home/agents//memory/MEMORY.md`) | +| `.claude/projects/`, `.claude/todos/`, `.claude/history.jsonl` | per-agent | **no** | transcripts, todos, and Claude Code's auto-memory (`projects/-data-agents-/memory/MEMORY.md`, keyed by the agent's cwd) | | `.gemini/antigravity-cli/`, `.gemini/settings.json`, `oauth_creds.json`, `google_accounts.json`, `installation_id` | dir / file | yes | agy and Gemini CLI sign-in and settings | | `.gemini/GEMINI.md`, `.gemini/tmp/` | per-agent | **no** | Gemini's saved memory and session checkpoints | | `.bob/settings.json`, `.bob/settings/` | file / dir | yes | the auth-method/provider pins hive asserts for every bob agent | @@ -626,7 +626,7 @@ 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). 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. From 8bc78908dca340b145f76892a748b88fea6383b0 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:44:59 -0500 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=8C=B1=20agents:=20keep=20manager.go?= =?UTF-8?q?=20inside=20its=20file-size=20ratchet=20baseline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/crux/agent/manager.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 60939a994f..6110fdf159 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -547,13 +547,9 @@ type Manager struct { // rateLimitRelaunchMu guards lastRateLimitRelaunch, the fleet-wide clock // that spaces rate-limit relaunches (rateLimitRelaunchFleetSpacing). Its // own mutex: the pane pollers that consult it must not take m.mu. - rateLimitRelaunchMu sync.Mutex - lastRateLimitRelaunch time.Time - - // sharedCLIMemoryWarnOnce gates the one-per-process warning that the - // shared /data/home still holds a pre-isolation CLI memory store - // (hivecommons/hive#17031); see warnSharedCLIMemoryOnce. - sharedCLIMemoryWarnOnce sync.Once + rateLimitRelaunchMu sync.Mutex + lastRateLimitRelaunch time.Time + sharedCLIMemoryWarnOnce sync.Once // see warnSharedCLIMemoryOnce (hivecommons/hive#17031) // thrashMu guards thrash — its own mutex, NEVER m.mu: the breaker runs on // the output-capture goroutines, and taking m.mu there risks startup From caa9bd8c435a0876d086711a0ffd46ccd979a186 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:54:29 -0500 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=93=96=20agents:=20bring=20agent-know?= =?UTF-8?q?ledge-and-memory.md=20in=20line=20with=20per-agent=20CLI=20home?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/docs/agent-knowledge-and-memory.md | 61 +++++++++++++++----------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/src/docs/agent-knowledge-and-memory.md b/src/docs/agent-knowledge-and-memory.md index 5bc6bd08a3..a35f10b5ff 100644 --- a/src/docs/agent-knowledge-and-memory.md +++ b/src/docs/agent-knowledge-and-memory.md @@ -115,9 +115,10 @@ prepended the same way ([skills.md](skills.md)); the hive-wide house style precedes both ([house-style.md](house-style.md)). Two instruction files *are* read natively: a user-level -`~/.claude/CLAUDE.md` / `~/.gemini/GEMINI.md` if one exists — and because -those directories are fleet-shared today (next section), such a file applies -to every Claude or Gemini agent on the hive. +`~/.claude/CLAUDE.md` / `~/.gemini/GEMINI.md` if one exists. Since +[#17031](https://github.com/hivecommons/hive/issues/17031) those files live in +each agent's own `~/.claude` / `~/.gemini` (next section), so such a file +applies to that agent only. ## 4. CLI memory and conversation: what Hive does and does not touch @@ -134,15 +135,23 @@ conversation. `/clear` empties the chat; it does not touch anything on disk. - Per-UID agents get `HOME=/data/home/agents/` (`AgentHome`, `interactiveHomePath`) with per-agent `XDG_DATA_HOME`/`XDG_STATE_HOME` under `~/.local` (`setupAgentXDGDirs`). `/data/home` is the persistent volume. -- `interactiveHomeBridgeDirs` symlinks `.claude`, `.config`, `.codex`, `.bob`, - `.gemini` and `.cache` from every per-agent home to the **same** directories - under `/data/home`, so one login authenticates the fleet. Anything a CLI - keeps *inside* those directories is therefore fleet-shared and persistent. -- Real per-agent directories with one narrow bridge: `~/.copilot` (only - `config.json` shared — `setupCopilotHome`, #9444), `~/.local`, +- `interactiveHomeBridgeDirs` symlinks `.config`, `.codex` and `.cache` from + every per-agent home to the **same** directories under `/data/home`, so one + login authenticates the fleet. Those hold credentials/config and caches only. +- Real per-agent directories with narrow, credential-only bridges inside them + (`perAgentCLIHomes`, [#17031](https://github.com/hivecommons/hive/issues/17031)): + `~/.claude` (only `.credentials.json` and `settings.json` shared — + `projects/` with transcripts and auto-memory, `todos/`, `history.jsonl` and a + user-level `CLAUDE.md` are per-agent), `~/.gemini` (only sign-in files, + `settings.json` and `antigravity-cli/` shared — `GEMINI.md` and `tmp/` + per-agent), `~/.bob` (only `settings.json` / `settings/` shared), `~/.copilot` + (only `config.json` shared, #9444). Also per-agent: `~/.local`, `.claude.json`, `.npm`, `.gitconfig` (#9478). Codex gets `CODEX_HOME=/data/home/.codex-` with only `auth.json` symlinked to the - shared login (`setupCodexHome`, `codexHomePath`). + shared login (`setupCodexHome`, `codexHomePath`). Legacy whole-directory + symlinks are retired on the next launch; nothing under `/data/home` is + deleted — a pre-isolation `projects/*/memory` store is logged once for review. + The full table is in [agent-configuration.md](agent-configuration.md#per-agent-homes-what-is-shared-and-what-is-private). - `HIVE_SHARED_AGENT_HOME=1` forces the legacy single shared home for all. - Inference (API-routed) agents use throwaway homes under `/tmp/.claude-inference-home-` that vanish with the pod. @@ -155,7 +164,7 @@ conversation. `/clear` empties the chat; it does not touch anything on disk. 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, and — for the bridged directories — across agents. +restarts — but, since #17031, not across agents. ### What persists across what @@ -167,29 +176,29 @@ 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//memory/`, `~/.claude/CLAUDE.md`, `history.jsonl`) | ✓ | ✓ | ✓ (`/data/home/.claude` is shared & persistent) | ✓ readable: the tree is fleet-shared; auto-memory is keyed by cwd `/data/agents/` so files are per-agent by path, but `CLAUDE.md`/history are one copy | +| **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 | | **Copilot CLI memory/sessions** (`~/.copilot`) | ✓ | ✓ | ✓ | ✗ per-agent dir (#9444); only `config.json` shared | -| **Gemini memory** (`~/.gemini/GEMINI.md`, state) | ✓ | ✓ | ✓ | ✓ whole directory shared | -| **Bob memory/settings** (`~/.bob`) | ✓ | ✓ | ✓ | ✓ whole directory shared | +| **Gemini memory** (`~/.gemini/GEMINI.md`, state) | ✓ | ✓ | ✓ | ✗ 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 the shared Claude tree -(`data.claude_sessions_dir`, default `/data/home/.claude/projects`, and -attributes sessions by the `-data-agents-` project slug — -`src/pkg/tokens/claude_scanner.go`), which is why that tree is shared on -purpose today. +The dashboard's cost accounting reads `data.claude_sessions_dir` (default +`/data/home/.claude/projects`) **and** every per-agent sibling +`/data/home/agents/*/.claude/projects` (`ClaudeSessionTrees`, +`src/pkg/tokens/agent_home_trees.go`), attributing each per-agent tree to its +owner and falling back to the `-data-agents-` project slug for the +shared tree (`claude_scanner.go`); `bob_sessions_dir` and +`copilot_sessions_dir` work the same way. ## Known gaps / in progress Do not treat the following as current behaviour; follow the links. -- [#17031](https://github.com/hivecommons/hive/issues/17031) — Claude/Gemini/Bob - persistent memory is shared across every agent on a hive. Fix in flight: - [PR #17039](https://github.com/hivecommons/hive/pull/17039) makes `.claude`, - `.gemini` and `.bob` real per-agent directories with only credential/settings - entries bridged (the `setupCopilotHome` pattern) and teaches the token - collector to scan `/data/home/agents/*/.claude/projects`. Until it merges, - the table above stands. +- [#17031](https://github.com/hivecommons/hive/issues/17031) — fixed by + [PR #17039](https://github.com/hivecommons/hive/pull/17039) (per-agent + `.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`.