From a6c0882c6f9a22387ba75551ca1f0ca057eeddca Mon Sep 17 00:00:00 2001 From: Danathar Date: Sun, 8 Nov 2026 10:40:49 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20[v6]=20claude=20auth:=20re-b?= =?UTF-8?q?ridge=20per-agent=20credentials=20a=20token=20refresh=20replace?= =?UTF-8?q?d,=20and=20resume=20login-paused=20agents=20after=20sign-in?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code refreshes its OAuth token by writing a temp file and renaming it over ~/.claude/.credentials.json, which replaces each agent's symlink to the shared /data/home/.claude/.credentials.json with a private 0600 copy. bridgeHomeEntry refused to touch a real file, the credential watchdog only probed the shared file, and the dashboard sign-in never reached the agents, so an agent whose private token was revoked stayed on "Please run /login" through any number of sign-ins. - Re-bridge at launch, on every credential-watchdog tick and after a sign-in: move the private file aside (.credentials.json.stale-), keep the newer usable token in the shared file (claude.TokensUsable + later expiresAt; the replaced shared file is preserved), restore the symlink, audit claude_credential_rebridged. - A successful dashboard Claude sign-in resumes the claude agents whose pause trigger is login-detector, and only those. - Status carries credentialBridgeBroken; the card names "credential bridge broken (private stale file)" and the Claude button reads "Sign in Claude for all agents". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- changelog.d/fixed-claude-credential-bridge.md | 1 + src/crux/agent/audit.go | 2 + src/crux/agent/claude_credential_bridge.go | 356 ++++++++++++++++++ .../claude_credential_bridge_internal_test.go | 140 +++++++ .../agent/claude_credential_bridge_test.go | 267 +++++++++++++ src/crux/agent/credentials_watchdog.go | 12 + src/crux/agent/interactive_home.go | 7 + src/crux/agent/manager_pane_signals.go | 1 + src/crux/agent/manager_tokens.go | 15 +- src/crux/audit.go | 9 + src/crux/claude/oauth.go | 10 +- src/crux/process.go | 6 + src/docs/agent-configuration.md | 18 + src/docs/agent-watchdog.md | 13 + src/docs/api-reference.md | 32 +- src/docs/api-reference/auth.md | 6 +- src/docs/api-reference/dashboard-misc.md | 2 +- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/snapshots-and-style.md | 2 +- .../dashboard-sections/workflow-and-agents.md | 2 +- src/docs/troubleshooting.md | 2 + src/pkg/dashboard/audit.go | 1 + src/pkg/dashboard/claude_auth.go | 16 +- src/pkg/dashboard/claude_auth_resume.go | 54 +++ src/pkg/dashboard/claude_auth_resume_test.go | 128 +++++++ src/pkg/dashboard/server.go | 6 + .../dashboard/static-src/js/agent-cards.js | 34 +- .../dashboard/static-src/js/agent-detail.js | 10 +- src/pkg/dashboard/static-src/js/gh-auth.js | 3 +- src/pkg/dashboard/static/index.html | 47 ++- src/pkg/dashboard/status_builder.go | 1 + .../claude_credential_bridge_ui_test.go | 40 ++ 32 files changed, 1204 insertions(+), 61 deletions(-) create mode 100644 changelog.d/fixed-claude-credential-bridge.md create mode 100644 src/crux/agent/claude_credential_bridge.go create mode 100644 src/crux/agent/claude_credential_bridge_internal_test.go create mode 100644 src/crux/agent/claude_credential_bridge_test.go create mode 100644 src/pkg/dashboard/claude_auth_resume.go create mode 100644 src/pkg/dashboard/claude_auth_resume_test.go create mode 100644 src/pkg/dashboard/webstatic/claude_credential_bridge_ui_test.go diff --git a/changelog.d/fixed-claude-credential-bridge.md b/changelog.d/fixed-claude-credential-bridge.md new file mode 100644 index 0000000000..cb82b1c288 --- /dev/null +++ b/changelog.d/fixed-claude-credential-bridge.md @@ -0,0 +1 @@ +- A Claude token refresh no longer cuts an agent off from the fleet's shared login, and a dashboard Claude sign-in now actually recovers the agents it was meant to (refs [#17031](https://github.com/hivecommons/hive/issues/17031), [#17039](https://github.com/hivecommons/hive/pull/17039)). Each per-UID claude agent reaches the one shared login through a symlink, `~/.claude/.credentials.json` -> `/data/home/.claude/.credentials.json`. Claude Code refreshes its token about every 8 hours by writing a temp file and renaming it over that path, which replaces the symlink with a private `0600` copy. From then on the agent ran on its own token: a dashboard sign-in rewrote the shared file and never reached it, and once the private token was revoked the agent answered every kick with `Login expired · Please run /login` or `OAuth token revoked`, was re-paused by the login detector or restart-looped, and nothing told the owner that signing in again could not help. On one hive seven agents sat in that state through two sign-ins until the links were fixed by hand. Hive now checks every agent's link at launch, on every credential-watchdog cycle and right after a dashboard sign-in. When a regular file has replaced it, hive moves the file aside as `.credentials.json.stale-` (never deleting it), keeps whichever credential is newer and still usable in the shared file (so one agent's fresh refresh becomes the fleet's login instead of stranding the rest), restores the symlink, and records a `claude_credential_rebridged` Audit Log entry. A successful dashboard Claude sign-in also resumes the claude agents the login detector paused, and only those: operator, fleet-breaker, hook and other pauses stay. On the dashboard, an affected agent's card now says **credential bridge broken (private stale file)** instead of a generic "needs login", and the agent card's Claude button reads **Sign in Claude for all agents**, with a tooltip saying it is the fleet-wide sign-in rather than a per-agent login. diff --git a/src/crux/agent/audit.go b/src/crux/agent/audit.go index b0572db5ba..41dc7b0b09 100644 --- a/src/crux/agent/audit.go +++ b/src/crux/agent/audit.go @@ -27,6 +27,8 @@ const ( AuditCopilotTokenMissing = crux.AuditCopilotTokenMissing AuditClaudeTokenMissing = crux.AuditClaudeTokenMissing + + AuditClaudeCredentialRebridged = crux.AuditClaudeCredentialRebridged ) // auditActorSystem attributes an event to the hive process itself rather than diff --git a/src/crux/agent/claude_credential_bridge.go b/src/crux/agent/claude_credential_bridge.go new file mode 100644 index 0000000000..7a2c476554 --- /dev/null +++ b/src/crux/agent/claude_credential_bridge.go @@ -0,0 +1,356 @@ +package agent + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "sync" + "syscall" + "time" + + "github.com/hivecommons/hive/crux/claude" +) + +// Claude credential bridge repair. +// +// Each per-UID claude agent reaches the fleet's one Claude login through a +// symlink, $HOME/.claude/.credentials.json -> /data/home/.claude/.credentials.json +// (perAgentCLIHomes). Claude Code does not write through that link. When it +// refreshes the OAuth token (about every 8 hours) it writes a temp file in +// $HOME/.claude and renames it over .credentials.json, which REPLACES the +// symlink with a regular file owned by the agent's uid, mode 0600. From then +// on that agent runs on a private copy: a later dashboard sign-in rewrites the +// shared file and never reaches it, and when its private token is revoked the +// agent answers every kick with "Please run /login" while a perfectly good +// login sits one directory away. +// +// The Claude Code CLI offers no supported way to keep the link: its documented +// knob, CLAUDE_CONFIG_DIR, moves the WHOLE config directory (settings, +// transcripts, auto-memory) and would undo the per-agent split of +// hivecommons/hive#17031; a bind mount cannot be renamed over (EBUSY) and +// needs mount privileges the pod does not have. So hive cannot prevent the +// replacement and instead DETECTS and REPAIRS it: at every agent launch, on +// every credential-watchdog cycle, and right after a dashboard sign-in. +// +// The repair never deletes a token. It moves the private file aside, keeps +// whichever of the two credentials is newer AND usable in the shared file, and +// restores the symlink: +// +// - the private copy wins only when it is usable (claude.TokensUsable: a live +// access token, or a refresh grant that has not expired) and either the +// shared credential is not usable or the private access token expires +// LATER than the shared one. A refresh mints a later expiresAt, so this is +// what promotes one agent's fresh refresh to the whole fleet instead of +// stranding everyone else on the grant it just rotated; +// - otherwise the shared file stays as it is (ties keep the shared file, so +// a private copy identical to it is simply moved aside). +// +// The private file is renamed to .credentials.json.stale- in +// the agent's own .claude directory and keeps its owner and mode; when it is +// promoted, the shared file it replaces is preserved the same way beside the +// shared credential. Both names fall outside sharedCredentialBases, so the +// permissions watcher never opens them up to the group. + +// Repair triggers, recorded in the audit detail and the log. +const ( + claudeBridgeTriggerLaunch = "launch" + claudeBridgeTriggerWatchdog = "watchdog" + claudeBridgeTriggerSignIn = "sign-in" +) + +// claudeCredentialStaleInfix names a credential moved aside by the repair. +const claudeCredentialStaleInfix = ".stale-" + +// claudeSharedCredentialMode is the mode of a shared credential the repair +// writes: owner and group read/write, the same as claude.WriteCredentials (the +// dashboard sign-in) and what the entrypoint guard asserts, so every agent uid +// reaches it through the node group. +const claudeSharedCredentialMode = 0o660 + +// Test seams. chownClaudeCredential applies the previous shared file's owner +// to the promoted replacement; it is a seam so tests run without root or real +// agent uids. claudeBridgeNow stamps the moved-aside file names. +var ( + chownClaudeCredential = os.Chown + claudeBridgeNow = time.Now +) + +// claudeBridgeMu serializes repairs: the launch path, the watchdog and the +// sign-in hook can all reach the same agent's link. It is never held while +// taking m.mu, so it cannot invert against the launch path, which already +// holds m.mu when it provisions the home. +var claudeBridgeMu sync.Mutex + +// claudeBridgeRepair describes one repaired bridge, for the audit and log. +type claudeBridgeRepair struct { + agent string + // kept is "shared" when the shared credential was kept as it was, or + // "agent" when the agent's private copy was newer and usable and was + // promoted into the shared file. + kept string + // staleAgentPath is where the private file was moved. + staleAgentPath string + // staleSharedPath is where the replaced shared file was preserved; empty + // unless kept == "agent" and a shared file existed. + staleSharedPath string +} + +// claudeCredentialBridgePaths returns the agent's bridged credential path and +// the shared target it must link to. ok is false when the agent has no +// per-agent home (no uid, an inference backend, or HIVE_SHARED_AGENT_HOME=1), +// i.e. exactly when setupInteractiveHome provisions no bridge. +func claudeCredentialBridgePaths(agentName string, uid int, backend string) (link, target string, ok bool) { + if uid <= 0 || IsInferenceBackend(backend) || sharedAgentHomeForced() { + return "", "", false + } + link = filepath.Join(interactiveHomePath(agentName), claudeHomeDirName, claudeCredentialsFileName) + return link, sharedClaudeBridgeTarget(), true +} + +// sharedClaudeBridgeTarget is the shared credential every bridge links to. +// Derived from sharedAgentHome (not the claude.CredentialsPath constant) so it +// follows the same test seam as the links themselves. +func sharedClaudeBridgeTarget() string { + return filepath.Join(sharedAgentHome, claudeHomeDirName, claudeCredentialsFileName) +} + +// claudeCredentialBridgeBroken reports whether a regular file has replaced the +// agent's credential symlink. Read-only (one Lstat), so it is cheap enough for +// the status snapshot. +func claudeCredentialBridgeBroken(agentName string, uid int, backend string) bool { + link, _, ok := claudeCredentialBridgePaths(agentName, uid, backend) + if !ok { + return false + } + info, err := os.Lstat(link) + return err == nil && info.Mode().IsRegular() +} + +// preferAgentClaudeCredential decides which credential the shared file keeps. +// See the file comment for the rule. +func preferAgentClaudeCredential(agent, shared *claude.OAuthTokens, now time.Time) bool { + if !claude.TokensUsable(agent, now) { + return false + } + if !claude.TokensUsable(shared, now) { + return true + } + return agent.ExpiresAt > shared.ExpiresAt +} + +// repairClaudeCredentialBridge re-bridges one agent's credential when a regular +// file has replaced the symlink. It returns nil, nil when there is nothing to +// repair (a symlink, an absent link, or a directory, which is not this +// failure). +func (m *Manager) repairClaudeCredentialBridge(agentName, link, target string) (*claudeBridgeRepair, error) { + claudeBridgeMu.Lock() + defer claudeBridgeMu.Unlock() + + info, err := os.Lstat(link) + if err != nil || !info.Mode().IsRegular() { + return nil, nil + } + now := claudeBridgeNow() + + // Move the private file aside FIRST. After the rename the CLI can no + // longer change what is being judged (its next write lands at link), so + // the decision below works on a stable snapshot. + staleAgent, err := moveAsideClaudeCredential(link, now) + if err != nil { + return nil, fmt.Errorf("move private credential aside: %w", err) + } + rep := &claudeBridgeRepair{agent: agentName, kept: "shared", staleAgentPath: staleAgent} + + if preferAgentClaudeCredential(claude.LoadTokens(staleAgent), claude.LoadTokens(target), now) { + staleShared, perr := promoteClaudeCredential(staleAgent, target, now) + if perr != nil { + // Put the private file back: the agent's copy was the only usable + // token, and linking the agent to the older shared one would + // strand it. The next cycle tries again. + if rerr := os.Rename(staleAgent, link); rerr != nil { + m.logger.Error("claude credential bridge: promotion failed and the private credential could not be restored; it is kept at the stale path", + "agent", agentName, "stale", staleAgent, "error", perr, "restore_error", rerr) + } + return nil, fmt.Errorf("promote private credential to shared: %w", perr) + } + rep.kept = "agent" + rep.staleSharedPath = staleShared + } + + if err := os.Symlink(target, link); err != nil { + // EEXIST: the CLI wrote a fresh file between the rename and now. The + // next cycle repairs that one; nothing is lost either way. + return rep, fmt.Errorf("restore credential symlink: %w", err) + } + return rep, nil +} + +// moveAsideClaudeCredential renames path to a unique +// .stale-[-N] beside it and returns the new path. It skips +// any name that already exists. +func moveAsideClaudeCredential(path string, now time.Time) (string, error) { + base := path + claudeCredentialStaleInfix + now.UTC().Format("20060102T150405Z") + for i := 0; i < 100; i++ { + dst := base + if i > 0 { + dst = fmt.Sprintf("%s-%d", base, i) + } + if _, err := os.Lstat(dst); err == nil { + continue + } else if !errors.Is(err, fs.ErrNotExist) { + return "", err + } + // A rename keeps the file's owner and mode: the private copy stays + // readable only by the agent that wrote it. + if err := os.Rename(path, dst); err != nil { + return "", err + } + return dst, nil + } + return "", fmt.Errorf("no free stale name for %s", path) +} + +// promoteClaudeCredential replaces the shared credential with the bytes of src, +// atomically and at claudeSharedCredentialMode, owned like the file it +// replaces. The replaced file is preserved beside it first; its path is +// returned ("" when there was no shared file). +func promoteClaudeCredential(src, target string, now time.Time) (string, error) { + data, err := os.ReadFile(src) + if err != nil { + return "", err + } + uid, gid := -1, -1 + staleShared := "" + if info, err := os.Stat(target); err == nil { + if st, ok := info.Sys().(*syscall.Stat_t); ok { + uid, gid = int(st.Uid), int(st.Gid) + } + staleShared, err = preserveClaudeCredential(target, now) + if err != nil { + return "", fmt.Errorf("preserve shared credential: %w", err) + } + } + tmp := target + ".tmp-rebridge" + _ = os.Remove(tmp) + if err := os.WriteFile(tmp, data, claudeSharedCredentialMode); err != nil { + return staleShared, err + } + // WriteFile honours the umask; assert the mode explicitly. + if err := os.Chmod(tmp, claudeSharedCredentialMode); err != nil { + _ = os.Remove(tmp) + return staleShared, err + } + if uid >= 0 || gid >= 0 { + // Best-effort: an unprivileged hive cannot chown, and the file it + // wrote is already group-readable by mode. + _ = chownClaudeCredential(tmp, uid, gid) + } + if err := os.Rename(tmp, target); err != nil { + _ = os.Remove(tmp) + return staleShared, err + } + return staleShared, nil +} + +// preserveClaudeCredential copies path to a unique stale name beside it, +// leaving path itself in place (agents keep reading it until the rename that +// replaces it). The copy is 0600: it is an archive, not a live credential. +func preserveClaudeCredential(path string, now time.Time) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + base := path + claudeCredentialStaleInfix + now.UTC().Format("20060102T150405Z") + for i := 0; i < 100; i++ { + dst := base + if i > 0 { + dst = fmt.Sprintf("%s-%d", base, i) + } + f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, fs.ErrExist) { + continue + } + if err != nil { + return "", err + } + _, werr := f.Write(data) + cerr := f.Close() + if werr != nil || cerr != nil { + _ = os.Remove(dst) + return "", errors.Join(werr, cerr) + } + return dst, nil + } + return "", fmt.Errorf("no free stale name for %s", path) +} + +// rebridgeClaudeCredential runs the repair for one agent and records the +// outcome. It is the single entry point the launch path, the watchdog and the +// sign-in hook share, so all three log and audit identically. +func (m *Manager) rebridgeClaudeCredential(agentName, link, target, trigger string) *claudeBridgeRepair { + rep, err := m.repairClaudeCredentialBridge(agentName, link, target) + if err != nil { + // Logged, not audited: a repair that keeps failing (an unprivileged + // hive that cannot enter the agent's 0700 home) would otherwise add an + // audit row every watchdog cycle. The dashboard keeps showing the + // agent's bridge as broken, which is the standing signal. + m.logger.Warn("claude credential bridge: repair failed", + "agent", agentName, "link", link, "trigger", trigger, "error", err) + return nil + } + if rep == nil { + return nil + } + m.logger.Warn("claude credential bridge: a private credential file had replaced the shared-login symlink; re-bridged", + "agent", agentName, + "trigger", trigger, + "kept", rep.kept, + "stale_agent_file", rep.staleAgentPath, + "stale_shared_file", rep.staleSharedPath, + "cause", "Claude Code token refresh writes a temp file and renames it over the link") + m.audit(AuditClaudeCredentialRebridged, agentName, auditFields( + "outcome", "success", + "trigger", trigger, + "kept", rep.kept, + "stale_agent_file", rep.staleAgentPath, + "stale_shared_file", rep.staleSharedPath, + )) + return rep +} + +// RepairClaudeCredentialBridges checks every per-agent Claude credential +// bridge and repairs each one a regular file has replaced. It returns the +// names of the agents it re-bridged, sorted. Agents are snapshotted under m.mu +// and repaired after it is released. +func (m *Manager) RepairClaudeCredentialBridges(trigger string) []string { + type candidate struct { + name string + uid int + backend string + } + m.mu.RLock() + cands := make([]candidate, 0, len(m.agents)) + for name, a := range m.agents { + if a == nil { + continue + } + cands = append(cands, candidate{name: name, uid: a.UID, backend: effectiveBackend(a)}) + } + m.mu.RUnlock() + sort.Slice(cands, func(i, j int) bool { return cands[i].name < cands[j].name }) + + var repaired []string + for _, c := range cands { + link, target, ok := claudeCredentialBridgePaths(c.name, c.uid, c.backend) + if !ok { + continue + } + if rep := m.rebridgeClaudeCredential(c.name, link, target, trigger); rep != nil { + repaired = append(repaired, c.name) + } + } + return repaired +} diff --git a/src/crux/agent/claude_credential_bridge_internal_test.go b/src/crux/agent/claude_credential_bridge_internal_test.go new file mode 100644 index 0000000000..746940ce63 --- /dev/null +++ b/src/crux/agent/claude_credential_bridge_internal_test.go @@ -0,0 +1,140 @@ +package agent + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/hivecommons/hive/crux/claude" + "github.com/hivecommons/hive/crux/config" +) + +// TestRepairClaudeCredentialBridge_PromotionKeepsSharedOwner: the promoted +// shared credential is written by the hive process, so without a chown it would +// belong to whoever runs hive. It must keep the owner and group of the file it +// replaces. The chown is a seam so this runs without root or real agent uids. +func TestRepairClaudeCredentialBridge_PromotionKeepsSharedOwner(t *testing.T) { + shared := withSharedAgentHome(t) + m, _ := testManagerWithSink(t) + now := time.Now() + link, target := brokenBridgeFixture(t, shared, "coder", + fakeClaudeCredential("fake-old-access", now.Add(-time.Hour), "fake-old-refresh"), + fakeClaudeCredential("fake-new-access", now.Add(8*time.Hour), "fake-new-refresh")) + info, err := os.Stat(target) + if err != nil { + t.Fatal(err) + } + st := info.Sys().(*syscall.Stat_t) + + type chownCall struct { + path string + uid, gid int + } + var calls []chownCall + orig := chownClaudeCredential + chownClaudeCredential = func(path string, uid, gid int) error { + calls = append(calls, chownCall{path, uid, gid}) + return nil + } + t.Cleanup(func() { chownClaudeCredential = orig }) + + rep := m.rebridgeClaudeCredential("coder", link, target, claudeBridgeTriggerWatchdog) + if rep == nil || rep.kept != "agent" { + t.Fatalf("repair = %+v, want kept=agent", rep) + } + if len(calls) != 1 || calls[0].uid != int(st.Uid) || calls[0].gid != int(st.Gid) { + t.Fatalf("chown calls = %+v, want one call with the previous shared owner %d:%d", calls, st.Uid, st.Gid) + } + if filepath.Dir(calls[0].path) != filepath.Dir(target) { + t.Errorf("chown applied to %q, want the replacement written beside %q", calls[0].path, target) + } +} + +// TestRepairClaudeCredentialBridge_StaleNamesNeverCollide: two repairs in the +// same second must not overwrite the first moved-aside file. +func TestRepairClaudeCredentialBridge_StaleNamesNeverCollide(t *testing.T) { + shared := withSharedAgentHome(t) + m, _ := testManagerWithSink(t) + fixed := time.Date(2026, 11, 7, 14, 54, 0, 0, time.UTC) + orig := claudeBridgeNow + claudeBridgeNow = func() time.Time { return fixed } + t.Cleanup(func() { claudeBridgeNow = orig }) + + sharedJSON := fakeClaudeCredential("fake-shared-access", time.Now().Add(8*time.Hour), "fake-shared-refresh") + link, target := brokenBridgeFixture(t, shared, "tester", sharedJSON, + fakeClaudeCredential("fake-first-access", time.Now().Add(time.Hour), "fake-first-refresh")) + m.rebridgeClaudeCredential("tester", link, target, claudeBridgeTriggerWatchdog) + + // The CLI refreshes again within the same second. + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(link, []byte(fakeClaudeCredential("fake-second-access", time.Now().Add(time.Hour), "fake-second-refresh")), 0o600); err != nil { + t.Fatal(err) + } + m.rebridgeClaudeCredential("tester", link, target, claudeBridgeTriggerWatchdog) + + if got := staleFiles(t, filepath.Dir(link)); len(got) != 2 { + t.Fatalf("want two distinct moved-aside files, got %v", got) + } + assertBridgeRestored(t, link, target) +} + +// TestAgentSnapshot_ReportsCredentialBridgeBroken: the status the dashboard +// reads names the broken bridge, and stops naming it once it is repaired. +func TestAgentSnapshot_ReportsCredentialBridgeBroken(t *testing.T) { + shared := withSharedAgentHome(t) + m, _ := testManagerWithSink(t) + ap := &AgentProcess{Name: "architect", UID: 2001, Config: config.AgentConfig{Backend: "claude"}} + m.mu.Lock() + m.agents["architect"] = ap + m.mu.Unlock() + link, _ := brokenBridgeFixture(t, shared, "architect", + fakeClaudeCredential("fake-shared-access", time.Now().Add(8*time.Hour), "fake-shared-refresh"), + fakeClaudeCredential("fake-private-access", time.Now().Add(time.Hour), "fake-private-refresh")) + + if snap := ap.snapshot(); !snap.CredentialBridgeBroken { + t.Fatal("snapshot does not report the private file that replaced the credential link") + } + if got := m.RepairClaudeCredentialBridges(claudeBridgeTriggerWatchdog); len(got) != 1 || got[0] != "architect" { + t.Fatalf("RepairClaudeCredentialBridges = %v, want [architect]", got) + } + if snap := ap.snapshot(); snap.CredentialBridgeBroken { + t.Errorf("snapshot still reports a broken bridge after the repair (link %s)", link) + } + + // Non-claude agents never report it, even with a stray regular file. + other := &AgentProcess{Name: "copilot-one", UID: 2006, Config: config.AgentConfig{Backend: "copilot"}} + brokenBridgeFixture(t, shared, "copilot-one", "", fakeClaudeCredential("fake-x", time.Now(), "")) + if other.snapshot().CredentialBridgeBroken { + t.Error("a copilot agent must not report a Claude credential bridge") + } +} + +// TestPreferAgentClaudeCredential pins the "newer AND usable" rule. +func TestPreferAgentClaudeCredential(t *testing.T) { + now := time.Now() + tok := func(exp time.Duration, refresh string) *claude.OAuthTokens { + return &claude.OAuthTokens{AccessToken: "fake", RefreshToken: refresh, ExpiresAt: now.Add(exp).UnixMilli()} + } + cases := []struct { + name string + agent, shared *claude.OAuthTokens + want bool + }{ + {"agent newer and live", tok(8*time.Hour, "r"), tok(time.Hour, "r"), true}, + {"shared newer", tok(time.Hour, "r"), tok(8*time.Hour, "r"), false}, + {"tie keeps shared", tok(time.Hour, "r"), tok(time.Hour, "r"), false}, + {"agent expired but refreshable, shared absent", tok(-time.Hour, "r"), nil, true}, + {"agent unusable, shared absent", tok(-time.Hour, ""), nil, false}, + {"agent usable, shared unusable", tok(-time.Minute, "r"), tok(-2*time.Hour, ""), true}, + {"agent absent", nil, tok(time.Hour, "r"), false}, + } + for _, c := range cases { + if got := preferAgentClaudeCredential(c.agent, c.shared, now); got != c.want { + t.Errorf("%s: got %v, want %v", c.name, got, c.want) + } + } +} diff --git a/src/crux/agent/claude_credential_bridge_test.go b/src/crux/agent/claude_credential_bridge_test.go new file mode 100644 index 0000000000..e7bd0093f2 --- /dev/null +++ b/src/crux/agent/claude_credential_bridge_test.go @@ -0,0 +1,267 @@ +package agent + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux/config" +) + +// claude_credential_bridge_test.go: a Claude Code token refresh writes a temp +// file and renames it over $HOME/.claude/.credentials.json, which replaces the +// per-agent symlink to the shared login with a private regular file. These +// tests drive the three entry points that must repair it (agent launch, the +// credential watchdog, and the dashboard sign-in reload) through the same +// public paths production uses. Every token is a fake JSON blob written into a +// t.TempDir(). + +// fakeClaudeCredential is a credentials file in the on-disk shape Claude Code +// writes, with fake token strings. +func fakeClaudeCredential(access string, expiresAt time.Time, refresh string) string { + return fmt.Sprintf(`{"claudeAiOauth":{"accessToken":%q,"refreshToken":%q,"expiresAt":%d,"scopes":["user:inference"]}}`, + access, refresh, expiresAt.UnixMilli()) +} + +// brokenBridgeFixture lays out a per-agent home whose credential symlink a +// token refresh has replaced: the shared credential holds sharedJSON and the +// agent's .claude/.credentials.json is a REGULAR file holding agentJSON, mode +// 0600 as the CLI writes it. Returns (link, target). +func brokenBridgeFixture(t *testing.T, shared, agentName, sharedJSON, agentJSON string) (string, string) { + t.Helper() + target := filepath.Join(shared, ".claude", ".credentials.json") + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + t.Fatal(err) + } + if sharedJSON != "" { + if err := os.WriteFile(target, []byte(sharedJSON), 0o660); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(shared, "agents", agentName, ".claude", ".credentials.json") + if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(link, []byte(agentJSON), 0o600); err != nil { + t.Fatal(err) + } + return link, target +} + +func assertBridgeRestored(t *testing.T, link, target string) { + t.Helper() + info, err := os.Lstat(link) + if err != nil { + t.Fatalf("credential link missing after repair: %v", err) + } + if info.Mode()&os.ModeSymlink == 0 { + t.Fatalf("%s is still a regular file (mode %v); the bridge was not restored", link, info.Mode()) + } + if got, _ := os.Readlink(link); got != target { + t.Fatalf("credential link -> %q, want %q", got, target) + } +} + +// staleFiles lists the moved-aside credentials in dir. +func staleFiles(t *testing.T, dir string) []string { + t.Helper() + matches, err := filepath.Glob(filepath.Join(dir, ".credentials.json.stale-*")) + if err != nil { + t.Fatal(err) + } + return matches +} + +func readFileString(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestSetupInteractiveHome_RebridgesCredentialReplacedByRefresh_KeepsNewerShared +// is the hive-wild-mole state: the agent's private copy is an older refresh +// (whose grant was later revoked) and the shared file holds a newer dashboard +// sign-in. Launch must move the private file aside, keep the shared file +// as it is, and restore the symlink. On the v6 tip bridgeHomeEntry refused +// to touch the real file, so the agent ran on the dead copy forever. +func TestSetupInteractiveHome_RebridgesCredentialReplacedByRefresh_KeepsNewerShared(t *testing.T) { + shared := withSharedAgentHome(t) + m, sink := testManagerWithSink(t) + now := time.Now() + sharedJSON := fakeClaudeCredential("fake-signin-access", now.Add(8*time.Hour), "fake-signin-refresh") + agentJSON := fakeClaudeCredential("fake-refreshed-access", now.Add(time.Hour), "fake-refreshed-refresh") + link, target := brokenBridgeFixture(t, shared, "architect", sharedJSON, agentJSON) + + ap := &AgentProcess{Name: "architect", UID: 2001, Config: config.AgentConfig{Backend: "claude"}} + m.setupInteractiveHome(ap, "claude") + + assertBridgeRestored(t, link, target) + if got := readFileString(t, target); got != sharedJSON { + t.Errorf("shared credential changed although it was the newer one:\n got %s\nwant %s", got, sharedJSON) + } + stale := staleFiles(t, filepath.Dir(link)) + if len(stale) != 1 { + t.Fatalf("want exactly one moved-aside private file, got %v", stale) + } + if got := readFileString(t, stale[0]); got != agentJSON { + t.Errorf("moved-aside file does not hold the private credential: %s", got) + } + if info, err := os.Stat(stale[0]); err != nil || info.Mode().Perm() != 0o600 { + t.Errorf("moved-aside private file must keep its 0600 mode: info=%v err=%v", info, err) + } + if got := staleFiles(t, filepath.Dir(target)); len(got) != 0 { + t.Errorf("shared credential was not replaced, so nothing beside it should be moved aside: %v", got) + } + ev := sink.find("claude_credential_rebridged") + if ev == nil { + t.Fatal("no claude_credential_rebridged audit entry for the repair") + } + if ev.Agent != "architect" || ev.Fields["trigger"] != "launch" || ev.Fields["kept"] != "shared" { + t.Errorf("audit entry = %+v, want agent=architect trigger=launch kept=shared", ev) + } + for k, v := range ev.Fields { + if s, ok := v.(string); ok && strings.Contains(s, "fake-") { + t.Errorf("audit field %s carries token material: %q", k, s) + } + } +} + +// TestSetupInteractiveHome_RebridgePromotesNewerUsablePrivateCredential: when +// the agent's private copy is the NEWER usable one (it just refreshed, and the +// refresh rotated the grant the shared file still holds), the repair promotes +// it into the shared file so the rest of the fleet is not stranded, and +// preserves the old shared file instead of losing it. +func TestSetupInteractiveHome_RebridgePromotesNewerUsablePrivateCredential(t *testing.T) { + shared := withSharedAgentHome(t) + m, sink := testManagerWithSink(t) + now := time.Now() + sharedJSON := fakeClaudeCredential("fake-old-access", now.Add(-time.Hour), "fake-old-refresh") + agentJSON := fakeClaudeCredential("fake-new-access", now.Add(8*time.Hour), "fake-new-refresh") + link, target := brokenBridgeFixture(t, shared, "coder", sharedJSON, agentJSON) + + ap := &AgentProcess{Name: "coder", UID: 2002, Config: config.AgentConfig{Backend: "claude"}} + m.setupInteractiveHome(ap, "claude") + + assertBridgeRestored(t, link, target) + if got := readFileString(t, target); got != agentJSON { + t.Errorf("shared credential should now hold the newer private token:\n got %s\nwant %s", got, agentJSON) + } + if info, err := os.Stat(target); err != nil || info.Mode().Perm() != 0o660 { + t.Errorf("promoted shared credential must be 0660 (group-readable by every agent uid): info=%v err=%v", info, err) + } + oldShared := staleFiles(t, filepath.Dir(target)) + if len(oldShared) != 1 || readFileString(t, oldShared[0]) != sharedJSON { + t.Errorf("replaced shared credential must be preserved beside it, got %v", oldShared) + } + if got := staleFiles(t, filepath.Dir(link)); len(got) != 1 { + t.Errorf("private file must be moved aside, not deleted: %v", got) + } + if ev := sink.find("claude_credential_rebridged"); ev == nil || ev.Fields["kept"] != "agent" { + t.Errorf("audit entry = %+v, want kept=agent", ev) + } +} + +// TestSetupInteractiveHome_RebridgeNeverPromotesUnusablePrivateCredential: a +// private copy with a later expiresAt but no usable grant must not overwrite +// the shared file; "newer" alone is not enough. +func TestSetupInteractiveHome_RebridgeNeverPromotesUnusablePrivateCredential(t *testing.T) { + shared := withSharedAgentHome(t) + m, _ := testManagerWithSink(t) + now := time.Now() + sharedJSON := fakeClaudeCredential("fake-shared-access", now.Add(-2*time.Hour), "fake-shared-refresh") + // Expired access token and no refresh grant: not usable. + agentJSON := fakeClaudeCredential("fake-dead-access", now.Add(-time.Minute), "") + link, target := brokenBridgeFixture(t, shared, "scanner", sharedJSON, agentJSON) + + ap := &AgentProcess{Name: "scanner", UID: 2003, Config: config.AgentConfig{Backend: "claude"}} + m.setupInteractiveHome(ap, "claude") + + assertBridgeRestored(t, link, target) + if got := readFileString(t, target); got != sharedJSON { + t.Errorf("an unusable private credential replaced the shared one: %s", got) + } +} + +// TestCredentialWatchdog_RebridgesWithinOneCycle: a refresh that replaces the +// link while the agent is running must be caught by the next watchdog tick, +// not only at the next launch. +func TestCredentialWatchdog_RebridgesWithinOneCycle(t *testing.T) { + shared := withSharedAgentHome(t) + t.Setenv(CredentialWatchdogIntervalEnv, "20ms") + m, sink := testManagerWithSink(t) + m.mu.Lock() + m.agents["planner"] = &AgentProcess{Name: "planner", UID: 2004, Config: config.AgentConfig{Backend: "claude"}} + m.mu.Unlock() + now := time.Now() + link, target := brokenBridgeFixture(t, shared, "planner", + fakeClaudeCredential("fake-shared-access", now.Add(8*time.Hour), "fake-shared-refresh"), + fakeClaudeCredential("fake-private-access", now.Add(time.Hour), "fake-private-refresh")) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { m.StartCredentialWatchdog(ctx); close(done) }() + t.Cleanup(func() { cancel(); <-done }) + + // One cycle is 20ms; allow generous scheduling slack but far less than a + // second cycle would need to matter. + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if info, err := os.Lstat(link); err == nil && info.Mode()&os.ModeSymlink != 0 { + break + } + time.Sleep(10 * time.Millisecond) + } + assertBridgeRestored(t, link, target) + if ev := sink.find("claude_credential_rebridged"); ev == nil || ev.Fields["trigger"] != "watchdog" { + t.Errorf("audit entry = %+v, want trigger=watchdog", ev) + } +} + +// TestReloadClaudeToken_RebridgesAfterSignIn: the dashboard sign-in writes the +// shared credential and calls ReloadClaudeToken. That must reach the agents a +// refresh had cut off, or the sign-in cannot help them (the hive-wild-mole +// 14:31Z and 14:50Z sign-ins). +func TestReloadClaudeToken_RebridgesAfterSignIn(t *testing.T) { + shared := withSharedAgentHome(t) + m, sink := testManagerWithSink(t) + m.mu.Lock() + m.agents["reviewer"] = &AgentProcess{Name: "reviewer", UID: 2005, Config: config.AgentConfig{Backend: "claude"}} + m.mu.Unlock() + now := time.Now() + link, target := brokenBridgeFixture(t, shared, "reviewer", + fakeClaudeCredential("fake-signin-access", now.Add(8*time.Hour), "fake-signin-refresh"), + fakeClaudeCredential("fake-revoked-access", now.Add(-10*time.Minute), "fake-revoked-refresh")) + + m.ReloadClaudeToken() + + assertBridgeRestored(t, link, target) + if ev := sink.find("claude_credential_rebridged"); ev == nil || ev.Fields["trigger"] != "sign-in" || ev.Fields["kept"] != "shared" { + t.Errorf("audit entry = %+v, want trigger=sign-in kept=shared", ev) + } +} + +// TestReloadClaudeToken_LogoutDoesNotRebridge: after a logout the shared file +// is gone; moving a private credential aside then would leave the agent with +// nothing at all. +func TestReloadClaudeToken_LogoutDoesNotRebridge(t *testing.T) { + shared := withSharedAgentHome(t) + m, _ := testManagerWithSink(t) + m.mu.Lock() + m.agents["reviewer"] = &AgentProcess{Name: "reviewer", UID: 2005, Config: config.AgentConfig{Backend: "claude"}} + m.mu.Unlock() + link, _ := brokenBridgeFixture(t, shared, "reviewer", "", + fakeClaudeCredential("fake-private-access", time.Now().Add(time.Hour), "fake-private-refresh")) + + m.ReloadClaudeToken() + + if info, err := os.Lstat(link); err != nil || !info.Mode().IsRegular() { + t.Errorf("private credential must stay in place when there is no shared login: info=%v err=%v", info, err) + } +} diff --git a/src/crux/agent/credentials_watchdog.go b/src/crux/agent/credentials_watchdog.go index f64c76eca0..61eb65ecbe 100644 --- a/src/crux/agent/credentials_watchdog.go +++ b/src/crux/agent/credentials_watchdog.go @@ -189,6 +189,12 @@ func credentialWatches() []credentialWatch { // the only signal is agents quietly ceasing work for hours. Turning that into // an immediate, queryable Audit Log entry is the whole point. // +// One exception to "not a fixer": each tick also re-bridges any per-agent +// Claude credential link that a token refresh replaced with a private file +// (RepairClaudeCredentialBridges). That repair moves files and never mints, +// prints or deletes a token; it is what keeps one agent's refresh from +// stranding the rest of the fleet for more than one cycle. +// // Gating: each backend's check only fires when at least one configured agent // uses that backend. A Claude-only hive never alerts on a missing Copilot // token, and vice versa; gateway/inference-only hives alert on neither. @@ -208,6 +214,12 @@ func (m *Manager) StartCredentialWatchdog(ctx context.Context) { case <-ctx.Done(): return case <-ticker.C: + // Re-bridge BEFORE probing: a Claude token refresh can leave one + // agent on a private copy holding the only live grant, and the + // repair promotes it into the shared file the probe reads. + if m.backendInUse("claude") { + m.RepairClaudeCredentialBridges(claudeBridgeTriggerWatchdog) + } for _, w := range credentialWatches() { m.evalCredentialWatch(w, lastUnusable) } diff --git a/src/crux/agent/interactive_home.go b/src/crux/agent/interactive_home.go index 99ce2c6a48..dcd9227180 100644 --- a/src/crux/agent/interactive_home.go +++ b/src/crux/agent/interactive_home.go @@ -437,6 +437,13 @@ func (m *Manager) setupPerAgentCLIHome(agentName, home string, uid int, spec per "agent", agentName, "link", link, "target", target) continue } + if spec.dir == claudeHomeDirName && name == claudeCredentialsFileName { + // A Claude token refresh replaces this link with a private regular + // file, which bridgeHomeEntry deliberately refuses to clobber. + // Re-bridge it first (moving the file aside, never deleting it); + // see claude_credential_bridge.go. + m.rebridgeClaudeCredential(agentName, link, target, claudeBridgeTriggerLaunch) + } m.bridgeHomeEntry(agentName, link, target) } } diff --git a/src/crux/agent/manager_pane_signals.go b/src/crux/agent/manager_pane_signals.go index 693128c465..24fc5edf87 100644 --- a/src/crux/agent/manager_pane_signals.go +++ b/src/crux/agent/manager_pane_signals.go @@ -112,6 +112,7 @@ func (a *AgentProcess) snapshot() crux.Process { RepeatFailure: a.RepeatFailure, SandboxLastRun: cloneSandboxRun(a.SandboxLastRun), NeedsLogin: needsLogin, + CredentialBridgeBroken: effectiveBackend(a) == "claude" && claudeCredentialBridgeBroken(a.Name, a.UID, "claude"), LoginURL: loginURL, Starting: a.startupLaunchQueued || a.launching, QuotaExhausted: quotaExhausted, diff --git a/src/crux/agent/manager_tokens.go b/src/crux/agent/manager_tokens.go index d6d5a23444..8e5e27f52d 100644 --- a/src/crux/agent/manager_tokens.go +++ b/src/crux/agent/manager_tokens.go @@ -22,11 +22,22 @@ type ( ) // ReloadClaudeToken re-reads the Claude credentials file and updates the -// cached token. Called by the dashboard after a successful OAuth login. +// cached token. Called by the dashboard after a successful OAuth login (and +// after a logout). +// +// When the shared credential is usable afterwards — a sign-in just wrote it — +// it also re-bridges every agent whose credential link a token refresh had +// replaced with a private file. Without that, the new login never reaches +// those agents: they keep reading their private, often revoked, copy and +// every re-login is wasted. After a logout the shared file is gone, so +// nothing is re-bridged. func (m *Manager) ReloadClaudeToken() { m.mu.Lock() - defer m.mu.Unlock() m.claudeAuthToken = claude.ReadAccessToken(claude.CredentialsPath) + m.mu.Unlock() + if claude.HasUsableToken(sharedClaudeBridgeTarget()) { + m.RepairClaudeCredentialBridges(claudeBridgeTriggerSignIn) + } } // Copilot token sources, as reported by CopilotTokenSource. Operator-facing diff --git a/src/crux/audit.go b/src/crux/audit.go index 350cfa09e4..5616cc09fc 100644 --- a/src/crux/audit.go +++ b/src/crux/audit.go @@ -40,6 +40,15 @@ const ( // failure shape and same operator-login recovery as the Copilot case; the // detail's outcome= distinguishes "missing" from "invalid or expired". AuditClaudeTokenMissing = "claude_token_missing" + + // AuditClaudeCredentialRebridged is recorded when an agent's per-agent + // Claude credential link ($HOME/.claude/.credentials.json -> the shared + // /data/home/.claude/.credentials.json) had been replaced by a private + // regular file (a Claude Code token refresh renames its temp file over the + // link) and hive re-bridged it. The detail names the trigger (launch, + // watchdog, sign-in), which credential the shared file kept (shared or + // agent), and where the moved-aside file now lives. Never token material. + AuditClaudeCredentialRebridged = "claude_credential_rebridged" ) // AuditSink receives agent lifecycle events for durable, queryable recording. diff --git a/src/crux/claude/oauth.go b/src/crux/claude/oauth.go index e5d87de632..8b262a88fa 100644 --- a/src/crux/claude/oauth.go +++ b/src/crux/claude/oauth.go @@ -436,11 +436,17 @@ func HasValidToken(path string) bool { // Positive evidence only: an unreadable or absent file returns false, leaving // callers exactly where they were before they asked. func HasUsableToken(path string) bool { - tokens := LoadTokens(path) + return TokensUsable(LoadTokens(path), time.Now()) +} + +// TokensUsable is HasUsableToken over an already-loaded token set, for callers +// that must judge two credentials side by side (the per-agent credential +// bridge repair compares an agent's private copy with the shared file). A nil +// token set is not usable. +func TokensUsable(tokens *OAuthTokens, now time.Time) bool { if tokens == nil { return false } - now := time.Now() if tokens.AccessToken != "" && !expired(tokens.ExpiresAt, now) { return true } diff --git a/src/crux/process.go b/src/crux/process.go index 649a4ce47a..12f7923a9a 100644 --- a/src/crux/process.go +++ b/src/crux/process.go @@ -54,6 +54,12 @@ type Process struct { BootstrapOverride string LastError string NeedsLogin bool + // CredentialBridgeBroken is true for a per-UID claude agent whose + // $HOME/.claude/.credentials.json is a regular file instead of the symlink + // to the shared login: a Claude Code token refresh replaced the link with + // a private copy, so a dashboard sign-in does not reach this agent until + // hive re-bridges it (launch, credential watchdog, or sign-in). + CredentialBridgeBroken bool LoginURL string Starting bool QuotaExhausted bool diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 11ea065b91..102e60b7e4 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -681,6 +681,24 @@ Each per-UID agent runs with its own durable `HOME` under `/data/home/agents//memory/MEMORY.md`, per-agent by path) was writable by every other agent and persisted on the PVC forever. Provisioning now retires those whole-directory bridges on the next launch, keeps only the login/settings entries above, and never deletes or moves anything under `/data/home`: a pre-existing shared memory store is left in place and logged once (`shared CLI home still holds a persistent memory store …`) so you can review or drain it ([#17033](https://github.com/hivecommons/hive/issues/17033)) before removing it by hand. The dashboard's token/cost scanners (`data.claude_sessions_dir`, `data.bob_sessions_dir`, `data.copilot_sessions_dir`) walk the shared path **and** every `/data/home/agents/*/…` sibling, attributing each per-agent tree to its owner, so cost accounting does not regress. `HIVE_SHARED_AGENT_HOME=1` restores the legacy single shared `HOME` for every agent (and with it the shared memory). +#### When a Claude token refresh breaks the credential link + +The `.claude/.credentials.json` bridge is a symlink, and Claude Code does not write through it. About every 8 hours the CLI refreshes its OAuth token by writing a temp file in `~/.claude` and renaming it over `.credentials.json`. The rename replaces the symlink with a private regular file, owned by the agent's uid with mode `0600`. That agent now runs on its own copy: a later dashboard sign-in rewrites the shared file and never reaches it, and if its private token is revoked it answers every kick with `Login expired · Please run /login` or `OAuth token revoked`. + +Claude Code has no supported way to keep the link. `CLAUDE_CONFIG_DIR` moves the whole config directory (settings, transcripts, auto-memory), which would undo the per-agent split above, and a bind mount cannot be renamed over. So hive detects and repairs the replacement instead, in three places: + +- at every agent launch; +- on every credential-watchdog cycle (`HIVE_CREDENTIAL_WATCHDOG_INTERVAL`, default 5 minutes), so a refresh that happens while the agent runs is caught within one cycle; +- right after a successful dashboard Claude sign-in. + +The repair never deletes a token: + +1. It moves the private file aside to `.credentials.json.stale-` in the agent's `~/.claude`. The file keeps its owner and `0600` mode. +2. It keeps whichever credential is newer **and** usable in the shared `/data/home/.claude/.credentials.json`. "Usable" is the rule the rest of hive uses: a live access token, or a refresh grant that has not expired. "Newer" means the access token's `expiresAt` is later. A fresh refresh in one agent therefore becomes the fleet's login, instead of stranding every other agent on the grant it just rotated. When the agent's copy wins, the old shared file is kept beside it as `.credentials.json.stale-` and the new one is written `0660` with the old file's owner and group. On a tie, or when the agent's copy is not usable, the shared file stays as it is. +3. It restores the symlink. + +Each repair writes a `claude_credential_rebridged` Audit Log entry naming the agent, the trigger (`launch`, `watchdog` or `sign-in`), which credential was kept (`shared` or `agent`) and where the moved-aside file went. It never records token material. Until the repair runs, the agent card shows **credential bridge broken (private stale file)** instead of a generic "needs login". Moved-aside files are not cleaned up automatically; remove them by hand once you no longer need them. + ### CLI auto-memory (`agents.cli_memory`) Subscription CLIs keep their own long-lived "memory" next to the transcripts: Claude Code's auto-memory (`~/.claude/projects/-data-agents-/memory/MEMORY.md`), Codex memories (`$CODEX_HOME/memories/`), Copilot CLI's `memory` setting, and Gemini's `~/.gemini/GEMINI.md`. Hive agents already get their durable context from beads, the knowledge store, and the kick prompt, so a hidden per-CLI notebook mostly accumulates stale one-off inferences ([#17032](https://github.com/hivecommons/hive/issues/17032)). The `agents.cli_memory` block controls it fleet-wide, and each agent may override it with its own `cli_memory:` block: diff --git a/src/docs/agent-watchdog.md b/src/docs/agent-watchdog.md index 5cccabdcd7..23cfd86fdd 100644 --- a/src/docs/agent-watchdog.md +++ b/src/docs/agent-watchdog.md @@ -111,6 +111,19 @@ recovery=chmod g+r /data/home/.claude/.credentials.json that is this condition, stated plainly. A report of `login expired (no usable refresh grant)` is the other condition and does need an operator login. +### Some Claude agents stay on "Login expired" after a sign-in + +If a dashboard sign-in brings most of the fleet back but a few agents keep answering with `Login expired · Please run /login` or `OAuth token revoked`, look at their credential link: + +```console +$ podman exec hive ls -l /data/home/agents//.claude/.credentials.json +-rw-------. 1 hive- node 471 Nov 7 06:51 /data/home/agents//.claude/.credentials.json +``` + +A regular file here, instead of a symlink to `/data/home/.claude/.credentials.json`, is the cause. A Claude Code token refresh replaced the link with a private copy, so no sign-in can reach that agent. The agent card says **credential bridge broken (private stale file)**. + +Hive repairs this on its own: at the agent's next launch, on the next credential-watchdog tick, and right after the next dashboard sign-in. It moves the private file aside as `.credentials.json.stale-`, keeps whichever token is newer and usable in the shared file, restores the symlink, and writes a `claude_credential_rebridged` Audit Log entry. See [When a Claude token refresh breaks the credential link](agent-configuration.md#when-a-claude-token-refresh-breaks-the-credential-link) for the rule. You do not need to move files by hand. If the card still shows the broken bridge after a watchdog cycle, the hive log has a `claude credential bridge: repair failed` warning that names the file and the error. + ## Configuration Everything lives under `governor.watchdog` and is optional; an absent block diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index af6c52b7a7..b0c8bc37e5 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -33,17 +33,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)); also `hub_build` (the hub's short SHA) and, once a stdio `hive-admin-mcp` client has called `/api/version`, `/api/status` or `/api/status/summary` with its `hive-admin-mcp/+` User-Agent, `last_seen_stdio_build` and `last_seen_stdio_at` (RFC3339) so the dashboard can flag build skew ([#12318](https://github.com/hivecommons/hive/issues/12318)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:76` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1811` | -| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1812` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1813` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1819` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1824` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1825` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1828` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1829` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1830` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1831` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1832` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1817` | +| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1818` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1819` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1825` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1830` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1831` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1834` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1835` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1836` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1837` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1838` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | @@ -86,7 +86,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1906` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1912` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | @@ -114,9 +114,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1833` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1834` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1835` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1839` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1840` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1841` | ## Configuration @@ -652,7 +652,7 @@ always resolved server-side from the validated token. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:389` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:390` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:391` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1840` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1846` | ## Hub SaaS 102 routes — see [api-reference/hub-saas.md](api-reference/hub-saas.md). diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index b43e4ad671..6c2430bdc2 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1833` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1834` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1835` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1839` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1840` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1841` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 4eeb6036c2..ade1a22ced 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -88,7 +88,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:389` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:390` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:391` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1840` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1846` | ### Activity observation provenance diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 0fbbde359a..d56f1dc1c2 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:76` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1811` | -| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1812` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1813` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1819` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `code_scanning` `{enabled, repos[], notices[]}` is the code scanning sweep's picture, absent while the sweep is off everywhere — per repo `{repo, security_url, checked_at, open_alerts, by_severity{critical,high,medium,low,note}, qualifying, below_threshold, excluded, tracked, tracked_closed, untracked, open_issues, filed, updated, closed, truncated, notice, notice_kind, error}`, where `tracked` is open alerts listed on an open hive issue and `notice_kind` is `missing_permission` (the App lacks Code scanning alerts: Read) or `not_enabled` (see `docs/code-scanning.md`); `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1824` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1825` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1828` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1829` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1830` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1831` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1832` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1817` | +| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1818` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1819` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1825` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `code_scanning` `{enabled, repos[], notices[]}` is the code scanning sweep's picture, absent while the sweep is off everywhere — per repo `{repo, security_url, checked_at, open_alerts, by_severity{critical,high,medium,low,note}, qualifying, below_threshold, excluded, tracked, tracked_closed, untracked, open_issues, filed, updated, closed, truncated, notice, notice_kind, error}`, where `tracked` is open alerts listed on an open hive issue and `notice_kind` is `missing_permission` (the App lacks Code scanning alerts: Read) or `not_enabled` (see `docs/code-scanning.md`); `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1830` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1831` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1834` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1835` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1836` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1837` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1838` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index f71c066c4e..68beeccb57 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1906` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1912` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | diff --git a/src/docs/dashboard-sections/workflow-and-agents.md b/src/docs/dashboard-sections/workflow-and-agents.md index ef9677f59e..14a92427ec 100644 --- a/src/docs/dashboard-sections/workflow-and-agents.md +++ b/src/docs/dashboard-sections/workflow-and-agents.md @@ -367,7 +367,7 @@ More about the line: **Sandboxed worker's last run.** A sandboxed worker's card also carries a **last run** line: when it ran, how long it took, whether it succeeded, and the pull request it opened. If the worker's own report said the run failed, or the sandbox exited with an error, Hive keeps any commits the run made off GitHub and the line reads `no PR opened: ` — for example `no PR opened: agent report status=failed: RPM install returned 401`. The same line appears when a configured publish preflight (`publish.verify`, for example a whole-suite `pytest --collect-only`) failed after the run: `no PR opened: verify failed (1/2): uv run pytest --collect-only -q (exit 2)`, with the command's output tail in the tooltip. The full reason is in the line's tooltip and in the full log's outcome block, where each verify command has its own `---- verify: … ----` section. -**Example.** A card says "needs login". You click **Login** and sign in again. Another card says `Now: working — no issue or pull request yet · started 50 min ago`. That worker has changed nothing through the hive for 50 minutes, so you open its log to see what it is doing. +**Example.** A card says "needs login". You click **Sign in Claude for all agents** and sign in again. That button is the one fleet-wide Claude sign-in, not a login for that card only, and it resumes every claude agent the login detector paused. If the card says **credential bridge broken (private stale file)** instead, the agent's link to the shared login was replaced by a private copy; the sign-in, the next credential-watchdog cycle or the agent's next restart re-links it. Another card says `Now: working — no issue or pull request yet · started 50 min ago`. That worker has changed nothing through the hive for 50 minutes, so you open its log to see what it is doing. **When it appears.** Always. diff --git a/src/docs/troubleshooting.md b/src/docs/troubleshooting.md index 4f0981ac6b..165b381538 100644 --- a/src/docs/troubleshooting.md +++ b/src/docs/troubleshooting.md @@ -304,6 +304,8 @@ To recover a paused agent: 1. Complete the CLI login for that backend outside the pause. Attach to the session (`tmux attach -t hive-`) and run the login command shown in the notification: `claude login`, `copilot auth login`, `gemini auth login`, or the backend-specific command. The picker expects an interactive OAuth/browser flow, so complete it from a terminal you control rather than leaving the unattended session blocked on it. 2. Resume the agent from the dashboard, or `POST /api/resume/{agent}`. If the pause outlived its session, the card offers a single `▶ start & resume` instead — see [Start on the agent card, not in tmux](#start-on-the-agent-card-not-in-tmux). +For `claude` agents you rarely need step 2. A successful dashboard Claude sign-in (the agent card's **Sign in Claude for all agents** button, which is one fleet-wide sign-in, not a per-agent login) resumes every claude agent that the login detector paused. It resumes only those: a pause with any other trigger, such as an operator's (`dashboard-api`), the fleet breaker's or a hook's, stays as it is. Each resume is in the Audit Log as `resume` with `trigger=claude-sign-in`, and the sign-in's `claude_auth_complete` entry lists the agents it resumed. The sign-in also re-links any agent whose credential link a token refresh had broken; such an agent's card says **credential bridge broken (private stale file)** until then (see [the agent watchdog notes](agent-watchdog.md#some-claude-agents-stay-on-login-expired-after-a-sign-in)). + If an agent returns to "needs login" immediately after resuming, the credentials themselves are the problem (expired token, revoked API key, or an account-level sign-out). Re-authenticate that backend's CLI as the agent user, then resume again so the fresh session is picked up. ## A permission prompt seems to block an agent diff --git a/src/pkg/dashboard/audit.go b/src/pkg/dashboard/audit.go index 9f6c29aa07..51e7028e2d 100644 --- a/src/pkg/dashboard/audit.go +++ b/src/pkg/dashboard/audit.go @@ -57,6 +57,7 @@ var auditSensitiveActions = map[string]bool{ "claude_auth_complete": true, "claude_auth_logout": true, "claude_auth_start": true, + "claude_credential_rebridged": true, "claude_token_missing": true, "config_agent_cadences": true, "config_agent_channels": true, diff --git a/src/pkg/dashboard/claude_auth.go b/src/pkg/dashboard/claude_auth.go index 0547e744f7..050814fa35 100644 --- a/src/pkg/dashboard/claude_auth.go +++ b/src/pkg/dashboard/claude_auth.go @@ -183,9 +183,13 @@ func (s *Server) handleClaudeAuthExchange(w http.ResponseWriter, r *http.Request } } - // Tell the agent manager to pick up the new token. + // Tell the agent manager to pick up the new token. With a usable shared + // credential this also re-bridges every agent whose link to it a token + // refresh had replaced with a private file (agent.Manager.ReloadClaudeToken). + var resumed []string if s.deps != nil && s.deps.AgentMgr != nil { s.deps.AgentMgr.ReloadClaudeToken() + resumed = s.resumeLoginPausedClaudeAgents(r) } // Clear the PKCE state. @@ -194,10 +198,14 @@ func (s *Server) handleClaudeAuthExchange(w http.ResponseWriter, r *http.Request s.claudeOAuthFlow.state = "" s.claudeOAuthFlow.mu.Unlock() - s.auditFromRequest(r, "claude_auth_complete", "", "") - s.deps.Logger.Info("Claude Code authenticated via OAuth") + detail := "" + if len(resumed) > 0 { + detail = auditDetail("resumed_login_paused", strings.Join(resumed, " ")) + } + s.auditFromRequest(r, "claude_auth_complete", detail, "") + s.deps.Logger.Info("Claude Code authenticated via OAuth", "resumed_login_paused", resumed) - jsonResponse(w, map[string]interface{}{"status": "complete"}) + jsonResponse(w, map[string]interface{}{"status": "complete", "resumed": resumed}) } // handleClaudeAuthLogout removes the Claude credentials. diff --git a/src/pkg/dashboard/claude_auth_resume.go b/src/pkg/dashboard/claude_auth_resume.go new file mode 100644 index 0000000000..518143247a --- /dev/null +++ b/src/pkg/dashboard/claude_auth_resume.go @@ -0,0 +1,54 @@ +package dashboard + +import ( + "net/http" + "sort" +) + +// claudeSignInResumeTrigger is the pause trigger recorded when a dashboard +// Claude sign-in resumes an agent. +const claudeSignInResumeTrigger = "claude-sign-in" + +// loginDetectorPauseTrigger is the trigger the login detector pauses with +// (pkg/loginscan). A pause carries its trigger in crux.Process.PausedTrigger, +// which is how the sign-in tells the detector's own pauses apart from an +// operator's ("dashboard-api"), the fleet breaker's, a hook's, a relay's or +// any other system pause. +const loginDetectorPauseTrigger = "login-detector" + +// resumeLoginPausedClaudeAgents resumes the claude agents the login detector +// paused, and only those, after a successful fleet-wide Claude sign-in. Those +// pauses mean "this agent is at a login prompt"; the sign-in is the fix, so +// leaving them paused would make the owner resume every agent by hand. Every +// other pause is someone's decision and is left alone. Each resume is audited +// under the signing-in user. Returns the resumed agent names, sorted. +func (s *Server) resumeLoginPausedClaudeAgents(r *http.Request) []string { + statuses := s.deps.AgentMgr.AllStatuses() + names := make([]string, 0, len(statuses)) + for name := range statuses { + names = append(names, name) + } + sort.Strings(names) + var resumed []string + for _, name := range names { + proc := statuses[name] + if proc == nil || !proc.Paused || proc.PausedTrigger != loginDetectorPauseTrigger { + continue + } + backend := proc.Config.Backend + if proc.BackendOverride != "" { + backend = proc.BackendOverride + } + if backend != "claude" { + // A Claude sign-in does not fix a Copilot or Gemini login prompt. + continue + } + if err := s.deps.AgentMgr.Resume(s.deps.Ctx, name, claudeSignInResumeTrigger, "Claude sign-in completed; releasing the login-detector pause"); err != nil { + s.deps.Logger.Warn("Claude sign-in: resume of login-paused agent failed", "agent", name, "error", err) + continue + } + s.auditFromRequest(r, "resume", auditDetail("trigger", claudeSignInResumeTrigger, "prev_trigger", loginDetectorPauseTrigger), name) + resumed = append(resumed, name) + } + return resumed +} diff --git a/src/pkg/dashboard/claude_auth_resume_test.go b/src/pkg/dashboard/claude_auth_resume_test.go new file mode 100644 index 0000000000..db2cc8aaae --- /dev/null +++ b/src/pkg/dashboard/claude_auth_resume_test.go @@ -0,0 +1,128 @@ +package dashboard + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/claude" + "github.com/hivecommons/hive/crux/cruxtest" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/governor" +) + +// A successful dashboard Claude sign-in must resume the claude agents the +// login detector paused, and nothing else. On hive-wild-mole two sign-ins +// (14:31Z, 14:50Z) wrote a valid shared credential and every login-paused +// agent stayed paused; the owner had to find and resume each one by hand. +// Operator pauses, fleet-breaker, hook and relay pauses are someone's +// decision and must survive the sign-in; a Copilot agent's login prompt is +// not fixed by a Claude login. +func TestClaudeSignIn_ResumesOnlyLoginDetectorPausedClaudeAgents(t *testing.T) { + stubClaudeSeams(t) + s := claudeDeepServer(t) + rt := cruxtest.NewRecorder() + s.deps.AgentMgr = rt + s.deps.Ctx = context.Background() + + paused := func(backend, trigger string) *crux.Process { + return &crux.Process{ + Config: config.AgentConfig{Backend: backend}, + State: crux.StatePaused, + Paused: true, + PausedTrigger: trigger, + PausedReason: "test", + } + } + rt.Procs["login-claude"] = paused("claude", "login-detector") + rt.Procs["operator-claude"] = paused("claude", "dashboard-api") + rt.Procs["breaker-claude"] = paused("claude", "fleet-breaker") + rt.Procs["hook-claude"] = paused("claude", "hook") + rt.Procs["relay-claude"] = paused("claude", "contributor-relay") + rt.Procs["login-copilot"] = paused("copilot", "login-detector") + override := paused("copilot", "login-detector") + override.BackendOverride = "claude" + rt.Procs["login-override-claude"] = override + rt.Procs["running-claude"] = &crux.Process{Config: config.AgentConfig{Backend: "claude"}, State: crux.StateRunning} + for name, p := range rt.Procs { + p.Name = name + } + + s.claudeOAuthFlow.codeVerifier = "verifier" + s.claudeOAuthFlow.expiresAt = time.Now().Add(10 * time.Minute) + claudeExchange = func(code, verifier, redirect string) (*claude.OAuthTokens, error) { + return &claude.OAuthTokens{AccessToken: "fake-access", RefreshToken: "fake-refresh", ExpiresAt: time.Now().Add(8 * time.Hour).UnixMilli()}, nil + } + + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/claude-auth/exchange", strings.NewReader(`{"code":"good-code"}`)) + markOwnerRequest(req) + s.handleClaudeAuthExchange(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String()) + } + + var resumed []string + reloadAt, firstResumeAt := -1, -1 + for i, c := range rt.Calls() { + switch c.Method { + case "ReloadClaudeToken": + if reloadAt < 0 { + reloadAt = i + } + case "Resume": + if firstResumeAt < 0 { + firstResumeAt = i + } + resumed = append(resumed, c.Args[0].(string)) + if c.Args[1] != "claude-sign-in" { + t.Errorf("resume of %v recorded trigger %v, want claude-sign-in", c.Args[0], c.Args[1]) + } + } + } + want := []string{"login-claude", "login-override-claude"} + if strings.Join(resumed, ",") != strings.Join(want, ",") { + t.Fatalf("sign-in resumed %v, want exactly %v", resumed, want) + } + if reloadAt < 0 || firstResumeAt < reloadAt { + t.Errorf("agents must be resumed after the token reload (which re-bridges credentials): reload at %d, first resume at %d", reloadAt, firstResumeAt) + } + for _, name := range []string{"operator-claude", "breaker-claude", "hook-claude", "relay-claude", "login-copilot"} { + if !rt.Procs[name].Paused { + t.Errorf("%s (trigger %q) was resumed by the sign-in; only login-detector pauses may be", name, rt.Procs[name].PausedTrigger) + } + } + m := decodeJSONMap(t, rec.Body) + if got, _ := m["resumed"].([]interface{}); len(got) != 2 { + t.Errorf("response resumed = %v, want the two resumed agents", m["resumed"]) + } +} + +// TestBuildAgents_CredentialBridgeBroken: the status payload carries the +// bridge-broken reason so the card can name it instead of a generic +// needs-login. +func TestBuildAgents_CredentialBridgeBroken(t *testing.T) { + broken := newBlockerProc("architect", config.AgentConfig{Backend: "claude", Enabled: true}, nil) + broken.NeedsLogin = true + broken.CredentialBridgeBroken = true + healthy := newBlockerProc("coder", config.AgentConfig{Backend: "claude", Enabled: true}, nil) + statuses := map[string]*crux.Process{"architect": broken, "coder": healthy} + cfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{ + "architect": {Backend: "claude", Enabled: true}, + "coder": {Backend: "claude", Enabled: true}, + }}} + got := map[string]FrontendAgent{} + for _, a := range buildAgents(statuses, cfg, governor.State{Mode: governor.ModeIdle}) { + got[a.Name] = a + } + if !got["architect"].CredentialBridgeBroken { + t.Error("architect: credentialBridgeBroken not carried into the status payload") + } + if got["coder"].CredentialBridgeBroken { + t.Error("coder: healthy agent reported a broken credential bridge") + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index aa7923fcfe..7e165a06de 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -980,6 +980,12 @@ type FrontendAgent struct { NoCadence bool `json:"noCadence"` NeedsLogin bool `json:"needsLogin"` LoginURL string `json:"loginURL,omitempty"` + + // CredentialBridgeBroken: a Claude token refresh replaced this agent's + // link to the shared login with a private file (crux.Process). The card + // names it instead of a generic needs-login. + CredentialBridgeBroken bool `json:"credentialBridgeBroken,omitempty"` + AuthAvailable bool `json:"authAvailable"` AuthKnown bool `json:"authKnown"` CLI string `json:"cli"` diff --git a/src/pkg/dashboard/static-src/js/agent-cards.js b/src/pkg/dashboard/static-src/js/agent-cards.js index 6b6397a04e..10f1ccb760 100644 --- a/src/pkg/dashboard/static-src/js/agent-cards.js +++ b/src/pkg/dashboard/static-src/js/agent-cards.js @@ -699,6 +699,32 @@ kbShowModal('🗣 Advisor — ' + escapeHtml(agentName), bodyHtml, { width: '720px' }); } + /* A Claude token refresh replaces an agent's link to the shared login + ($HOME/.claude/.credentials.json -> /data/home/.claude/.credentials.json) + with a private copy. The server reports it as credentialBridgeBroken. + A sign-in rewrites the shared file, which that agent no longer reads, + so a generic "needs login" sends the owner round a loop that cannot + work. The card names the real condition instead. */ + const CREDENTIAL_BRIDGE_BROKEN_LABEL = 'credential bridge broken (private stale file)'; + function credentialBridgeHintHtml(a) { + if (!a || a.credentialBridgeBroken !== true) return ''; + return ``; + } + function needsLoginBadgeTitle(a) { + return (a && a.credentialBridgeBroken === true) ? CREDENTIAL_BRIDGE_BROKEN_LABEL : 'CLI needs login'; + } + /* The Claude login on an agent card is NOT a per-agent login: it runs the + one dashboard sign-in that writes the shared credential every claude + agent uses. The label and tooltip say so. */ + const CLAUDE_FLEET_SIGNIN_LABEL = 'Sign in Claude for all agents'; + const CLAUDE_FLEET_SIGNIN_HELP = 'Fleet-wide sign-in, not a login for this agent only: it replaces the one shared Claude login every claude agent uses, re-links agents whose link a token refresh broke, and resumes agents the login detector paused. Operator pauses are left alone.'; + function claudeLoginButtonHtml(a, needsLogin, claudeIcon) { + if (needsLogin) { + return ''; + } + return ''; + } + /* SINGLE source of truth for the 🔑 "needs login" badge. Mirrors the server-side precedence rule in pkg/agent/authprobe.go: @@ -1037,7 +1063,7 @@ return `
${agentSpanHandle} -
${agentOrderHandle}${a.emoji ? a.emoji + ' ' : ''}${esc(a.displayName || a.name)}${needsLogin ? ' \uD83D\uDD11' : ''}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${disabledBadge}${continuousBadge}${replicaBadge} ${agentPowerSwitchHtml(a)} ${isDisabled ? disabledEnableBtn : ''}${toggleBtn}${neverScheduledChipHtml(a, configTarget)} ${sessionActions}
+
${agentOrderHandle}${a.emoji ? a.emoji + ' ' : ''}${esc(a.displayName || a.name)}${needsLogin ? ' \uD83D\uDD11' : ''}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${disabledBadge}${continuousBadge}${replicaBadge} ${agentPowerSwitchHtml(a)} ${isDisabled ? disabledEnableBtn : ''}${toggleBtn}${neverScheduledChipHtml(a, configTarget)} ${sessionActions}
${agentStateText(a)}${pauseInfoIcon(a)}${(() => { if (a.structuredStatus === 'BLOCKED') return statusBadgeHTML('blocked', 'blocked', a.statusEvidence, 'blocked'); if (a.structuredStatus === 'NEEDS_CONTEXT') return statusBadgeHTML('needs_context', 'needs context', a.statusEvidence, 'needs-context'); @@ -1050,7 +1076,7 @@ ${agentRunLineHtml(a)} ${agentBlockerLineHtml(a)} ${repeatFailureLineHtml(a)} - ${terminalCopyHintHtml(needsLogin, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} + ${credentialBridgeHintHtml(a)}${terminalCopyHintHtml(needsLogin, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} ${(() => { // Last upstream/launch error stays on its own line below the state // badge, never behind the working-indicator dot — previously the @@ -1085,11 +1111,11 @@ const claudeIcon = ''; const copilotIcon = ''; if (needsLogin) { - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, true, claudeIcon); if (isCopilot) return ''; return ''; } - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, false, claudeIcon); if (isCopilot) return ''; return ''; })()}
diff --git a/src/pkg/dashboard/static-src/js/agent-detail.js b/src/pkg/dashboard/static-src/js/agent-detail.js index e25417f4cc..6dd30e0788 100644 --- a/src/pkg/dashboard/static-src/js/agent-detail.js +++ b/src/pkg/dashboard/static-src/js/agent-detail.js @@ -593,11 +593,11 @@ const claudeIcon = ''; const copilotIcon = ''; if (_needsLogin) { - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, true, claudeIcon); if (isCopilot) return ''; return ''; } - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, false, claudeIcon); if (isCopilot) return ''; return ''; })()}
@@ -657,7 +657,7 @@ /* 'disabled' outranks 'down': both reach here with state!=='running', but a switched-off agent is not a fault, and labelling it "down" sent operators looking for a crash that never happened. */ - const stateLabel = agentSessionUnavailable(a) ? 'disabled' : needsLoginDown ? 'needs login' : isStopped ? (agentSandboxDownLabel(a) || (a.operatorStopped ? 'stopped by operator' : 'down')) : isOnDemand ? 'on demand' : isPaused ? 'paused' : isOff ? agentCadenceOffLabel() : isRunning ? (a.awaitingCI ? 'Waiting on CI' : 'working') : 'idle'; + const stateLabel = agentSessionUnavailable(a) ? 'disabled' : needsLoginDown ? (a.credentialBridgeBroken === true ? CREDENTIAL_BRIDGE_BROKEN_LABEL : 'needs login') : isStopped ? (agentSandboxDownLabel(a) || (a.operatorStopped ? 'stopped by operator' : 'down')) : isOnDemand ? 'on demand' : isPaused ? 'paused' : isOff ? agentCadenceOffLabel() : isRunning ? (a.awaitingCI ? 'Waiting on CI' : 'working') : 'idle'; const kickId = `oc-kick-${a.name}`; const prevInput = document.getElementById(kickId); @@ -832,7 +832,7 @@ detail.innerHTML = `
- ${esc(a.displayName || a.name)}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${needsLoginDown ? '\uD83D\uDD11' : ''} + ${esc(a.displayName || a.name)}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${needsLoginDown ? '\uD83D\uDD11' : ''} ${agentRunLineHtml(a)} ${stateLabel}${pauseInfoIcon(a)}
@@ -868,7 +868,7 @@ ${agentNowHtml(a)}
${agentBlockerLineHtml(a)}${neverScheduledChipHtml(a, a.name)}${repeatFailureLineHtml(a)}
- ${terminalCopyHintHtml(needsLoginDown, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} + ${credentialBridgeHintHtml(a)}${terminalCopyHintHtml(needsLoginDown, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} ${ocDetailFieldsHtml(a, isPaused, isOff, isOnDemand)} ${subAgentModelsHtml(a)}
${agentIndicators(a.name)}
diff --git a/src/pkg/dashboard/static-src/js/gh-auth.js b/src/pkg/dashboard/static-src/js/gh-auth.js index 35e4c6bf6c..364deb848e 100644 --- a/src/pkg/dashboard/static-src/js/gh-auth.js +++ b/src/pkg/dashboard/static-src/js/gh-auth.js @@ -804,7 +804,8 @@ overlay.className = 'gh-auth-overlay cred-dialog-overlay'; var countdownSec = CLAUDE_AUTH_TAB_DELAY_MS / 1000; overlay.innerHTML = '
' + - '

Login Claude Code

' + + '

Sign in Claude for all agents

' + + '

This is the fleet-wide sign-in: it replaces the one shared Claude login every claude agent uses, then resumes the agents the login detector paused.

' + '
' + 'Opening Claude login in ' + countdownSec + 's…
' + '
    ' + diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 231c7a2c5f..b35e72d63d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -12557,11 +12557,11 @@

    Where to get help

    const claudeIcon = ''; const copilotIcon = ''; if (_needsLogin) { - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, true, claudeIcon); if (isCopilot) return ''; return ''; } - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, false, claudeIcon); if (isCopilot) return ''; return ''; })()}
@@ -12621,7 +12621,7 @@

Where to get help

/* 'disabled' outranks 'down': both reach here with state!=='running', but a switched-off agent is not a fault, and labelling it "down" sent operators looking for a crash that never happened. */ - const stateLabel = agentSessionUnavailable(a) ? 'disabled' : needsLoginDown ? 'needs login' : isStopped ? (agentSandboxDownLabel(a) || (a.operatorStopped ? 'stopped by operator' : 'down')) : isOnDemand ? 'on demand' : isPaused ? 'paused' : isOff ? agentCadenceOffLabel() : isRunning ? (a.awaitingCI ? 'Waiting on CI' : 'working') : 'idle'; + const stateLabel = agentSessionUnavailable(a) ? 'disabled' : needsLoginDown ? (a.credentialBridgeBroken === true ? CREDENTIAL_BRIDGE_BROKEN_LABEL : 'needs login') : isStopped ? (agentSandboxDownLabel(a) || (a.operatorStopped ? 'stopped by operator' : 'down')) : isOnDemand ? 'on demand' : isPaused ? 'paused' : isOff ? agentCadenceOffLabel() : isRunning ? (a.awaitingCI ? 'Waiting on CI' : 'working') : 'idle'; const kickId = `oc-kick-${a.name}`; const prevInput = document.getElementById(kickId); @@ -12796,7 +12796,7 @@

Where to get help

detail.innerHTML = `
- ${esc(a.displayName || a.name)}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${needsLoginDown ? '\uD83D\uDD11' : ''} + ${esc(a.displayName || a.name)}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${needsLoginDown ? '\uD83D\uDD11' : ''} ${agentRunLineHtml(a)} ${stateLabel}${pauseInfoIcon(a)}
@@ -12832,7 +12832,7 @@

Where to get help

${agentNowHtml(a)}
${agentBlockerLineHtml(a)}${neverScheduledChipHtml(a, a.name)}${repeatFailureLineHtml(a)}
- ${terminalCopyHintHtml(needsLoginDown, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} + ${credentialBridgeHintHtml(a)}${terminalCopyHintHtml(needsLoginDown, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} ${ocDetailFieldsHtml(a, isPaused, isOff, isOnDemand)} ${subAgentModelsHtml(a)}
${agentIndicators(a.name)}
@@ -29491,6 +29491,32 @@

All labels

kbShowModal('🗣 Advisor — ' + escapeHtml(agentName), bodyHtml, { width: '720px' }); } + /* A Claude token refresh replaces an agent's link to the shared login + ($HOME/.claude/.credentials.json -> /data/home/.claude/.credentials.json) + with a private copy. The server reports it as credentialBridgeBroken. + A sign-in rewrites the shared file, which that agent no longer reads, + so a generic "needs login" sends the owner round a loop that cannot + work. The card names the real condition instead. */ + const CREDENTIAL_BRIDGE_BROKEN_LABEL = 'credential bridge broken (private stale file)'; + function credentialBridgeHintHtml(a) { + if (!a || a.credentialBridgeBroken !== true) return ''; + return ``; + } + function needsLoginBadgeTitle(a) { + return (a && a.credentialBridgeBroken === true) ? CREDENTIAL_BRIDGE_BROKEN_LABEL : 'CLI needs login'; + } + /* The Claude login on an agent card is NOT a per-agent login: it runs the + one dashboard sign-in that writes the shared credential every claude + agent uses. The label and tooltip say so. */ + const CLAUDE_FLEET_SIGNIN_LABEL = 'Sign in Claude for all agents'; + const CLAUDE_FLEET_SIGNIN_HELP = 'Fleet-wide sign-in, not a login for this agent only: it replaces the one shared Claude login every claude agent uses, re-links agents whose link a token refresh broke, and resumes agents the login detector paused. Operator pauses are left alone.'; + function claudeLoginButtonHtml(a, needsLogin, claudeIcon) { + if (needsLogin) { + return ''; + } + return ''; + } + /* SINGLE source of truth for the 🔑 "needs login" badge. Mirrors the server-side precedence rule in pkg/agent/authprobe.go: @@ -29829,7 +29855,7 @@

All labels

return `
${agentSpanHandle} -
${agentOrderHandle}${a.emoji ? a.emoji + ' ' : ''}${esc(a.displayName || a.name)}${needsLogin ? ' \uD83D\uDD11' : ''}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${disabledBadge}${continuousBadge}${replicaBadge} ${agentPowerSwitchHtml(a)} ${isDisabled ? disabledEnableBtn : ''}${toggleBtn}${neverScheduledChipHtml(a, configTarget)} ${sessionActions}
+
${agentOrderHandle}${a.emoji ? a.emoji + ' ' : ''}${esc(a.displayName || a.name)}${needsLogin ? ' \uD83D\uDD11' : ''}${a.sandboxed ? ' ' + statusBadgeHTML('ready', 'sandboxed', 'Sandboxed runner active', 'done') : ''}${disabledBadge}${continuousBadge}${replicaBadge} ${agentPowerSwitchHtml(a)} ${isDisabled ? disabledEnableBtn : ''}${toggleBtn}${neverScheduledChipHtml(a, configTarget)} ${sessionActions}
${agentStateText(a)}${pauseInfoIcon(a)}${(() => { if (a.structuredStatus === 'BLOCKED') return statusBadgeHTML('blocked', 'blocked', a.statusEvidence, 'blocked'); if (a.structuredStatus === 'NEEDS_CONTEXT') return statusBadgeHTML('needs_context', 'needs context', a.statusEvidence, 'needs-context'); @@ -29842,7 +29868,7 @@

All labels

${agentRunLineHtml(a)} ${agentBlockerLineHtml(a)} ${repeatFailureLineHtml(a)} - ${terminalCopyHintHtml(needsLogin, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} + ${credentialBridgeHintHtml(a)}${terminalCopyHintHtml(needsLogin, agentSessionUnavailable(a), a.name, a.loginURL, a.backendAuthStatus, a.backendAuthLastError, a.statusEvidence, a.inferenceLastError)} ${(() => { // Last upstream/launch error stays on its own line below the state // badge, never behind the working-indicator dot — previously the @@ -29877,11 +29903,11 @@

All labels

const claudeIcon = ''; const copilotIcon = ''; if (needsLogin) { - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, true, claudeIcon); if (isCopilot) return ''; return ''; } - if (isClaude) return ''; + if (isClaude) return claudeLoginButtonHtml(a, false, claudeIcon); if (isCopilot) return ''; return ''; })()}
@@ -72296,7 +72322,8 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

Login Claude Code' + + '

Sign in Claude for all agents

' + + '

This is the fleet-wide sign-in: it replaces the one shared Claude login every claude agent uses, then resumes the agents the login detector paused.

' + '
' + 'Opening Claude login in ' + countdownSec + 's…
' + '
    ' + diff --git a/src/pkg/dashboard/status_builder.go b/src/pkg/dashboard/status_builder.go index 84ab2699fb..616fab52e9 100644 --- a/src/pkg/dashboard/status_builder.go +++ b/src/pkg/dashboard/status_builder.go @@ -1421,6 +1421,7 @@ func buildAgentsWithHidden(statuses map[string]*crux.Process, cfg *config.Config // (BackendRequiresInteractiveAuth) so the badge and control only // ever appear for a backend where a login URL is a real possibility. a.NeedsLogin = proc.NeedsLogin && crux.BackendRequiresInteractiveAuth(cli) + a.CredentialBridgeBroken = proc.CredentialBridgeBroken // Per-agent probe FIRST: it resolves this agent's own per-UID HOME and // answers "does this backend even have an interactive login?" before // looking at any file. The backend-level probe (shared legacy path diff --git a/src/pkg/dashboard/webstatic/claude_credential_bridge_ui_test.go b/src/pkg/dashboard/webstatic/claude_credential_bridge_ui_test.go new file mode 100644 index 0000000000..d223a1c714 --- /dev/null +++ b/src/pkg/dashboard/webstatic/claude_credential_bridge_ui_test.go @@ -0,0 +1,40 @@ +package webstatic + +import ( + "os" + "strings" + "testing" +) + +// TestAgentCard_NamesBrokenCredentialBridge: when a Claude token refresh has +// replaced an agent's link to the shared login with a private file, the card +// must say so (the server sends credentialBridgeBroken) instead of a generic +// needs-login that sends the owner round a sign-in that cannot reach the +// agent. The agent-card Claude button runs the FLEET-WIDE sign-in, so it must +// say that too: on hive-wild-mole the per-agent "Login" button looked like a +// per-agent fix and was not one. +func TestAgentCard_NamesBrokenCredentialBridge(t *testing.T) { + body, err := os.ReadFile("../static/index.html") + if err != nil { + t.Fatal(err) + } + html := string(body) + for _, want := range []string{ + "credential bridge broken (private stale file)", + "a.credentialBridgeBroken", + "Sign in Claude for all agents", + } { + if !strings.Contains(html, want) { + t.Errorf("index.html lacks %q", want) + } + } + // The old per-agent wording must be gone from the Claude login buttons. + for _, stale := range []string{ + `title="Authenticate Claude Code CLI"`, + `title="Re-authenticate Claude Code CLI"`, + } { + if strings.Contains(html, stale) { + t.Errorf("index.html still labels the fleet-wide Claude sign-in as a per-agent login: %s", stale) + } + } +} From 61aafae61dc0106abf638a1eb8529833809eeac3 Mon Sep 17 00:00:00 2001 From: Danathar Date: Sun, 8 Nov 2026 10:49:23 -0500 Subject: [PATCH 2/2] chore(agent): keep manager_tokens.go within its file-size ratchet The crux file-size ratchet caps crux/agent/manager_tokens.go at 975 lines. The new ReloadClaudeToken doc comment pushed it to 981. The comment now says the same in four lines. No code change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/crux/agent/manager_tokens.go | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/crux/agent/manager_tokens.go b/src/crux/agent/manager_tokens.go index 8e5e27f52d..ec25c777d2 100644 --- a/src/crux/agent/manager_tokens.go +++ b/src/crux/agent/manager_tokens.go @@ -22,15 +22,9 @@ type ( ) // ReloadClaudeToken re-reads the Claude credentials file and updates the -// cached token. Called by the dashboard after a successful OAuth login (and -// after a logout). -// -// When the shared credential is usable afterwards — a sign-in just wrote it — -// it also re-bridges every agent whose credential link a token refresh had -// replaced with a private file. Without that, the new login never reaches -// those agents: they keep reading their private, often revoked, copy and -// every re-login is wasted. After a logout the shared file is gone, so -// nothing is re-bridged. +// cached token (dashboard sign-in or logout). When the shared credential is +// usable afterwards, it re-bridges agents whose link a token refresh replaced +// with a private file, so the new login reaches them. func (m *Manager) ReloadClaudeToken() { m.mu.Lock() m.claudeAuthToken = claude.ReadAccessToken(claude.CredentialsPath)