From d261ce8863fdbdac1ff60dd37f4b4a2c0d0230a1 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Fri, 30 Oct 2026 11:17:03 -0400 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Show=20the=20upgrade=20animation=20?= =?UTF-8?q?for=20every=20roll=20(announce=20+=20SIGTERM=20fallback)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dashboard's bee/hive upgrade animation only played for self-upgrades: upgradeProgress derived from the drain latch, PVC marker and hub policy, so a hub kubectl roll, an operator rollout restart or a plain SIGTERM showed nothing until the SSE stream dropped and the page reconnected. Two layers, both rendering through the same SPA component: - Intent before the kill: POST /api/upgrade/announce (owner-only) and the heartbeat response's upgrade_announce (sent by the hub while its latch is open onto a build the hub-managed spoke is not running) mark upgradeProgress state=pulling/phase=announced with the target and publish an SSE 'upgrading' event. - Fallback at the kill: the first SIGTERM hook publishes phase=restarting (keeping an announced or hub-armed target) before the contributor drain, so the banner is up before the stream drops. The SPA keeps a roll record across the reconnect, polls /api/version every 2s while the pod is down, shows the new pod's boot phase (startupPhase from cmd/hive's boot sequence) and on reconnect compares build hash and process startedAt: 'Upgraded to ✓' or 'Restarted ✓' with the 15s toast countdown; the silent hash-change reload waits for that. ?demo=upgrade and Settings → Diagnostics → Preview upgrade animation walk the same state machine on demand. Closes #15788 Signed-off-by: Andrew Anderson --- .../added-15788-roll-upgrade-animation.md | 1 + dashboard/openapi.json | 67 +++ src/cmd/hive/boot_heartbeat_deps_test.go | 11 +- src/cmd/hive/boot_sequence.go | 27 +- src/cmd/hive/boot_sequence_test.go | 31 +- src/cmd/hive/main.go | 18 + src/cmd/hive/self_upgrade_drain.go | 5 + src/docs/api-reference/agents-and-controls.md | 72 ++-- src/docs/api-reference/auth.md | 20 +- src/docs/api-reference/beads.md | 10 +- src/docs/api-reference/configuration.md | 174 ++++---- .../api-reference/cost-tokens-telemetry.md | 16 +- src/docs/api-reference/dashboard-misc.md | 65 +-- .../api-reference/health-status-events.md | 80 ++-- src/docs/api-reference/inception.md | 28 +- src/docs/api-reference/knowledge.md | 88 ++-- src/docs/api-reference/nous.md | 50 +-- src/docs/api-reference/packs-and-acmm.md | 28 +- src/docs/api-reference/snapshots-and-style.md | 8 +- src/docs/dashboard-standalone-upgrades.md | 35 ++ src/pkg/dashboard/api.go | 1 + src/pkg/dashboard/api_version.go | 11 + .../dashboard/roll_upgrade_harness_test.go | 25 ++ src/pkg/dashboard/roll_upgrade_state.test.js | 185 ++++++++ src/pkg/dashboard/server.go | 9 +- .../dashboard/sidebar_version_panel_test.go | 4 + .../static-src/css/sections-collapse.css | 6 + src/pkg/dashboard/static-src/js/acmm.js | 7 + src/pkg/dashboard/static-src/js/debug-logs.js | 5 + .../dashboard/static-src/js/sse-bootstrap.js | 13 +- src/pkg/dashboard/static-src/js/version.js | 280 +++++++++++- src/pkg/dashboard/static/index.html | 311 ++++++++++++- src/pkg/dashboard/upgrade_announce.go | 408 ++++++++++++++++++ src/pkg/dashboard/upgrade_announce_test.go | 190 ++++++++ src/pkg/dashboard/upgrade_progress.go | 18 +- .../dashboard/version_provenance_ui_test.go | 1 + src/pkg/hub/heartbeat.go | 12 +- src/pkg/hub/heartbeat_upgrade_announce.go | 41 ++ .../hub/heartbeat_upgrade_announce_test.go | 41 ++ src/pkg/hub/server.go | 11 + src/pkg/hub/spoke/heartbeat.go | 16 + ...artbeat_reconnect_upgrade_coverage_test.go | 12 +- src/pkg/hub/spoke/upgrade_progress.go | 41 ++ 43 files changed, 2134 insertions(+), 348 deletions(-) create mode 100644 changelog.d/added-15788-roll-upgrade-animation.md create mode 100644 src/pkg/dashboard/roll_upgrade_harness_test.go create mode 100644 src/pkg/dashboard/roll_upgrade_state.test.js create mode 100644 src/pkg/dashboard/upgrade_announce.go create mode 100644 src/pkg/dashboard/upgrade_announce_test.go create mode 100644 src/pkg/hub/heartbeat_upgrade_announce.go create mode 100644 src/pkg/hub/heartbeat_upgrade_announce_test.go diff --git a/changelog.d/added-15788-roll-upgrade-animation.md b/changelog.d/added-15788-roll-upgrade-animation.md new file mode 100644 index 0000000000..073a87a69a --- /dev/null +++ b/changelog.d/added-15788-roll-upgrade-animation.md @@ -0,0 +1 @@ +- The dashboard's upgrade animation now plays for every pod roll, not only self-upgrades ([#15788](https://github.com/hivecommons/hive/issues/15788)): the hub announces hub-managed rolls through the heartbeat (`upgrade_announce`), operators can announce theirs with `POST /api/upgrade/announce` (owner-only; one-liner in `dashboard-standalone-upgrades.md`), and a SIGTERM with no announce still publishes an SSE `upgrading` event with `phase: restarting` before the stream drops. The banner survives the reconnect, shows the new pod's boot phase from `/api/version.startupPhase`, and reads **Upgraded to `` ✓** or **Restarted ✓** by comparing build hash and process `startedAt`. Preview it any time with `?demo=upgrade` or Settings → Diagnostics → *Preview upgrade animation*. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 8d1a272193..af69cfdd77 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -29621,6 +29621,73 @@ } } }, + "/api/upgrade/announce": { + "post": { + "tags": [ + "System" + ], + "summary": "Announce a pod roll before it happens", + "description": "Marks this spoke's upgradeProgress as state=pulling/phase=announced with the given target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation before the pod is killed (#15788). Used by the hub (also delivered via the heartbeat response) and by operator scripts ahead of `kubectl rollout restart`. A SIGTERM afterwards publishes phase=restarting from the same record; an announce with no kill expires after 15 minutes. Requires owner role.", + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "target": { + "type": "string", + "description": "Commit SHA or image tag the pod restarts onto; omit for a plain restart" + }, + "version": { + "type": "string", + "description": "Alias of target" + }, + "source": { + "type": "string", + "enum": [ + "hub", + "operator" + ], + "description": "Who is rolling the pod; anything else is recorded as operator" + }, + "reason": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Announce recorded", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "upgradeProgress": { + "type": "object", + "description": "The spoke's upgradeProgress as now reported by /api/status and /api/version (state, phase, source, target, from, detail, startedAt)" + } + } + } + } + } + }, + "400": { + "description": "Invalid JSON body" + }, + "403": { + "description": "Owner access required" + } + } + } + }, "/api/snapshot": { "get": { "tags": [ diff --git a/src/cmd/hive/boot_heartbeat_deps_test.go b/src/cmd/hive/boot_heartbeat_deps_test.go index 3d730748d8..1447cebd4f 100644 --- a/src/cmd/hive/boot_heartbeat_deps_test.go +++ b/src/cmd/hive/boot_heartbeat_deps_test.go @@ -180,8 +180,9 @@ func TestBootHeartbeatWith_PublishesIdentityBeforeTheLoopAndWiresEveryCallback(t heartbeatCallback[spoke.GatewayConfigCallback](t, f) heartbeatCallback[spoke.ClusterIDCallback](t, f) heartbeatCallback[spoke.FreshStatusCollector](t, f) - if len(f.callbacks) != 14 { - t.Fatalf("registered %d callbacks, want 14 (one of each)", len(f.callbacks)) + heartbeatCallback[spoke.UpgradeAnnounceCallback](t, f) + if len(f.callbacks) != 15 { + t.Fatalf("registered %d callbacks, want 15 (one of each)", len(f.callbacks)) } // The collector honours a runtime hub.enabled=false without being torn @@ -230,6 +231,12 @@ func TestBootHeartbeatWith_CallbacksReconcileRunningConfig(t *testing.T) { banner(nil) heartbeatCallback[spoke.UpgradePolicyCallback](t, f)(&spoke.HeartbeatUpgradePolicy{HubManaged: true}) heartbeatCallback[spoke.UpgradePolicyCallback](t, f)(nil) + // A hub roll announce (#15788) lands on the dashboard as an in-flight + // upgrade so the operator sees the animation before the kill. + heartbeatCallback[spoke.UpgradeAnnounceCallback](t, f)(&spoke.UpgradeAnnounce{Target: "0123456789abcdef", Source: spoke.UpgradeSourceHub}) + if p := b.dashSrv.AnnounceRestart(time.Now()); p.Target != "0123456" || p.Source != spoke.UpgradeSourceHub { + t.Fatalf("announce did not reach the dashboard: %+v", p) + } // Unknown agent: warn, never panic — the hub may name an agent this // spoke's pack no longer has. diff --git a/src/cmd/hive/boot_sequence.go b/src/cmd/hive/boot_sequence.go index 993d584634..8a5af5d6d8 100644 --- a/src/cmd/hive/boot_sequence.go +++ b/src/cmd/hive/boot_sequence.go @@ -66,11 +66,36 @@ func defaultBootSequenceNames() []string { func defaultBootSequence() bootSequence { seq := bootSequence{config: (*boot).bootConfig, loop: (*boot).runLoop} for _, p := range defaultBootPhases() { - seq.phases = append(seq.phases, p.run) + seq.phases = append(seq.phases, notingPhase(p)) } return seq } +// bootPhaseFirstEval is the phase name runLoop reports once every boot +// phase has run and the governor is about to publish its first status. +const bootPhaseFirstEval = "firstEval" + +// notingPhase wraps a phase so the dashboard learns its name as it starts +// (#15788): a browser reconnecting onto a fresh pod reads startupPhase from +// /api/status and shows "starting: opening stores" instead of a bare +// spinner. Phases before bootDashboard have no server to tell and are +// skipped by noteBootPhase. +func notingPhase(p namedPhase) bootPhase { + return func(b *boot) bool { + b.noteBootPhase(p.name) + return p.run(b) + } +} + +// noteBootPhase records the running boot phase on the dashboard server, +// when one exists yet. +func (b *boot) noteBootPhase(name string) { + if b == nil || b.dashSrv == nil { + return + } + b.dashSrv.SetStartupPhase(name) +} + // runBoot drives one hive process through seq. b.cleanup runs on every // return path, including a config veto. func runBoot(b *boot, seq bootSequence) { diff --git a/src/cmd/hive/boot_sequence_test.go b/src/cmd/hive/boot_sequence_test.go index a25bec19ee..6a4e2af479 100644 --- a/src/cmd/hive/boot_sequence_test.go +++ b/src/cmd/hive/boot_sequence_test.go @@ -1,10 +1,14 @@ package main import ( + "io" + "log/slog" "reflect" "runtime" "strings" "testing" + + "github.com/hivecommons/hive/pkg/dashboard" ) func funcName(f interface{}) string { @@ -29,10 +33,11 @@ func TestDefaultBootSequenceOrder(t *testing.T) { if len(seq.phases) != len(want) { t.Fatalf("phase count = %d, want %d", len(seq.phases), len(want)) } - // step() wraps non-veto phases in a closure, so their names are not - // recoverable through the func value; only the veto-capable bootAdvisory - // is pinned by name. defaultBootSequenceNames pins the rest. - if got := funcName(seq.phases[2]); got != "bootAdvisory" { + // step() and notingPhase() wrap every phase in a closure, so names are + // not recoverable through the func values; the veto-capable bootAdvisory + // is pinned through the phase table and defaultBootSequenceNames pins + // the order. + if got := funcName(defaultBootPhases()[2].run); got != "bootAdvisory" { t.Fatalf("phases[2] = %s, want bootAdvisory (the veto-capable phase)", got) } if got := defaultBootSequenceNames(); strings.Join(got, ",") != strings.Join(want, ",") { @@ -90,3 +95,21 @@ func TestRunBootPhaseVetoSkipsLaterPhasesAndLoop(t *testing.T) { t.Fatalf("trace = %s", got) } } + +// #15788: each phase reports its name to the dashboard as it starts so a +// browser reconnecting onto a fresh pod can say what it is waiting on; a +// phase before bootDashboard has nowhere to report and must not panic. +func TestNotingPhaseReportsStartupPhaseToDashboard(t *testing.T) { + b := &boot{} + ran := false + phase := notingPhase(namedPhase{name: "bootGitHub", run: func(*boot) bool { ran = true; return false }}) + if phase(b) || !ran { + t.Fatal("wrapper must run the phase and return its verdict") + } + + b.dashSrv = dashboard.NewServer(0, slog.New(slog.NewTextHandler(io.Discard, nil))) + notingPhase(namedPhase{name: "bootStores", run: func(*boot) bool { return true }})(b) + if got := b.dashSrv.StartupPhase(); got != "bootStores" { + t.Fatalf("StartupPhase = %q, want bootStores", got) + } +} diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index f51a1ffaca..7e216b4b53 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -2428,6 +2428,18 @@ func (b *boot) bootDashboardWith(deps bootDashboardDeps) { b.preShutdownHooks.addUrgent("drain-contributor-websockets", func() { b.dashSrv.DrainContributorsForShutdown() }) + // Tell the dashboard the pod is going down BEFORE the stream drops + // (#15788): an SSE "upgrading" event with phase=restarting and the + // target the hub armed (when known), so the operator sees the upgrade + // animation instead of a bare "reconnecting". Registered after the + // contributor drain with addUrgent so it runs first — the frame is one + // write on sockets that are already open, and the drain is what takes + // the time. restartAnnounceSettle gives the SSE handler goroutines a + // moment to flush before the hooks that follow race the grace period. + b.preShutdownHooks.addUrgent("announce-restart", func() { + b.dashSrv.AnnounceRestart(time.Now()) + <-time.After(restartAnnounceSettle) + }) // Stop the contributor hub's background cleanup loop on the way out // (#6272). On v4 this is a `defer dashSrv.CloseContributeHub()` in main(); // v5 has no such single-function scope, so it rides the same shutdown-hook @@ -5317,6 +5329,11 @@ func (b *boot) bootHeartbeatWith(deps bootHeartbeatDeps) { // the hub will actually roll us to and renders the hub's schedule. b.dashSrv.SetHubUpgradePolicy(p) }), + spoke.UpgradeAnnounceCallback(func(a *spoke.UpgradeAnnounce) { + // The hub is about to roll (or has rolled) this pod itself + // (#15788): show the upgrade animation before the kill. + b.dashSrv.AnnounceUpgrade(*a, time.Now()) + }), spoke.VisibilityCallback(func(isPublic bool) { if b.cfg.Hub.IsPublic != isPublic { b.logger.Info("hub overrode visibility via heartbeat", @@ -5766,6 +5783,7 @@ func (b *boot) runLoop() { b.runLoopWith(defaultRunLoopDeps()) } // runLoopWith is runLoop with its timers and per-tick IO injected; see // runLoopDeps. func (b *boot) runLoopWith(deps runLoopDeps) { + b.noteBootPhase(bootPhaseFirstEval) initialEvalInterval, initialMode := evalIntervalAndModeForConfig(b.cfg, b.ghClient, b.logger) b.logger.Info("entering governor loop", "interval_seconds", int(initialEvalInterval.Seconds()), "eval_mode", initialMode) lastEvalInterval := initialEvalInterval diff --git a/src/cmd/hive/self_upgrade_drain.go b/src/cmd/hive/self_upgrade_drain.go index 32abce31ca..f9fabc2794 100644 --- a/src/cmd/hive/self_upgrade_drain.go +++ b/src/cmd/hive/self_upgrade_drain.go @@ -17,6 +17,11 @@ import ( // upgrade was cancelled or superseded — and kicks must not stay withheld. const selfUpgradeDrainStaleAfter = 3 * heartbeatSendInterval +// restartAnnounceSettle is how long the SIGTERM hook lets the SSE handler +// goroutines flush the "upgrading" frame before the next hook runs +// (#15788). One write on already-open sockets; well inside the grace period. +const restartAnnounceSettle = 100 * time.Millisecond + // selfUpgradeDrainNow is the drain clock, a seam for tests. var selfUpgradeDrainNow = time.Now diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index b6e22a9b38..c31c3f8d46 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -6,43 +6,43 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:135` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:139` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:140` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:141` | -| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:142` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:143` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:144` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:145` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:146` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:147` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:148` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:149` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:150` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:154` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:171` | -| `GET` | `/api/governor/pr-models` | Dashboard auth/session | Agent-authored PR distribution by normalized attribution model/backend for `window=7d`, `30d`, or `all`, including per-model rework stats and the top 10 most-reworked PRs | `pkg/dashboard/api.go:172` | -| `GET` | `/api/reviewer/accuracy` | Dashboard auth/session | Reviewer verdict calibration for the configured window: false-approve/false-block rates and confidence buckets per perspective and reviewer model | `pkg/dashboard/api.go:233` | -| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:500` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:503` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:504` | -| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:508` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:136` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:140` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:141` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:142` | +| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:143` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:144` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:145` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:146` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:147` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:148` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:149` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:150` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:151` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:155` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:172` | +| `GET` | `/api/governor/pr-models` | Dashboard auth/session | Agent-authored PR distribution by normalized attribution model/backend for `window=7d`, `30d`, or `all`, including per-model rework stats and the top 10 most-reworked PRs | `pkg/dashboard/api.go:173` | +| `GET` | `/api/reviewer/accuracy` | Dashboard auth/session | Reviewer verdict calibration for the configured window: false-approve/false-block rates and confidence buckets per perspective and reviewer model | `pkg/dashboard/api.go:234` | +| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:501` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:504` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:505` | +| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:509` | | `GET` | `/api/review/dispatch/events` | Dashboard auth/session | Webhook review dispatch queue: `enabled`, `webhooks_configured`, `debounce_s`, `pending` (soonest first) and `recent` (newest first) dispatches with repo, number, head SHA, action, timestamps and coalesced count, plus `stats` counters; in memory, never calls GitHub | `pkg/dashboard/api_review_event_dispatch.go:16` | -| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:512` | -| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:513` | -| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:515` | -| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:518` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:312` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:313` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:314` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:315` | - -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:122` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:126` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:129` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:130` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:131` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:153` | +| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:513` | +| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:514` | +| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:516` | +| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:519` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:313` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:314` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:315` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:316` | + +| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:123` | +| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:127` | +| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:130` | +| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:131` | +| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:132` | +| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:154` | ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 153b03c268..ae1ec65d17 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -5,13 +5,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:176` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:177` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:178` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:179` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:180` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:181` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:182` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:177` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:178` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:179` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:180` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:181` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:182` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:183` | | `GET` | `/api/claude-auth/status` | Dashboard auth/session | Claude Auth Status | `pkg/dashboard/claude_auth.go:54` | | `POST` | `/api/claude-auth/start` | Dashboard auth/session | Claude Auth Start | `pkg/dashboard/claude_auth.go:55` | | `POST` | `/api/claude-auth/exchange` | Dashboard auth/session | Claude Auth Exchange | `pkg/dashboard/claude_auth.go:56` | @@ -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:1642` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1643` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1644` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1649` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1650` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1651` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index b2f87ad343..a99adea4c9 100644 --- a/src/docs/api-reference/beads.md +++ b/src/docs/api-reference/beads.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:484` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:485` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:486` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:487` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:488` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:485` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:486` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:487` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:488` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:489` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 25a15d4072..8d938b0c39 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -11,8 +11,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:56` | | `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:57` | | `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:50` | -| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:254` | -| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:255` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:255` | +| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:256` | | `GET` | `/api/config/export` | Owner only | Redacted JSON export of the effective config, layer files, side files, and provenance | `pkg/dashboard/api_config_export.go` | | `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:53` | | `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:54` | @@ -20,96 +20,96 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:58` | | `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:59` | -| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:190` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:191` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:192` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:193` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:194` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:195` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:196` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:197` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:198` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:199` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:200` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:201` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:202` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:203` | +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:191` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:192` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:193` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:194` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:195` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:196` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:197` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:198` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:199` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:200` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:201` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:202` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:203` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:204` | | `GET` | `/api/config/agent/{name}/variables` | Dashboard auth/session | Per-agent Variables tab: the agent's own `${VAR}` definitions plus the hive-level ones it inherits (each flagged `overridden` when the agent redefines it) and the seed-only exec/http gate flags. Never returns values — only name, type, scope and a non-secret source hint | `pkg/dashboard/api_variables.go:298` | | `PUT` | `/api/config/agent/{name}/variables/{var}` | Owner only | Create or update one per-agent variable (`static`/`env` only; `script`/`http` are 403 and seed-only; scope `template` or `both`; secret-looking static values rejected). Persisted on the agent entry; overrides a same-named hive-level variable in this agent's kick prompt | `pkg/dashboard/api_variables.go:299` | | `DELETE` | `/api/config/agent/{name}/variables/{var}` | Owner only | Delete one per-agent variable (404 for inherited hive-level variables — delete those via `/api/config/variables/{name}`) | `pkg/dashboard/api_variables.go:300` | -| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:204` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:206` | -| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:209` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:210` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:217` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:218` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:222` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:223` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:235` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:236` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:237` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:238` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:239` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:205` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:207` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:211` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:218` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:219` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:223` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:224` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:236` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:237` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:238` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:239` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:240` | | `GET` | `/api/config/governor/backup` | Owner only | Backup Key Status (presence + safe source label; never the key value) | `pkg/dashboard/backup_key.go` | | `PUT` | `/api/config/governor/backup` | Owner only | Backup Key Set (64-hex AES-256 key; stored 0600, path-only in `hive.yaml`) | `pkg/dashboard/backup_key.go` | | `DELETE` | `/api/config/governor/backup` | Owner only | Backup Key Clear (backups are refused again) | `pkg/dashboard/backup_key.go` | -| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:283` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:284` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:285` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:284` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:285` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:286` | -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:211` | -| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:212` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:287` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:288` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:291` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:292` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:293` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:294` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:295` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:300` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:301` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:302` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:306` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:307` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:310` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:359` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:360` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:361` | -| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:351` | -| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:352` | -| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:353` | -| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:354` | -| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:355` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:356` | -| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:357` | -| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:525` | +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:212` | +| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:213` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:288` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:289` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:292` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:293` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:294` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:295` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:296` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:301` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:302` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:303` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:307` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:308` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:311` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:360` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:361` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:362` | +| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:352` | +| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:353` | +| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:354` | +| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:355` | +| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:356` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:357` | +| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:358` | +| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:526` | -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:214` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:216` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:219` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:224` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:227` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:228` | -| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:521` | -| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:522` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:231` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:234` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:240` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:241` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:242` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:246` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:247` | -| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:252` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:253` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:257` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:258` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:259` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:260` | -| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:270` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:271` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:272` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:273` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:274` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:289` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:290` | +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:215` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:216` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:217` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:220` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:225` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:228` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:229` | +| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:522` | +| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:523` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:232` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:235` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:241` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:242` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:243` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:247` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:248` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:253` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:254` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:258` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:259` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:260` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:261` | +| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:271` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:272` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:273` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:274` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:275` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:290` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:291` | diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index 67b5d4a9ea..126127728c 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -5,16 +5,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:83` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:157` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:158` | -| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485) | `pkg/dashboard/api.go:159` | +| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:84` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:158` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:159` | +| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485) | `pkg/dashboard/api.go:160` | | `GET` | `/api/repo-activity` | Dashboard auth/session | Per-repo audited activity | `pkg/dashboard/api.go` | | `GET` | `/api/repo-cost` | Dashboard auth/session | Per-repo estimated token cost (interval join, cached) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost` | Dashboard auth/session | Per-issue / PR / head-SHA estimated token cost from kick launch attribution (cached; `?ref=owner/repo#N` narrows) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost/history` | Dashboard auth/session | Daily per-ref rollup of launch attribution (`daily_rollup[]`: `day`, `by_ref[]` with `ref`, `kind`, `launches`, `share_usd`), kept ~2 years on the `/data` PVC so cost per PR can be measured past the `/api/launch-cost` window | `pkg/dashboard/api.go` | -| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:165` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:168` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:170` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:166` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:169` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:171` | | `GET` | `/api/providers/headroom` | Dashboard auth/session | Providers Headroom | `pkg/dashboard/api.go:61` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:167` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:168` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index ffb9f714eb..57fd430b5e 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -6,46 +6,47 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:60` | -| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:495` | +| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:496` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:63` | +| `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:66` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:64` | | `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:65` | -| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:69` | -| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:70` | -| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:71` | -| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:82` | -| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:84` | -| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:85` | -| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:86` | +| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:70` | +| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:71` | +| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:72` | +| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:83` | +| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:85` | +| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:86` | +| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:87` | -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:256` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:447` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:450` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:451` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:453` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:454` | +| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:257` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:448` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:451` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:452` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:454` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:455` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:215` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:216` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:217` | -| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:298` | -| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:299` | +| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:299` | +| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:300` | -| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:532` | -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:114` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:119` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:133` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:155` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:173` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:174` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:186` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Merge queued · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:187` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:188` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:364` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:426` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:427` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:456` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:490` | +| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:533` | +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:115` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:120` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:134` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:156` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:174` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:175` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:187` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Merge queued · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:188` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:189` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:365` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:427` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:428` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:457` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:491` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:288` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:289` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:290` | @@ -63,4 +64,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:315` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:316` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:317` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1649` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1656` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 4cd2182b36..9492f45186 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -5,20 +5,20 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `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)) | `pkg/dashboard/api.go:44` | +| `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:44` | | `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:45` | -| `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:66` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1622` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1623` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1624` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1630` | -| `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; `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`) | `pkg/dashboard/server.go:1635` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1636` | -| `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:1637` | -| `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:1638` | -| `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:1639` | -| `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:1640` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1641` | +| `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:67` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1629` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1630` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1631` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1637` | +| `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; `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`) | `pkg/dashboard/server.go:1642` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1643` | +| `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:1644` | +| `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:1645` | +| `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:1646` | +| `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:1647` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1648` | | `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` | @@ -28,30 +28,30 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/swarm/themes` | Owner only | Set a per-repo swarm theme (`event_name`, `call_to_arms`, `leaderboard_title`). | `pkg/dashboard/swarm.go:316` | | `PATCH` | `/api/swarm/objectives` | Owner only | Update the active swarm SDLC objective checklist completion state. | `pkg/dashboard/swarm.go:317` | | `GET` | `/api/leaderboard/swarm` | Public | Stable public JSON record of swarm history, leaderboard, top players, and achievements. | `pkg/dashboard/swarm.go:318` | -| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:87` | -| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:88` | -| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:89` | -| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:91` | -| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:92` | -| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:93` | -| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:94` | -| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:95` | -| `GET` | `/api/campaigns/{id}` | Dashboard auth/session | Return one campaign by URL-escaped stable campaign id or run key, using the same campaign shape as `/api/campaigns`; recheck revisions may include a `drift` block with `codebase_changed`, `prior_revision`, `delta_count`, `recheck_reason`, `external[]` (`source`, `kind`, `title`, `url`, `published_at`, `summary`), `external_count`, and `sources_failed`. | `pkg/dashboard/api.go:96` | -| `POST` | `/api/campaigns/{id}/resume` | Owner only | Resume or pick up a campaign. Archived Inception campaigns take a durable campaign lease, restore their saved state and wiki working files; Spek campaigns return the retained run detail plus a CLI status command that reloads state from Spek artifacts. Body may include `{ "surface": "chat"|"contributor"|"cli"|"dashboard" }`; 409 means another user holds the lease. | `pkg/dashboard/api.go:97` | -| `POST` | `/api/campaigns/{id}/release` | Owner only | Release the caller's Inception campaign lease and write a `campaign_release` audit entry so another user can continue it. Run-backed Spektacular campaigns return `409 Conflict`; this endpoint never revokes their run-lifecycle stage leases. | `pkg/dashboard/api.go:98` | -| `POST` | `/api/campaigns/{id}/revise` | Owner only | Create a linked revision campaign (`revision_of`, `revision`) for revisiting shipped or parked Inception/Spek work without overwriting the previous campaign. The new revision is leased to the caller and audit-logged as `campaign_revise`. | `pkg/dashboard/api.go:99` | -| `DELETE` | `/api/campaigns/{id}` | Owner only | Delete a campaign record: removes the archived Inception state and wiki snapshot for the stable campaign id and audit-logs `campaign_delete`. Knowledge-base facts, Jam threads, scaffolded repo files and other revisions in the same chain are kept; deleting the live L1 session clears it. Run-backed Spektacular campaigns return `409 Conflict`; unknown ids `404`. | `pkg/dashboard/api.go:100` | -| `POST` | `/api/campaigns/{id}/recheck` | Owner only | Create an immediate linked Spek recheck revision using the cadence path. Returns `409 Conflict` when a recheck revision is already in flight, `404 Not Found` when recheck is disabled unless `?force=true` is supplied, and records `campaign_recheck`. | `pkg/dashboard/api.go:101` | -| `GET` | `/api/campaigns/{id}/jam` | Dashboard auth/session | Return the per-campaign Jam workspace: section-anchored threads, comments, suggestions, polls, poll decisions, current spec revision and attributed revision history. | `pkg/dashboard/api.go:102` | -| `POST` | `/api/campaigns/{id}/jam` | Read-write role | Record an attributed spec revision for a campaign. Body includes `spec_content`, optional `reason`, and optional agent/model attribution fields. | `pkg/dashboard/api.go:103` | -| `GET` | `/api/campaigns/{id}/jam/threads` | Dashboard auth/session | List async Jam threads anchored to spec sections, including comments and author attribution. | `pkg/dashboard/api.go:104` | -| `POST` | `/api/campaigns/{id}/jam/threads` | Read-write role | Create a section-anchored Jam thread or add a comment to an existing thread. Body includes `section` and `body`, or `thread_id` and `body`. | `pkg/dashboard/api.go:105` | -| `POST` | `/api/campaigns/{id}/jam/agents` | Maintainer only | Invite Spektacular or a configured hive agent into a Jam thread. The agent reply is posted as an attributed thread comment and an open suggestion for human accept/reject; no spec revision is auto-applied. | `pkg/dashboard/api.go:106` | -| `GET` | `/api/campaigns/{id}/jam/suggestions` | Dashboard auth/session | List Jam suggestions with open/accepted/rejected status, proposed text, attribution and applied revision id when accepted. | `pkg/dashboard/api.go:107` | -| `POST` | `/api/campaigns/{id}/jam/suggestions` | Read-write role; maintainer for accept | Create a suggestion (`section`, `proposed_text`) or resolve it with `action: "accept"`/`"reject"` and `suggestion_id`. Accepting records a new attributed spec revision. | `pkg/dashboard/api.go:108` | -| `GET` | `/api/campaigns/{id}/jam/polls` | Dashboard auth/session | List Jam polls, advisory vote tallies and maintainer decisions stored against spec revisions. | `pkg/dashboard/api.go:109` | -| `POST` | `/api/campaigns/{id}/jam/polls` | Read-write role; maintainer for decide | Create polls (`section`, `question`, `options`), cast/update advisory votes (`action: "vote"`), or record a maintainer decision with rationale (`action: "decide"`). | `pkg/dashboard/api.go:110` | -| `GET` | `/api/campaigns/{id}/jam/project-sync` | Dashboard auth/session | Return the campaign's GitHub Projects sync configuration, last published items, last status, and retry guidance for failures. | `pkg/dashboard/api.go:111` | -| `POST` | `/api/campaigns/{id}/jam/project-sync` | Maintainer only | Enable/disable opt-in GitHub Projects sync, publish campaign specs/decisions/derived issues to the linked project, or record inbound project status updates without losing local Jam decisions. | `pkg/dashboard/api.go:112` | -| `GET` | `/api/campaigns/{id}/jam/ws` | Dashboard auth/session | Upgrade to a Jam WebSocket for live participant presence, section focus, and conflict-aware spec co-edit messages. Live edits require read-write role and stale `base_revision_id` values are rejected with a conflict message. | `pkg/dashboard/api.go:113` | -| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:90` | +| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:88` | +| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:89` | +| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:90` | +| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:92` | +| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:93` | +| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:94` | +| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:95` | +| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:96` | +| `GET` | `/api/campaigns/{id}` | Dashboard auth/session | Return one campaign by URL-escaped stable campaign id or run key, using the same campaign shape as `/api/campaigns`; recheck revisions may include a `drift` block with `codebase_changed`, `prior_revision`, `delta_count`, `recheck_reason`, `external[]` (`source`, `kind`, `title`, `url`, `published_at`, `summary`), `external_count`, and `sources_failed`. | `pkg/dashboard/api.go:97` | +| `POST` | `/api/campaigns/{id}/resume` | Owner only | Resume or pick up a campaign. Archived Inception campaigns take a durable campaign lease, restore their saved state and wiki working files; Spek campaigns return the retained run detail plus a CLI status command that reloads state from Spek artifacts. Body may include `{ "surface": "chat"|"contributor"|"cli"|"dashboard" }`; 409 means another user holds the lease. | `pkg/dashboard/api.go:98` | +| `POST` | `/api/campaigns/{id}/release` | Owner only | Release the caller's Inception campaign lease and write a `campaign_release` audit entry so another user can continue it. Run-backed Spektacular campaigns return `409 Conflict`; this endpoint never revokes their run-lifecycle stage leases. | `pkg/dashboard/api.go:99` | +| `POST` | `/api/campaigns/{id}/revise` | Owner only | Create a linked revision campaign (`revision_of`, `revision`) for revisiting shipped or parked Inception/Spek work without overwriting the previous campaign. The new revision is leased to the caller and audit-logged as `campaign_revise`. | `pkg/dashboard/api.go:100` | +| `DELETE` | `/api/campaigns/{id}` | Owner only | Delete a campaign record: removes the archived Inception state and wiki snapshot for the stable campaign id and audit-logs `campaign_delete`. Knowledge-base facts, Jam threads, scaffolded repo files and other revisions in the same chain are kept; deleting the live L1 session clears it. Run-backed Spektacular campaigns return `409 Conflict`; unknown ids `404`. | `pkg/dashboard/api.go:101` | +| `POST` | `/api/campaigns/{id}/recheck` | Owner only | Create an immediate linked Spek recheck revision using the cadence path. Returns `409 Conflict` when a recheck revision is already in flight, `404 Not Found` when recheck is disabled unless `?force=true` is supplied, and records `campaign_recheck`. | `pkg/dashboard/api.go:102` | +| `GET` | `/api/campaigns/{id}/jam` | Dashboard auth/session | Return the per-campaign Jam workspace: section-anchored threads, comments, suggestions, polls, poll decisions, current spec revision and attributed revision history. | `pkg/dashboard/api.go:103` | +| `POST` | `/api/campaigns/{id}/jam` | Read-write role | Record an attributed spec revision for a campaign. Body includes `spec_content`, optional `reason`, and optional agent/model attribution fields. | `pkg/dashboard/api.go:104` | +| `GET` | `/api/campaigns/{id}/jam/threads` | Dashboard auth/session | List async Jam threads anchored to spec sections, including comments and author attribution. | `pkg/dashboard/api.go:105` | +| `POST` | `/api/campaigns/{id}/jam/threads` | Read-write role | Create a section-anchored Jam thread or add a comment to an existing thread. Body includes `section` and `body`, or `thread_id` and `body`. | `pkg/dashboard/api.go:106` | +| `POST` | `/api/campaigns/{id}/jam/agents` | Maintainer only | Invite Spektacular or a configured hive agent into a Jam thread. The agent reply is posted as an attributed thread comment and an open suggestion for human accept/reject; no spec revision is auto-applied. | `pkg/dashboard/api.go:107` | +| `GET` | `/api/campaigns/{id}/jam/suggestions` | Dashboard auth/session | List Jam suggestions with open/accepted/rejected status, proposed text, attribution and applied revision id when accepted. | `pkg/dashboard/api.go:108` | +| `POST` | `/api/campaigns/{id}/jam/suggestions` | Read-write role; maintainer for accept | Create a suggestion (`section`, `proposed_text`) or resolve it with `action: "accept"`/`"reject"` and `suggestion_id`. Accepting records a new attributed spec revision. | `pkg/dashboard/api.go:109` | +| `GET` | `/api/campaigns/{id}/jam/polls` | Dashboard auth/session | List Jam polls, advisory vote tallies and maintainer decisions stored against spec revisions. | `pkg/dashboard/api.go:110` | +| `POST` | `/api/campaigns/{id}/jam/polls` | Read-write role; maintainer for decide | Create polls (`section`, `question`, `options`), cast/update advisory votes (`action: "vote"`), or record a maintainer decision with rationale (`action: "decide"`). | `pkg/dashboard/api.go:111` | +| `GET` | `/api/campaigns/{id}/jam/project-sync` | Dashboard auth/session | Return the campaign's GitHub Projects sync configuration, last published items, last status, and retry guidance for failures. | `pkg/dashboard/api.go:112` | +| `POST` | `/api/campaigns/{id}/jam/project-sync` | Maintainer only | Enable/disable opt-in GitHub Projects sync, publish campaign specs/decisions/derived issues to the linked project, or record inbound project status updates without losing local Jam decisions. | `pkg/dashboard/api.go:113` | +| `GET` | `/api/campaigns/{id}/jam/ws` | Dashboard auth/session | Upgrade to a Jam WebSocket for live participant presence, section focus, and conflict-aware spec co-edit messages. Live edits require read-write role and stale `base_revision_id` values are rejected with a conflict message. | `pkg/dashboard/api.go:114` | +| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:91` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 92198c6b14..fd323af0aa 100644 --- a/src/docs/api-reference/inception.md +++ b/src/docs/api-reference/inception.md @@ -5,17 +5,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:429` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:430` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:431` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:432` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:433` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:434` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:435` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:436` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:437` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:438` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:439` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:440` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:441` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:442` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:430` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:431` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:432` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:433` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:434` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:435` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:436` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:437` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:438` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:439` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:440` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:441` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:442` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:443` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index e65781ed83..1bfbdc0fb2 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -5,37 +5,37 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:366` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:367` | -| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; 404 otherwise | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](../public-knowledge-mcp.md)) | `pkg/dashboard/api.go:375` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:368` | -| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:369` | -| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](../knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:370` | -| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:371` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:376` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:377` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:378` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:379` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:380` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:381` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:382` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:383` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:389` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:390` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:391` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:392` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:393` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:394` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:395` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:396` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:397` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:398` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:399` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:400` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:401` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:402` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:403` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:404` | +| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:367` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:368` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; 404 otherwise | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](../public-knowledge-mcp.md)) | `pkg/dashboard/api.go:376` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:369` | +| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:370` | +| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](../knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:371` | +| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:372` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:377` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:378` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:379` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:380` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:381` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:382` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:383` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:384` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:390` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:391` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:392` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:393` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:394` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:395` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:396` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:397` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:398` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:399` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:400` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:401` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:402` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:403` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:404` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:405` | | `GET` | `/api/config/knowledge/connectors` | Dashboard auth/session | Knowledge connectors config (name, type, layer, scope, env/file auth reference) and registered types | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/connectors` | Owner only | Replace `knowledge.connectors` after validation; inline secrets rejected | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/connectors/status` | Dashboard auth/session | Per-connector status pill, last sync, pages/facts, last error, plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -45,19 +45,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/knowledge/agent-scopes` | Owner only | Replace `knowledge.agent_scopes` after validating layer and state names; persisted and audited as `config_knowledge_agent_scopes` | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/pipeline` | Owner only | Scalar bead synthesizer, curator, code map and primer settings, plus the read-only engine, vault paths and primer merge strategy ([docs](../settings.md#knowledge)) | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/pipeline` | Owner only | Update those settings after `config.ValidateKnowledgePipeline`; 0 or empty restores the default; the bead synthesizer switch applies at once, the rest after a restart; audited as `config_knowledge_pipeline` | `pkg/dashboard/api.go` | -| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:414` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:415` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:416` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:417` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:418` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:419` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:420` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:421` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:422` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:423` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:424` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:387` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:388` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:415` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:416` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:417` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:418` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:420` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:421` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:422` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:423` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:424` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:388` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:389` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](../knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:23` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/publish/sync` | Owner only | Run a publish mirror batch now (202 with publish status; 503 mirror not running, 409 batch in progress) | `pkg/dashboard/api_knowledge_connectors.go:25` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index aa50f2970f..6bc6ea82e3 100644 --- a/src/docs/api-reference/nous.md +++ b/src/docs/api-reference/nous.md @@ -5,28 +5,28 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:458` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:459` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:460` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:461` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:462` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:463` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:464` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:465` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:466` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:467` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:468` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:469` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:470` | -| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:471` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:472` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:473` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:474` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:475` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:476` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:477` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:478` | -| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:479` | -| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:480` | -| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:481` | -| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:482` | +| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:459` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:460` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:461` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:462` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:463` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:464` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:465` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:466` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:467` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:468` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:469` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:470` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:471` | +| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:472` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:473` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:474` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:475` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:477` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:478` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:479` | +| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:480` | +| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:481` | +| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:482` | +| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:483` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 0cd5946296..ee8d28634a 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -5,25 +5,25 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:317` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:318` | -| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:319` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:318` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:319` | +| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:320` | | `POST` | `/api/repos/rescan` | Dashboard auth/session | Re-enumerate watched repositories' open issues/PRs for the dashboard Projects cards. The scan is read-only with respect to agents/governor actions, collapses concurrent requests, and debounces repeated presses for 30 seconds (`repoRescanDebounce`) so the button cannot hammer GitHub | `pkg/dashboard/api.go`, `pkg/dashboard/api_repos_rescan.go` | | `POST` | `/api/repos/pause` | Owner | Quiet ONE repository without stopping the hive: agents stop writing to it and stop being handed work on it, while it keeps its dashboard card and ACMM eval. Body `{"repo": "...", "reason": "..."}` — the repo travels in the body because a `project.repos` entry may be an explicit cross-org `owner/name`. Records who/when/why; `changed: false` marks a no-op re-pause and leaves the original provenance intact; `persisted: false` means the pause is in force but could not be written to config. Rejects a repo outside `project.repos`. See [per-repo agent pause](../repo-pause.md) | `pkg/dashboard/api_repo_pause.go` | | `POST` | `/api/repos/resume` | Owner | Lift a repository's pause. Unlike pause, does not require the repo to be in `project.repos`, so a pause left behind by a removed repo can still be cleared | `pkg/dashboard/api_repo_pause.go` | | `GET` | `/api/repos/pauses` | Dashboard auth/session | Every repo pause with its provenance. Read-only — the same state is already on the repository cards | `pkg/dashboard/api_repo_pause.go` | -| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:334`, `pkg/dashboard/api_repo_hold.go` | +| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:335`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:339`, `pkg/dashboard/api_repo_item_decision.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:339`, `pkg/dashboard/api_repo_hold.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:340`, `pkg/dashboard/api_repo_item_decision.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:342`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:343` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:344` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:539`, `pkg/dashboard/api_repo_item_accept_triage.go` | -| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:346`, `pkg/dashboard/api_acmm_eval.go` | -| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:347` | -| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:348` | -| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:350`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:344` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:345` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:540`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:347`, `pkg/dashboard/api_acmm_eval.go` | +| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:348` | +| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:349` | +| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:351`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 2f8063c389..7d6fc9459d 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:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1702` | -| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:79` | -| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:80` | -| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:81` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1709` | +| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:80` | +| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:81` | +| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:82` | diff --git a/src/docs/dashboard-standalone-upgrades.md b/src/docs/dashboard-standalone-upgrades.md index 250665cbd1..c52c17e0de 100644 --- a/src/docs/dashboard-standalone-upgrades.md +++ b/src/docs/dashboard-standalone-upgrades.md @@ -278,6 +278,41 @@ see [podman-auto-update.md](podman-auto-update.md) and gap 3 of [#10344](https://github.com/hivecommons/hive/issues/10344) for why a plain `pin` would silently disable tracking. +## Seeing the upgrade animation for every roll + +The dashboard's version chip and navbar indicator animate a self-upgrade +(bees over the hive, `draining → pulling → rolling → done`). Since +[#15788](https://github.com/hivecommons/hive/issues/15788) the same +component also covers rolls the spoke did not start itself: + +- **Hub-managed rolls** — the hub attaches `upgrade_announce` to the + heartbeat response while its upgrade latch is open onto a build the spoke + is not running, so the chip shows `Upgrading hive… → ` before the + hub's `kubectl rollout restart` kills the pod. +- **Operator rolls** — announce first, then roll, so the dashboard shows the + intent rather than a bare "reconnecting": + + ```sh + curl -sS -X POST "https:///api/upgrade/announce" \ + -H "Authorization: Bearer $HIVE_TOKEN" -H 'Content-Type: application/json' \ + -d '{"target":"","source":"operator","reason":"rollout restart"}' \ + && kubectl -n rollout restart deploy/hive + ``` + + The endpoint is owner-only; `target` may be omitted for a plain restart. +- **Anything else (SIGTERM, OOM-kill-then-restart, `kubectl delete pod`)** — + the old pod publishes an SSE `upgrading` event with `phase: restarting` as + its first shutdown hook, before the stream drops. The banner persists in + the browser across the reconnect, shows the new pod's boot phase + (`starting: opening stores…`) from `/api/version.startupPhase`, and on + reconnect compares build hash and process `startedAt`: **Upgraded to + `` ✓** when the build changed, **Restarted ✓** when only the process + did. Both end with the standard 15-second toast countdown. + +To see the animation without rolling anything, open the dashboard with +`?demo=upgrade` or press **Settings → Diagnostics → Preview upgrade +animation**. + ## Operational notes - Owner authorization is still required on `/api/self-upgrade`. diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 0c2a9f04a5..fe5f97a802 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -63,6 +63,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("POST /api/presence", s.handlePresence) s.mux.HandleFunc("GET /api/prompt-history", s.handlePromptHistory) s.mux.HandleFunc("POST /api/self-upgrade", s.handleSelfUpgrade) + s.mux.HandleFunc("POST /api/upgrade/announce", s.handleUpgradeAnnounce) s.mux.HandleFunc("POST /api/release-channel", s.handleReleaseChannelSwitch) // Self-service, owner-only spoke backup (encrypted; includes the bead // ledger the fleet-wide hub backup excludes — see issue #2318). diff --git a/src/pkg/dashboard/api_version.go b/src/pkg/dashboard/api_version.go index 881d5d667d..179b257673 100644 --- a/src/pkg/dashboard/api_version.go +++ b/src/pkg/dashboard/api_version.go @@ -94,6 +94,17 @@ func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) { if progress := s.upgradeProgress(curStatus, time.Now()); progress != nil { resp["upgradeProgress"] = progress } + // Process identity for the roll banner (#15788): startedAt changes on + // every restart even when the build does not, so the dashboard can say + // "Restarted" rather than "Upgraded"; startupPhase says what a fresh pod + // is still booting while its first status is pending. + if !s.startedAt.IsZero() { + resp["startedAt"] = s.startedAt.UTC().Format(time.RFC3339) + } + if phase := s.StartupPhase(); phase != "" { + resp["startupPhase"] = phase + resp["startupPhaseLabel"] = StartupPhaseLabel(phase) + } if policy != nil && len(policy.UpgradeHistory) > 0 { var upgradedAt time.Time if upgradeOutcomeRec != nil { diff --git a/src/pkg/dashboard/roll_upgrade_harness_test.go b/src/pkg/dashboard/roll_upgrade_harness_test.go new file mode 100644 index 0000000000..01b5a79fb5 --- /dev/null +++ b/src/pkg/dashboard/roll_upgrade_harness_test.go @@ -0,0 +1,25 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// jsRollUpgradeFuncs returns the roll-upgrade helpers (#15788) the shared +// version renderers now call, plus their pacing constants, for node harnesses +// that assemble the renderer function by function. +func jsRollUpgradeFuncs(t *testing.T, html string) string { + t.Helper() + var b strings.Builder + b.WriteString("const VERSION_ROLL_POLL_MS = 2000;\nconst VERSION_ROLL_TOAST_MS = 15000;\n") + for _, name := range []string{ + "versionRollPhaseActive", "versionRollRecordFromEvent", "versionSameRollTarget", "versionAdoptServerRollProgress", + "versionRollComplete", "versionRollOutcome", "versionRollReconcile", "versionRollNotify", "versionRollWho", + "versionRollTitle", "versionRollStartupLabel", "versionRollStatusText", "versionRollStatusHTML", + "versionRollNavbarStatus", "versionRollReloadDeferred", "versionUpgradeTitle", + } { + b.WriteString(jsFunc(t, html, name)) + b.WriteByte('\n') + } + return b.String() +} diff --git a/src/pkg/dashboard/roll_upgrade_state.test.js b/src/pkg/dashboard/roll_upgrade_state.test.js new file mode 100644 index 0000000000..31160fed99 --- /dev/null +++ b/src/pkg/dashboard/roll_upgrade_state.test.js @@ -0,0 +1,185 @@ +// #15788: a pod roll (hub kubectl, operator `rollout restart`, bare SIGTERM) +// must drive the same upgrade banner the self-upgrade uses: SSE "upgrading" +// event → record → survives the reconnect → "Upgraded ✓" when the build hash +// changed, "Restarted ✓" when only the process did. +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); + +function slice(from, to) { + const start = html.indexOf(from); + assert.ok(start >= 0, 'missing ' + from); + const end = html.indexOf(to, start); + assert.ok(end > start, 'missing ' + to); + return html.slice(start, end); +} + +const stateSrc = slice('function versionNowMs()', 'function versionDeliveryLabel('); +const helpersSrc = slice('function versionShortSHA(sha)', 'function versionDashHTML('); +const renderSrc = slice('function versionUpgradeProgressStatus(v, st)', 'function versionSetHTMLPreservingUpgradeBee('); + +function build() { + const store = new Map(); + const toasts = []; + const prelude = ` + const VERSION_UPGRADE_STORAGE_KEY = 'hive.version.upgradeProgress'; + const VERSION_UPGRADE_HUB_SEEN_KEY = 'hive.version.upgradeHubAttempt'; + const VERSION_UPGRADE_DONE_MS = 30000; + const VERSION_UPGRADE_LONG_MS = 15 * 60 * 1000; + const VERSION_UPGRADE_POLL_MS = 5000; + const VERSION_ROLL_POLL_MS = 2000; + const VERSION_ROLL_TOAST_MS = 15000; + var _upgradeInProgress = false, _upgradeTargetHash = null, _versionUpgradePollTimer = null; + function escapeHtml(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } + function versionPolicy(v) { return v && v.upgradePolicy || null; } + function fetchGitVersion() {} + function setTimeout() { return 1; } + function clearTimeout() {} + function showToast(msg, type, persistent, ms) { toasts.push({ msg, type, ms }); } + `; + const h = new Function('localStorage', 'toasts', prelude + helpersSrc + stateSrc + renderSrc + ` + return { + read: versionReadUpgradeProgress, clear: versionClearUpgradeProgress, + fromEvent: versionRollRecordFromEvent, reconcile: versionReconcileUpgradeProgress, + adoptServer: versionAdoptServerRollProgress, outcome: versionRollOutcome, + title: versionRollTitle, status: versionRollStatusText, navbar: versionRollNavbarStatus, + navbarHTML: versionNavbarUpgradeHTML, beeHTML: versionBeeProgressHTML, + reloadDeferred: versionRollReloadDeferred, demoRequested: versionDemoRequested, + pollDelayIsFast: function(st) { versionScheduleUpgradePoll(st); return true; }, + inProgress: function() { return _upgradeInProgress; } + };`)({ + getItem: (k) => (store.has(k) ? store.get(k) : null), + setItem: (k, v) => store.set(k, String(v)), + removeItem: (k) => store.delete(k), + }, toasts); + h.toasts = toasts; + h.store = store; + return h; +} + +const OLD = { hash: 'aaaaaaa1111111111111111111111111111111111', short: 'aaaaaaa', startedAt: '2026-10-20T10:00:00Z' }; +const NEW_BUILD = { hash: 'bbbbbbb2222222222222222222222222222222222', short: 'bbbbbbb', startedAt: '2026-10-20T10:05:00Z' }; +const SAME_BUILD_NEW_PROCESS = { hash: OLD.hash, short: OLD.short, startedAt: '2026-10-20T10:05:00Z' }; +const T0 = Date.parse('2026-10-20T10:04:00Z'); + +test('announce event opens a roll record rendered as an in-flight upgrade', () => { + const h = build(); + const st = h.fromEvent({ phase: 'announced', source: 'hub', target: NEW_BUILD.hash, reason: 'hub-managed upgrade', startedAt: '2026-10-20T10:03:50Z' }, OLD, T0); + assert.strictEqual(st.source, 'roll'); + assert.strictEqual(st.phase, 'announced'); + assert.strictEqual(st.targetShort, 'bbbbbbb'); + assert.strictEqual(st.startedFrom, OLD.hash); + assert.strictEqual(st.fromStartedAt, OLD.startedAt); + assert.strictEqual(st.startedAt, Date.parse('2026-10-20T10:03:50Z')); + assert.ok(h.inProgress()); + assert.strictEqual(h.title(st), 'Upgrading hive…'); + assert.match(h.status(st, OLD, T0), /^roll announced by the hub → bbbbbbb — hub-managed upgrade · 10s elapsed$/); + assert.match(h.navbarHTML(st, OLD), /oc-version-hive/); + assert.match(h.navbarHTML(st, OLD), /Upgrading hive…/); + assert.match(h.beeHTML(st, OLD), /oc-version-upgrade-progress/); +}); + +test('SIGTERM with no prior announce still shows restarting, then Restarted on the same build', () => { + const h = build(); + const st = h.fromEvent({ phase: 'restarting', source: 'signal', target: '', processStartedAt: OLD.startedAt }, OLD, T0); + assert.strictEqual(st.target, ''); + assert.strictEqual(h.title(st), 'Restarting hive…'); + assert.strictEqual(h.status(st, {}, T0 + 3000), 'restarting · reconnecting · 3s elapsed'); + assert.strictEqual(h.navbar(st, {}), 'reconnecting'); + // The record survives a reload: read it back from storage. + assert.strictEqual(h.read(T0 + 5000).phase, 'restarting'); + // While the pod is down /api/version fails; nothing to reconcile, record stays. + assert.strictEqual(h.outcome(h.read(T0 + 5000), null), 'pending'); + // Old pod still answering (same process) → still pending. + assert.strictEqual(h.outcome(h.read(T0 + 5000), OLD), 'pending'); + // New pod, same build → Restarted. + const done = h.reconcile(SAME_BUILD_NEW_PROCESS, T0 + 20000); + assert.strictEqual(done.outcome, 'restarted'); + assert.ok(done.completedAt); + assert.strictEqual(h.title(done), 'Restarted ✓'); + assert.match(h.status(done, SAME_BUILD_NEW_PROCESS, T0 + 20000), /^↻ Restarted · still on aaaaaaa/); + assert.strictEqual(h.toasts.length, 1); + assert.match(h.toasts[0].msg, /Hive restarted/); + assert.strictEqual(h.toasts[0].ms, 15000); + assert.ok(!h.inProgress()); + // Reconciling again does not toast twice. + h.reconcile(SAME_BUILD_NEW_PROCESS, T0 + 21000); + assert.strictEqual(h.toasts.length, 1); +}); + +test('announce → restarting → reconnect onto a new build reads Upgraded to ', () => { + const h = build(); + h.fromEvent({ phase: 'announced', source: 'hub', target: NEW_BUILD.hash, startedAt: '2026-10-20T10:04:00Z' }, OLD, T0); + const restarting = h.fromEvent({ phase: 'restarting', source: 'hub', target: NEW_BUILD.hash, processStartedAt: OLD.startedAt, startedAt: '2026-10-20T10:04:00Z' }, OLD, T0 + 60000); + assert.strictEqual(restarting.startedAt, T0, 'the restart keeps the announce clock'); + assert.strictEqual(restarting.phase, 'restarting'); + // Fresh pod still booting: /api/version carries a startup phase. + const booting = Object.assign({}, NEW_BUILD, { startupPhase: 'bootStores', startupPhaseLabel: 'opening stores' }); + assert.strictEqual(h.navbar(restarting, booting), '→ bbbbbbb · starting: opening stores'); + const done = h.reconcile(NEW_BUILD, T0 + 90000); + assert.strictEqual(done.outcome, 'upgraded'); + assert.strictEqual(done.targetShort, 'bbbbbbb'); + assert.strictEqual(h.title(done), 'Upgraded ✓'); + assert.match(h.status(done, NEW_BUILD, T0 + 90000), /^✅ Upgraded to bbbbbbb/); + assert.deepStrictEqual(h.toasts.map((t) => t.msg), ['Upgraded to bbbbbbb ✓']); + // The silent hash-change reload waits for the toast countdown. + assert.strictEqual(h.reloadDeferred(done, T0 + 90000 + 1000), true); + assert.strictEqual(h.reloadDeferred(done, T0 + 90000 + 15000), false); + // The done record expires like a self-upgrade's. + assert.strictEqual(h.read(T0 + 90000 + 31000), null); +}); + +test('an announce the server no longer reports (aborted roll) is dropped; restarting is not', () => { + const h = build(); + h.fromEvent({ phase: 'announced', source: 'operator', target: NEW_BUILD.hash }, OLD, T0); + assert.strictEqual(h.reconcile(Object.assign({}, OLD, { upgradeProgress: { phase: 'announced', target: 'bbbbbbb' } }), T0 + 5000).phase, 'announced'); + assert.strictEqual(h.reconcile(OLD, T0 + 10000), null, 'server dropped the announce → record cleared'); + assert.strictEqual(h.read(T0 + 10000), null); + + h.fromEvent({ phase: 'restarting', source: 'signal', processStartedAt: OLD.startedAt }, OLD, T0); + assert.strictEqual(h.reconcile(OLD, T0 + 10000).phase, 'restarting', 'old pod still up: keep waiting for the kill'); +}); + +test('a tab opened after the announce adopts the server-side roll progress', () => { + const h = build(); + const v = Object.assign({}, OLD, { upgradeProgress: { phase: 'announced', state: 'pulling', source: 'hub', target: 'bbbbbbb', from: 'aaaaaaa', startedAt: '2026-10-20T10:03:00Z' } }); + const st = h.adoptServer(v, T0); + assert.strictEqual(st.source, 'roll'); + assert.strictEqual(st.rollSource, 'hub'); + assert.strictEqual(st.targetShort, 'bbbbbbb'); + assert.strictEqual(st.fromStartedAt, OLD.startedAt); + assert.strictEqual(h.adoptServer(OLD, T0), null); + // The server's phase advancing to restarting updates the record. + const adv = h.reconcile(Object.assign({}, OLD, { upgradeProgress: { phase: 'restarting', target: 'bbbbbbb' } }), T0 + 1000); + assert.strictEqual(adv.phase, 'restarting'); +}); + +test('a roll record never reports a bare "target" placeholder and the demo query is recognised', () => { + const h = build(); + assert.strictEqual(h.demoRequested('?demo=upgrade'), true); + assert.strictEqual(h.demoRequested('?x=1&demo=upgrade&y=2'), true); + assert.strictEqual(h.demoRequested('?demo=upgraded'), false); + assert.strictEqual(h.demoRequested(''), false); + const st = h.fromEvent({ phase: 'restarting', source: 'signal' }, {}, T0); + assert.doesNotMatch(h.status(st, {}, T0), /target/); + assert.strictEqual(h.fromEvent({ phase: 'done' }, OLD, T0), null); +}); + +test('the SIGTERM a self-upgrade causes does not replace the self-upgrade record', () => { + const h = build(); + h.store.set('hive.version.upgradeProgress', JSON.stringify({ target: NEW_BUILD.hash, targetShort: 'bbbbbbb', startedFrom: OLD.hash, startedAt: T0 - 5000, completedAt: 0 })); + const kept = h.fromEvent({ phase: 'restarting', source: 'signal', target: '' }, OLD, T0); + assert.strictEqual(kept.source, undefined); + assert.strictEqual(kept.targetShort, 'bbbbbbb'); + assert.strictEqual(h.read(T0).source, undefined, 'self-upgrade record untouched'); + // Whereas a roll record is superseded by the next roll event. + h.clear(); + h.fromEvent({ phase: 'announced', source: 'hub', target: NEW_BUILD.hash }, OLD, T0); + const killed = h.fromEvent({ phase: 'restarting', source: 'signal', target: '' }, OLD, T0 + 1); + assert.strictEqual(killed.phase, 'restarting'); + assert.strictEqual(killed.targetShort, 'bbbbbbb', 'a bare SIGTERM after an announce keeps the announced target'); + assert.strictEqual(killed.startedAt, T0); +}); diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 2b40cb4faf..99f286748d 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -427,6 +427,13 @@ type Server struct { // selfUpgradeDrain) so /api/status can show the countdown and the agents // holding it (#14856). Guarded by versionMu; nil when not installed. upgradeDrain upgradeDrainSource + // upgradeAnnounce is the announced/restarting roll record (#15788); + // see upgrade_announce.go. Zero value is usable. + upgradeAnnounce upgradeAnnounceStore + // startupPhase names the boot phase the process is in while s.status is + // still nil, so a dashboard reconnecting onto a fresh pod can show + // "starting: " instead of a bare spinner (#15788). + startupPhase atomic.Value // hubPushedDashboardURL is the vanity dashboard URL the hub last delivered // on a heartbeat (#7451). Non-empty means the hub owns hub.dashboard_url: // an operator edit would be reverted by the next push, and until then a @@ -3699,7 +3706,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { s.statusMu.RUnlock() if status == nil { - statusJSONResponse(w, r, map[string]string{"status": "initializing"}) + statusJSONResponse(w, r, s.initializingStatus()) return } now := time.Now().UTC() diff --git a/src/pkg/dashboard/sidebar_version_panel_test.go b/src/pkg/dashboard/sidebar_version_panel_test.go index 6ac0ccab43..be369c8452 100644 --- a/src/pkg/dashboard/sidebar_version_panel_test.go +++ b/src/pkg/dashboard/sidebar_version_panel_test.go @@ -74,6 +74,7 @@ const document = { getElementById(id) { return id === 'oc-version-chip' ? chip : jsFunc(t, html, "versionNowMs") + "\n" + jsFunc(t, html, "versionElapsedText") + "\n" + jsFunc(t, html, "versionUpgradeProgressStatus") + "\n" + + jsRollUpgradeFuncs(t, html) + jsFunc(t, html, "versionUpgradeKey") + "\n" + jsFunc(t, html, "versionBeeGlyphHTML") + "\n" + jsFunc(t, html, "versionUpgradeHiveHTML") + "\n" + @@ -180,6 +181,7 @@ var _upgradeInProgress = false; jsFunc(t, html, "versionNowMs") + "\n" + jsFunc(t, html, "versionElapsedText") + "\n" + jsFunc(t, html, "versionUpgradeProgressStatus") + "\n" + + jsRollUpgradeFuncs(t, html) + jsFunc(t, html, "versionUpgradeKey") + "\n" + jsFunc(t, html, "versionBeeGlyphHTML") + "\n" + jsFunc(t, html, "versionUpgradeHiveHTML") + "\n" + @@ -342,6 +344,7 @@ const localStorage = {data:{}, getItem(k){return this.data[k] || null}, setItem( jsFunc(t, html, "versionWriteUpgradeProgress") + "\n" + jsFunc(t, html, "versionClearUpgradeProgress") + "\n" + jsFunc(t, html, "versionMarkUpgradeComplete") + "\n" + + jsRollUpgradeFuncs(t, html) + jsFunc(t, html, "versionReconcileUpgradeProgress") + ` versionWriteUpgradeProgress({target:'bbb2222abcdef', targetShort:'bbb2222', startedAt:1000}); let st = versionReconcileUpgradeProgress({hash:'bbb2222abcdef'}, 2000); @@ -403,6 +406,7 @@ const localStorage = {data:{}, getItem(k){return this.data[k] || null}, setItem( jsFunc(t, html, "versionWriteUpgradeProgress") + "\n" + jsFunc(t, html, "versionClearUpgradeProgress") + "\n" + jsFunc(t, html, "versionMarkUpgradeComplete") + "\n" + + jsRollUpgradeFuncs(t, html) + jsFunc(t, html, "versionReconcileUpgradeProgress") + "\n" + jsFunc(t, html, "versionHubUpgradeAttemptKey") + "\n" + jsFunc(t, html, "versionAdoptHubUpgradeProgress") + ` diff --git a/src/pkg/dashboard/static-src/css/sections-collapse.css b/src/pkg/dashboard/static-src/css/sections-collapse.css index 9f679e5358..793af8e0d4 100644 --- a/src/pkg/dashboard/static-src/css/sections-collapse.css +++ b/src/pkg/dashboard/static-src/css/sections-collapse.css @@ -223,6 +223,12 @@ .gh-api-budget-fill.debug-quota-ok { fill: var(--green); } .gh-api-budget-fill.debug-quota-warn { fill: var(--yellow); } .gh-api-budget-fill.debug-quota-bad { fill: var(--red); } + /* Settings → Diagnostics "Hive process" tile (#15788): same tile look as the + inline-styled siblings, in tokens, so the style ratchet stays flat. */ + .debug-process-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r); padding: var(--sp-6); min-width: 0; } + .debug-process-label { font-size: var(--fs-2xs); text-transform: uppercase; letter-spacing: 0.5px; color: var(--muted); margin-bottom: var(--sp-4); font-weight: 600; } + .debug-process-note { color: var(--muted); font-size: var(--fs-sm); line-height: 1.45; } + .debug-process-actions { margin-top: var(--sp-3); } .gh-api-budget-table-wrap { overflow-x: auto; overscroll-behavior-x: contain; max-width: 100%; margin-top: var(--sp-4); } .gh-api-budget-table { width: 100%; min-width: 36rem; table-layout: fixed; border-collapse: collapse; font-size: var(--fs-xs); } .gh-api-budget-table th, .gh-api-budget-table td { text-align: left; padding: var(--sp-1) var(--sp-3) var(--sp-1) 0; white-space: normal; overflow-wrap: anywhere; } diff --git a/src/pkg/dashboard/static-src/js/acmm.js b/src/pkg/dashboard/static-src/js/acmm.js index 8c0dd48458..ed8ed07670 100644 --- a/src/pkg/dashboard/static-src/js/acmm.js +++ b/src/pkg/dashboard/static-src/js/acmm.js @@ -858,5 +858,12 @@ const VERSION_UPGRADE_DONE_MS = 30000; const VERSION_UPGRADE_LONG_MS = 15 * 60 * 1000; const VERSION_UPGRADE_POLL_MS = 5000; + // Pod rolls (#15788): poll faster while the pod is down, hold the + // "Upgraded ✓" outcome for the standard toast countdown, and pace the + // on-demand preview. + const VERSION_ROLL_POLL_MS = 2000; + const VERSION_ROLL_TOAST_MS = 15000; + const VERSION_ROLL_DEMO_STEP_MS = 4000; + const VERSION_ROLL_DEMO_START_MS = 1500; let _versionUpgradePollTimer = null; diff --git a/src/pkg/dashboard/static-src/js/debug-logs.js b/src/pkg/dashboard/static-src/js/debug-logs.js index ce304345e1..f65273438a 100644 --- a/src/pkg/dashboard/static-src/js/debug-logs.js +++ b/src/pkg/dashboard/static-src/js/debug-logs.js @@ -308,6 +308,11 @@
Cache Read${tokenCache}
${budgetLimit > 0 ? `
Budget
Used$${budgetUsed.toFixed(2)} / $${budgetLimit.toFixed(2)} (${budgetPct}%)
` : ''} +
+
Hive process
+
Pod rolls — by the hub, kubectl rollout restart or SIGTERM — animate the version chip while the pod restarts.
+
+
`); applySectionCollapse('debug-section'); } diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 5c98d043fd..b5f87b6b7d 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -120,10 +120,21 @@ } }); + // The pod announces its own roll before the stream drops (#15788). + source.addEventListener('upgrading', (e) => { + try { + versionHandleUpgradingEvent(JSON.parse(e.data)); + } catch (err) { + console.error('SSE upgrading parse error:', err); + } + }); + source.onerror = () => { if (conn) { + const roll = typeof versionReadUpgradeProgress === 'function' ? versionReadUpgradeProgress() : null; + const rolling = roll && roll.source === 'roll' && !roll.completedAt; conn.className = 'connection'; - conn.innerHTML = '● reconnecting...'; + conn.innerHTML = '● ' + (rolling ? (roll.target ? 'upgrading · reconnecting…' : 'restarting · reconnecting…') : 'reconnecting...'); } source.close(); if (_eventSource === source) _eventSource = null; diff --git a/src/pkg/dashboard/static-src/js/version.js b/src/pkg/dashboard/static-src/js/version.js index a294b2db8b..3d2341366c 100644 --- a/src/pkg/dashboard/static-src/js/version.js +++ b/src/pkg/dashboard/static-src/js/version.js @@ -8,7 +8,7 @@ const raw = localStorage.getItem(VERSION_UPGRADE_STORAGE_KEY); if (!raw) return null; const st = JSON.parse(raw); - if (!st || !st.target || st.target === 'latest' || !st.startedAt) { + if (!st || (!st.target && st.source !== 'roll') || st.target === 'latest' || !st.startedAt) { versionClearUpgradeProgress(); return null; } @@ -31,15 +31,25 @@ } function versionWriteUpgradeProgress(st) { - if (!st || !st.target || st.target === 'latest') return null; + if (!st || (!st.target && st.source !== 'roll') || st.target === 'latest') return null; const next = { - target: String(st.target), + target: String(st.target || ''), targetShort: versionShortSHA(st.targetShort || st.target), startedFrom: String(st.startedFrom || ''), startedAt: Number(st.startedAt || versionNowMs()), completedAt: st.completedAt ? Number(st.completedAt) : 0 }; if (st.source) next.source = String(st.source); + // Roll records (#15788): a pod roll announced by the hub/operator or + // caught at SIGTERM, tracked by process identity rather than target. + if (st.source === 'roll') { + next.phase = String(st.phase || 'announced'); + next.rollSource = String(st.rollSource || ''); + next.fromStartedAt = String(st.fromStartedAt || ''); + next.reason = String(st.reason || ''); + if (st.outcome) next.outcome = String(st.outcome); + if (st.toasted) next.toasted = true; + } try { localStorage.setItem(VERSION_UPGRADE_STORAGE_KEY, JSON.stringify(next)); } catch (_) {} return next; } @@ -71,6 +81,7 @@ function versionReconcileUpgradeProgress(v, now) { const st = versionReadUpgradeProgress(now); if (!st) return null; + if (st.source === 'roll') return versionRollReconcile(st, v, now); const running = v && (v.hash || v.short); const target = v && v.target || {}; const policy = versionPolicy(v) || {}; @@ -113,6 +124,247 @@ return st; } + // roll upgrade state begin + // Pod rolls (#15788). Self-upgrades drive the bee through a target SHA; + // a roll started by the hub's kubectl, an operator's `rollout restart` or + // a bare SIGTERM may have no target at all, so these records are keyed on + // process identity instead: the build hash and /api/version startedAt the + // old pod had. On reconnect a changed hash means "Upgraded", a changed + // startedAt on the same hash means "Restarted". The records render through + // the same surfaces (chip, navbar indicator, version card) as self-upgrades. + + function versionRollPhaseActive(phase) { + return phase === 'announced' || phase === 'restarting'; + } + + function versionRollRecordFromEvent(ev, current, now) { + ev = ev || {}; + current = current || {}; + now = now || versionNowMs(); + if (!versionRollPhaseActive(ev.phase)) return null; + const prev = versionReadUpgradeProgress(now); + // A self-upgrade (or adopted hub marker) already animating keeps its + // record: the SIGTERM it causes is the roll it was waiting for. + if (prev && prev.source !== 'roll' && !prev.completedAt) return prev; + let target = String(ev.target || ''); + const prevRoll = prev && prev.source === 'roll' && !prev.completedAt ? prev : null; + // A bare SIGTERM after an announce is that announce's kill: keep its target. + if (!target && prevRoll) target = prevRoll.target || ''; + let startedAt = Date.parse(ev.startedAt || ''); + if (!isFinite(startedAt) || startedAt <= 0 || now - startedAt > VERSION_UPGRADE_LONG_MS) startedAt = now; + if (prevRoll && versionSameRollTarget(prevRoll.target, target)) startedAt = prevRoll.startedAt; + const st = versionWriteUpgradeProgress({ + source: 'roll', + phase: ev.phase, + rollSource: ev.source || (prevRoll && prevRoll.rollSource) || '', + target: target, + targetShort: versionShortSHA(target), + startedFrom: current.hash || current.short || ev.from || '', + fromStartedAt: ev.processStartedAt || current.startedAt || '', + reason: ev.reason || (prevRoll && prevRoll.reason) || '', + startedAt: startedAt + }); + if (st) { + _upgradeInProgress = true; + _upgradeTargetHash = st.target || null; + } + return st; + } + + function versionSameRollTarget(a, b) { + a = String(a || ''); b = String(b || ''); + if (!a || !b) return a === b; + return versionSameCommit(a, b) || a.toLowerCase() === b.toLowerCase(); + } + + // The server's own view of an announced/restarting roll reaches the page + // as v.upgradeProgress (a tab opened after the announce, or an SSE frame + // that was missed). Mirror it into the record once. + function versionAdoptServerRollProgress(v, now) { + const sp = v && v.upgradeProgress; + if (!sp || !versionRollPhaseActive(sp.phase)) return null; + return versionRollRecordFromEvent({ + phase: sp.phase, source: sp.source, target: sp.target, from: sp.from, + reason: sp.reason, startedAt: sp.startedAt, processStartedAt: v.startedAt + }, v, now); + } + + function versionRollComplete(st, outcome, v, now) { + now = now || versionNowMs(); + const running = v && (v.hash || v.short) || ''; + const next = versionWriteUpgradeProgress({ + source: 'roll', phase: st.phase, rollSource: st.rollSource, reason: st.reason, + target: outcome === 'upgraded' ? (running || st.target) : (st.target || running), + targetShort: versionShortSHA(outcome === 'upgraded' ? (running || st.target) : (st.target || running)), + startedFrom: st.startedFrom, fromStartedAt: st.fromStartedAt, + startedAt: st.startedAt, completedAt: now, outcome: outcome + }); + _upgradeInProgress = false; + _upgradeTargetHash = null; + return next; + } + + // Outcome of one fresh /api/version read against a roll record: + // 'upgraded' | 'restarted' | 'pending' | 'aborted'. + function versionRollOutcome(st, v) { + if (!st || st.completedAt) return st && st.outcome || 'pending'; + if (st.rollSource === 'demo') return 'pending'; + if (!v) return 'pending'; + const running = v.hash || v.short || ''; + if (st.startedFrom && running && !versionSameCommit(running, st.startedFrom)) return 'upgraded'; + if (st.fromStartedAt && v.startedAt && String(v.startedAt) !== String(st.fromStartedAt)) return 'restarted'; + const sp = v.upgradeProgress; + if (sp && versionRollPhaseActive(sp.phase)) return 'pending'; + if (st.phase === 'restarting') return 'pending'; + return 'aborted'; + } + + function versionRollReconcile(st, v, now) { + now = now || versionNowMs(); + if (st.completedAt) { + _upgradeInProgress = false; + return st; + } + const outcome = versionRollOutcome(st, v); + if (outcome === 'aborted') { + versionClearUpgradeProgress(); + return null; + } + if (outcome === 'pending') { + const sp = v && v.upgradeProgress; + if (sp && versionRollPhaseActive(sp.phase) && sp.phase !== st.phase) { + st = versionWriteUpgradeProgress(Object.assign({}, st, { phase: sp.phase, target: st.target || sp.target || '', targetShort: versionShortSHA(st.target || sp.target) })) || st; + } + _upgradeInProgress = true; + _upgradeTargetHash = st.target || null; + return st; + } + const done = versionRollComplete(st, outcome, v, now); + versionRollNotify(done); + return done; + } + + function versionRollNotify(st) { + if (!st || !st.outcome || st.toasted) return st; + const marked = versionWriteUpgradeProgress(Object.assign({}, st, { toasted: true })) || st; + if (typeof showToast === 'function') { + const ver = st.targetShort || versionShortSHA(st.target) || ''; + showToast(st.outcome === 'upgraded' ? 'Upgraded to ' + ver + ' ✓' : 'Hive restarted' + (ver ? ' · still on ' + ver : '') + ' ✓', 'success', false, VERSION_ROLL_TOAST_MS); + } + return marked; + } + + function versionRollWho(st) { + const who = String(st && st.rollSource || ''); + if (who === 'hub' || who === 'operator') return 'the ' + who; + if (who === 'signal') return 'SIGTERM'; + if (who === 'demo') return 'preview'; + return who; + } + + function versionRollTitle(st) { + if (!st) return ''; + if (st.outcome === 'upgraded') return 'Upgraded ✓'; + if (st.outcome === 'restarted') return 'Restarted ✓'; + if (st.phase === 'restarting') return st.target ? 'Upgrading hive…' : 'Restarting hive…'; + return st.target ? 'Upgrading hive…' : 'Restart announced…'; + } + + function versionRollStartupLabel(v) { + if (!v) return ''; + const label = v.startupPhaseLabel || v.startupPhase || ''; + return label ? 'starting: ' + String(label) : ''; + } + + function versionRollStatusText(st, v, now) { + if (!st) return ''; + now = now || versionNowMs(); + const target = st.targetShort || versionShortSHA(st.target || ''); + const elapsed = versionElapsedText(st.startedAt, now); + if (st.outcome === 'upgraded') return '✅ Upgraded to ' + target + (elapsed ? ' · ' + elapsed : ''); + if (st.outcome === 'restarted') return '↻ Restarted' + (target ? ' · still on ' + target : '') + (elapsed ? ' · ' + elapsed : ''); + if (st.phase === 'restarting') { + const startup = versionRollStartupLabel(v); + return 'restarting' + (target ? ' → ' + target : '') + ' · ' + (startup || 'reconnecting') + (elapsed ? ' · ' + elapsed : ''); + } + const who = versionRollWho(st); + return 'roll announced' + (who ? ' by ' + who : '') + (target ? ' → ' + target : '') + (st.reason ? ' — ' + st.reason : '') + (elapsed ? ' · ' + elapsed : ''); + } + + function versionRollStatusHTML(st, v, now) { + return escapeHtml(versionRollStatusText(st, v, now)); + } + + function versionRollNavbarStatus(st, v, now) { + if (!st) return ''; + const target = st.targetShort || versionShortSHA(st.target || ''); + if (st.outcome) return target || ''; + if (st.phase === 'restarting') return (target ? '→ ' + target + ' · ' : '') + (versionRollStartupLabel(v) || 'reconnecting'); + return target ? '→ ' + target : 'queued'; + } + + // The silent reload on hash change must wait for the banner to say + // "Upgraded ✓" first, else the operator never sees the outcome. + function versionRollReloadDeferred(st, now) { + if (!st || st.source !== 'roll') return false; + now = now || versionNowMs(); + if (!st.completedAt) return true; + return now - Number(st.completedAt) < VERSION_ROLL_TOAST_MS; + } + + function versionDemoRequested(search) { + return /[?&]demo=upgrade(?:&|$)/.test(String(search || '')); + } + // roll upgrade state end + + function versionHandleUpgradingEvent(ev) { + const current = window._lastVersionData || {}; + const st = versionRollRecordFromEvent(ev, current, versionNowMs()); + if (!st) return null; + const conn = document.getElementById('conn'); + if (conn && st.phase === 'restarting') { + conn.className = 'connection'; + conn.innerHTML = '● ' + escapeHtml(st.target ? 'upgrading · reconnecting…' : 'restarting · reconnecting…'); + } + const ctx = window._lastVersionContext; + if (ctx) { + ctx.upgradeProgress = st; + ctx.hasUpgrade = false; + renderVersionSurfaces(current, ctx); + } + versionScheduleUpgradePoll(st); + return st; + } + + // Settings → Diagnostics "Preview upgrade animation" and ?demo=upgrade: + // walks the roll record through announced → restarting → upgraded with + // timers, so the operator can see what a roll looks like without rolling. + function versionPreviewUpgradeDemo() { + const current = window._lastVersionData || {}; + const running = current.hash || current.short || ''; + const target = running || 'preview'; + const base = { phase: 'announced', source: 'demo', target: target, from: running, reason: 'preview', processStartedAt: current.startedAt || '' }; + versionClearUpgradeProgress(); + const step = function(patch) { + const st = versionHandleUpgradingEvent(Object.assign({}, base, patch || {})); + return st; + }; + step(); + setTimeout(function() { step({ phase: 'restarting' }); }, VERSION_ROLL_DEMO_STEP_MS); + setTimeout(function() { + const st = versionReadUpgradeProgress(); + if (!st || st.rollSource !== 'demo') return; + const done = versionRollNotify(versionRollComplete(st, 'upgraded', current, versionNowMs())); + const ctx = window._lastVersionContext; + if (ctx) { + ctx.upgradeProgress = done; + renderVersionSurfaces(current, ctx); + } + versionScheduleUpgradePoll(done); + }, VERSION_ROLL_DEMO_STEP_MS * 2); + if (typeof showToast === 'function') showToast('Previewing the upgrade animation — nothing is being rolled', 'info'); + } + function versionHubUpgradeAttemptKey(um) { if (!um || !um.target) return ''; return [String(um.target), String(um.requestedAt || ''), String(um.attempts || '')].map(function(part) { return part.trim(); }).join('|'); @@ -163,6 +415,9 @@ } if (!state) return; let delay = VERSION_UPGRADE_POLL_MS; + if (state !== true && state.source === 'roll' && !state.completedAt && state.phase === 'restarting') { + delay = VERSION_ROLL_POLL_MS; + } if (state !== true && state.completedAt) { delay = Math.max(500, VERSION_UPGRADE_DONE_MS - (versionNowMs() - Number(state.completedAt)) + 100); } @@ -394,6 +649,7 @@ function versionUpgradeProgressStatus(v, st) { if (!st) return ''; + if (st.source === 'roll') return versionRollStatusHTML(st, v); const target = escapeHtml(st.targetShort || versionShortSHA(st.target || 'target')); const elapsed = versionElapsedText(st.startedAt); if (st.completedAt) return '✅ Upgraded to ' + target + (elapsed ? ' · ' + elapsed : ''); @@ -414,9 +670,15 @@ return [st.target || st.targetShort || 'target', st.startedAt || '0'].map(function(part) { return String(part || '').trim(); }).join('|'); } + function versionUpgradeTitle(st, compact) { + if (st && st.source === 'roll') return versionRollTitle(st); + if (st && st.completedAt) return compact ? 'Upgrade complete ✓' : 'Upgrade complete'; + return 'Upgrading…'; + } + function versionBeeProgressHTML(st, v) { if (!st) return ''; - const title = st.completedAt ? 'Upgrade complete' : 'Upgrading…'; + const title = versionUpgradeTitle(st, false); const key = versionUpgradeKey(st); return '
' + versionUpgradeHiveHTML(key) + '
' + escapeHtml(title) + '
' + @@ -449,8 +711,9 @@ const target = st.targetShort || versionShortSHA(st.target || ''); const elapsed = versionElapsedText(st.startedAt); const complete = !!st.completedAt; - const title = complete ? 'Upgrade complete ✓' : 'Upgrading…'; - const status = complete ? (target || '') : ((target ? '→ ' + target : versionUpgradeProgressStatus(v || {}, st)) + (elapsed ? ' · ' + elapsed : '')); + const title = versionUpgradeTitle(st, true); + const status = st.source === 'roll' ? versionRollNavbarStatus(st, v || {}) : + complete ? (target || '') : ((target ? '→ ' + target : versionUpgradeProgressStatus(v || {}, st)) + (elapsed ? ' · ' + elapsed : '')); const key = versionUpgradeKey(st); return '' + versionUpgradeHiveHTML(key) + '' + escapeHtml(title) + (complete ? '' : ' ') + '' + @@ -732,6 +995,7 @@ _upgradeTargetHash = null; } let upgradeProgress = versionReconcileUpgradeProgress(v); + if (!upgradeProgress) upgradeProgress = versionAdoptServerRollProgress(v); if (!upgradeProgress) upgradeProgress = versionAdoptHubUpgradeProgress(v); const upgradeCurrentHash = String(v.hash || '').toLowerCase(); const upgradeTargetHash = String(_upgradeTargetHash || '').toLowerCase(); @@ -1419,11 +1683,15 @@ dashboardSetInterval('version-reload-check', function() { fetch('/api/version').then(function(r) { return r.json(); }).then(function(d) { var current = d.hash || d.short || ''; + if (versionRollReloadDeferred(versionReadUpgradeProgress())) return; if (_initialVersionHash && current && current !== _initialVersionHash) { console.log('[hive] version changed from', _initialVersionHash, 'to', current, '— reloading'); reloadForNewVersion(); } }).catch(function() {}); }, VERSION_CHECK_INTERVAL_MS); + if (versionDemoRequested(window.location && window.location.search)) { + setTimeout(versionPreviewUpgradeDemo, VERSION_ROLL_DEMO_START_MS); + } } // startVersionCheck() — deferred to _deferredInit diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 4791999463..7c65a1351c 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -5342,6 +5342,12 @@ .gh-api-budget-fill.debug-quota-ok { fill: var(--green); } .gh-api-budget-fill.debug-quota-warn { fill: var(--yellow); } .gh-api-budget-fill.debug-quota-bad { fill: var(--red); } + /* Settings → Diagnostics "Hive process" tile (#15788): same tile look as the + inline-styled siblings, in tokens, so the style ratchet stays flat. */ + .debug-process-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r); padding: var(--sp-6); min-width: 0; } + .debug-process-label { font-size: var(--fs-2xs); text-transform: uppercase; letter-spacing: 0.5px; color: var(--muted); margin-bottom: var(--sp-4); font-weight: 600; } + .debug-process-note { color: var(--muted); font-size: var(--fs-sm); line-height: 1.45; } + .debug-process-actions { margin-top: var(--sp-3); } .gh-api-budget-table-wrap { overflow-x: auto; overscroll-behavior-x: contain; max-width: 100%; margin-top: var(--sp-4); } .gh-api-budget-table { width: 100%; min-width: 36rem; table-layout: fixed; border-collapse: collapse; font-size: var(--fs-xs); } .gh-api-budget-table th, .gh-api-budget-table td { text-align: left; padding: var(--sp-1) var(--sp-3) var(--sp-1) 0; white-space: normal; overflow-wrap: anywhere; } @@ -43251,6 +43257,11 @@

GitHub Projects sync

Cache Read${tokenCache}
${budgetLimit > 0 ? `
Budget
Used$${budgetUsed.toFixed(2)} / $${budgetLimit.toFixed(2)} (${budgetPct}%)
` : ''}
+
+
Hive process
+
Pod rolls — by the hub, kubectl rollout restart or SIGTERM — animate the version chip while the pod restarts.
+
+
`); applySectionCollapse('debug-section'); } @@ -46272,6 +46283,13 @@

Configure LiteLLM

const VERSION_UPGRADE_DONE_MS = 30000; const VERSION_UPGRADE_LONG_MS = 15 * 60 * 1000; const VERSION_UPGRADE_POLL_MS = 5000; + // Pod rolls (#15788): poll faster while the pod is down, hold the + // "Upgraded ✓" outcome for the standard toast countdown, and pace the + // on-demand preview. + const VERSION_ROLL_POLL_MS = 2000; + const VERSION_ROLL_TOAST_MS = 15000; + const VERSION_ROLL_DEMO_STEP_MS = 4000; + const VERSION_ROLL_DEMO_START_MS = 1500; let _versionUpgradePollTimer = null; function versionNowMs() { @@ -46284,7 +46302,7 @@

Configure LiteLLM

const raw = localStorage.getItem(VERSION_UPGRADE_STORAGE_KEY); if (!raw) return null; const st = JSON.parse(raw); - if (!st || !st.target || st.target === 'latest' || !st.startedAt) { + if (!st || (!st.target && st.source !== 'roll') || st.target === 'latest' || !st.startedAt) { versionClearUpgradeProgress(); return null; } @@ -46307,15 +46325,25 @@

Configure LiteLLM

} function versionWriteUpgradeProgress(st) { - if (!st || !st.target || st.target === 'latest') return null; + if (!st || (!st.target && st.source !== 'roll') || st.target === 'latest') return null; const next = { - target: String(st.target), + target: String(st.target || ''), targetShort: versionShortSHA(st.targetShort || st.target), startedFrom: String(st.startedFrom || ''), startedAt: Number(st.startedAt || versionNowMs()), completedAt: st.completedAt ? Number(st.completedAt) : 0 }; if (st.source) next.source = String(st.source); + // Roll records (#15788): a pod roll announced by the hub/operator or + // caught at SIGTERM, tracked by process identity rather than target. + if (st.source === 'roll') { + next.phase = String(st.phase || 'announced'); + next.rollSource = String(st.rollSource || ''); + next.fromStartedAt = String(st.fromStartedAt || ''); + next.reason = String(st.reason || ''); + if (st.outcome) next.outcome = String(st.outcome); + if (st.toasted) next.toasted = true; + } try { localStorage.setItem(VERSION_UPGRADE_STORAGE_KEY, JSON.stringify(next)); } catch (_) {} return next; } @@ -46347,6 +46375,7 @@

Configure LiteLLM

function versionReconcileUpgradeProgress(v, now) { const st = versionReadUpgradeProgress(now); if (!st) return null; + if (st.source === 'roll') return versionRollReconcile(st, v, now); const running = v && (v.hash || v.short); const target = v && v.target || {}; const policy = versionPolicy(v) || {}; @@ -46389,6 +46418,247 @@

Configure LiteLLM

return st; } + // roll upgrade state begin + // Pod rolls (#15788). Self-upgrades drive the bee through a target SHA; + // a roll started by the hub's kubectl, an operator's `rollout restart` or + // a bare SIGTERM may have no target at all, so these records are keyed on + // process identity instead: the build hash and /api/version startedAt the + // old pod had. On reconnect a changed hash means "Upgraded", a changed + // startedAt on the same hash means "Restarted". The records render through + // the same surfaces (chip, navbar indicator, version card) as self-upgrades. + + function versionRollPhaseActive(phase) { + return phase === 'announced' || phase === 'restarting'; + } + + function versionRollRecordFromEvent(ev, current, now) { + ev = ev || {}; + current = current || {}; + now = now || versionNowMs(); + if (!versionRollPhaseActive(ev.phase)) return null; + const prev = versionReadUpgradeProgress(now); + // A self-upgrade (or adopted hub marker) already animating keeps its + // record: the SIGTERM it causes is the roll it was waiting for. + if (prev && prev.source !== 'roll' && !prev.completedAt) return prev; + let target = String(ev.target || ''); + const prevRoll = prev && prev.source === 'roll' && !prev.completedAt ? prev : null; + // A bare SIGTERM after an announce is that announce's kill: keep its target. + if (!target && prevRoll) target = prevRoll.target || ''; + let startedAt = Date.parse(ev.startedAt || ''); + if (!isFinite(startedAt) || startedAt <= 0 || now - startedAt > VERSION_UPGRADE_LONG_MS) startedAt = now; + if (prevRoll && versionSameRollTarget(prevRoll.target, target)) startedAt = prevRoll.startedAt; + const st = versionWriteUpgradeProgress({ + source: 'roll', + phase: ev.phase, + rollSource: ev.source || (prevRoll && prevRoll.rollSource) || '', + target: target, + targetShort: versionShortSHA(target), + startedFrom: current.hash || current.short || ev.from || '', + fromStartedAt: ev.processStartedAt || current.startedAt || '', + reason: ev.reason || (prevRoll && prevRoll.reason) || '', + startedAt: startedAt + }); + if (st) { + _upgradeInProgress = true; + _upgradeTargetHash = st.target || null; + } + return st; + } + + function versionSameRollTarget(a, b) { + a = String(a || ''); b = String(b || ''); + if (!a || !b) return a === b; + return versionSameCommit(a, b) || a.toLowerCase() === b.toLowerCase(); + } + + // The server's own view of an announced/restarting roll reaches the page + // as v.upgradeProgress (a tab opened after the announce, or an SSE frame + // that was missed). Mirror it into the record once. + function versionAdoptServerRollProgress(v, now) { + const sp = v && v.upgradeProgress; + if (!sp || !versionRollPhaseActive(sp.phase)) return null; + return versionRollRecordFromEvent({ + phase: sp.phase, source: sp.source, target: sp.target, from: sp.from, + reason: sp.reason, startedAt: sp.startedAt, processStartedAt: v.startedAt + }, v, now); + } + + function versionRollComplete(st, outcome, v, now) { + now = now || versionNowMs(); + const running = v && (v.hash || v.short) || ''; + const next = versionWriteUpgradeProgress({ + source: 'roll', phase: st.phase, rollSource: st.rollSource, reason: st.reason, + target: outcome === 'upgraded' ? (running || st.target) : (st.target || running), + targetShort: versionShortSHA(outcome === 'upgraded' ? (running || st.target) : (st.target || running)), + startedFrom: st.startedFrom, fromStartedAt: st.fromStartedAt, + startedAt: st.startedAt, completedAt: now, outcome: outcome + }); + _upgradeInProgress = false; + _upgradeTargetHash = null; + return next; + } + + // Outcome of one fresh /api/version read against a roll record: + // 'upgraded' | 'restarted' | 'pending' | 'aborted'. + function versionRollOutcome(st, v) { + if (!st || st.completedAt) return st && st.outcome || 'pending'; + if (st.rollSource === 'demo') return 'pending'; + if (!v) return 'pending'; + const running = v.hash || v.short || ''; + if (st.startedFrom && running && !versionSameCommit(running, st.startedFrom)) return 'upgraded'; + if (st.fromStartedAt && v.startedAt && String(v.startedAt) !== String(st.fromStartedAt)) return 'restarted'; + const sp = v.upgradeProgress; + if (sp && versionRollPhaseActive(sp.phase)) return 'pending'; + if (st.phase === 'restarting') return 'pending'; + return 'aborted'; + } + + function versionRollReconcile(st, v, now) { + now = now || versionNowMs(); + if (st.completedAt) { + _upgradeInProgress = false; + return st; + } + const outcome = versionRollOutcome(st, v); + if (outcome === 'aborted') { + versionClearUpgradeProgress(); + return null; + } + if (outcome === 'pending') { + const sp = v && v.upgradeProgress; + if (sp && versionRollPhaseActive(sp.phase) && sp.phase !== st.phase) { + st = versionWriteUpgradeProgress(Object.assign({}, st, { phase: sp.phase, target: st.target || sp.target || '', targetShort: versionShortSHA(st.target || sp.target) })) || st; + } + _upgradeInProgress = true; + _upgradeTargetHash = st.target || null; + return st; + } + const done = versionRollComplete(st, outcome, v, now); + versionRollNotify(done); + return done; + } + + function versionRollNotify(st) { + if (!st || !st.outcome || st.toasted) return st; + const marked = versionWriteUpgradeProgress(Object.assign({}, st, { toasted: true })) || st; + if (typeof showToast === 'function') { + const ver = st.targetShort || versionShortSHA(st.target) || ''; + showToast(st.outcome === 'upgraded' ? 'Upgraded to ' + ver + ' ✓' : 'Hive restarted' + (ver ? ' · still on ' + ver : '') + ' ✓', 'success', false, VERSION_ROLL_TOAST_MS); + } + return marked; + } + + function versionRollWho(st) { + const who = String(st && st.rollSource || ''); + if (who === 'hub' || who === 'operator') return 'the ' + who; + if (who === 'signal') return 'SIGTERM'; + if (who === 'demo') return 'preview'; + return who; + } + + function versionRollTitle(st) { + if (!st) return ''; + if (st.outcome === 'upgraded') return 'Upgraded ✓'; + if (st.outcome === 'restarted') return 'Restarted ✓'; + if (st.phase === 'restarting') return st.target ? 'Upgrading hive…' : 'Restarting hive…'; + return st.target ? 'Upgrading hive…' : 'Restart announced…'; + } + + function versionRollStartupLabel(v) { + if (!v) return ''; + const label = v.startupPhaseLabel || v.startupPhase || ''; + return label ? 'starting: ' + String(label) : ''; + } + + function versionRollStatusText(st, v, now) { + if (!st) return ''; + now = now || versionNowMs(); + const target = st.targetShort || versionShortSHA(st.target || ''); + const elapsed = versionElapsedText(st.startedAt, now); + if (st.outcome === 'upgraded') return '✅ Upgraded to ' + target + (elapsed ? ' · ' + elapsed : ''); + if (st.outcome === 'restarted') return '↻ Restarted' + (target ? ' · still on ' + target : '') + (elapsed ? ' · ' + elapsed : ''); + if (st.phase === 'restarting') { + const startup = versionRollStartupLabel(v); + return 'restarting' + (target ? ' → ' + target : '') + ' · ' + (startup || 'reconnecting') + (elapsed ? ' · ' + elapsed : ''); + } + const who = versionRollWho(st); + return 'roll announced' + (who ? ' by ' + who : '') + (target ? ' → ' + target : '') + (st.reason ? ' — ' + st.reason : '') + (elapsed ? ' · ' + elapsed : ''); + } + + function versionRollStatusHTML(st, v, now) { + return escapeHtml(versionRollStatusText(st, v, now)); + } + + function versionRollNavbarStatus(st, v, now) { + if (!st) return ''; + const target = st.targetShort || versionShortSHA(st.target || ''); + if (st.outcome) return target || ''; + if (st.phase === 'restarting') return (target ? '→ ' + target + ' · ' : '') + (versionRollStartupLabel(v) || 'reconnecting'); + return target ? '→ ' + target : 'queued'; + } + + // The silent reload on hash change must wait for the banner to say + // "Upgraded ✓" first, else the operator never sees the outcome. + function versionRollReloadDeferred(st, now) { + if (!st || st.source !== 'roll') return false; + now = now || versionNowMs(); + if (!st.completedAt) return true; + return now - Number(st.completedAt) < VERSION_ROLL_TOAST_MS; + } + + function versionDemoRequested(search) { + return /[?&]demo=upgrade(?:&|$)/.test(String(search || '')); + } + // roll upgrade state end + + function versionHandleUpgradingEvent(ev) { + const current = window._lastVersionData || {}; + const st = versionRollRecordFromEvent(ev, current, versionNowMs()); + if (!st) return null; + const conn = document.getElementById('conn'); + if (conn && st.phase === 'restarting') { + conn.className = 'connection'; + conn.innerHTML = '● ' + escapeHtml(st.target ? 'upgrading · reconnecting…' : 'restarting · reconnecting…'); + } + const ctx = window._lastVersionContext; + if (ctx) { + ctx.upgradeProgress = st; + ctx.hasUpgrade = false; + renderVersionSurfaces(current, ctx); + } + versionScheduleUpgradePoll(st); + return st; + } + + // Settings → Diagnostics "Preview upgrade animation" and ?demo=upgrade: + // walks the roll record through announced → restarting → upgraded with + // timers, so the operator can see what a roll looks like without rolling. + function versionPreviewUpgradeDemo() { + const current = window._lastVersionData || {}; + const running = current.hash || current.short || ''; + const target = running || 'preview'; + const base = { phase: 'announced', source: 'demo', target: target, from: running, reason: 'preview', processStartedAt: current.startedAt || '' }; + versionClearUpgradeProgress(); + const step = function(patch) { + const st = versionHandleUpgradingEvent(Object.assign({}, base, patch || {})); + return st; + }; + step(); + setTimeout(function() { step({ phase: 'restarting' }); }, VERSION_ROLL_DEMO_STEP_MS); + setTimeout(function() { + const st = versionReadUpgradeProgress(); + if (!st || st.rollSource !== 'demo') return; + const done = versionRollNotify(versionRollComplete(st, 'upgraded', current, versionNowMs())); + const ctx = window._lastVersionContext; + if (ctx) { + ctx.upgradeProgress = done; + renderVersionSurfaces(current, ctx); + } + versionScheduleUpgradePoll(done); + }, VERSION_ROLL_DEMO_STEP_MS * 2); + if (typeof showToast === 'function') showToast('Previewing the upgrade animation — nothing is being rolled', 'info'); + } + function versionHubUpgradeAttemptKey(um) { if (!um || !um.target) return ''; return [String(um.target), String(um.requestedAt || ''), String(um.attempts || '')].map(function(part) { return part.trim(); }).join('|'); @@ -46439,6 +46709,9 @@

Configure LiteLLM

} if (!state) return; let delay = VERSION_UPGRADE_POLL_MS; + if (state !== true && state.source === 'roll' && !state.completedAt && state.phase === 'restarting') { + delay = VERSION_ROLL_POLL_MS; + } if (state !== true && state.completedAt) { delay = Math.max(500, VERSION_UPGRADE_DONE_MS - (versionNowMs() - Number(state.completedAt)) + 100); } @@ -46670,6 +46943,7 @@

Configure LiteLLM

function versionUpgradeProgressStatus(v, st) { if (!st) return ''; + if (st.source === 'roll') return versionRollStatusHTML(st, v); const target = escapeHtml(st.targetShort || versionShortSHA(st.target || 'target')); const elapsed = versionElapsedText(st.startedAt); if (st.completedAt) return '✅ Upgraded to ' + target + (elapsed ? ' · ' + elapsed : ''); @@ -46690,9 +46964,15 @@

Configure LiteLLM

return [st.target || st.targetShort || 'target', st.startedAt || '0'].map(function(part) { return String(part || '').trim(); }).join('|'); } + function versionUpgradeTitle(st, compact) { + if (st && st.source === 'roll') return versionRollTitle(st); + if (st && st.completedAt) return compact ? 'Upgrade complete ✓' : 'Upgrade complete'; + return 'Upgrading…'; + } + function versionBeeProgressHTML(st, v) { if (!st) return ''; - const title = st.completedAt ? 'Upgrade complete' : 'Upgrading…'; + const title = versionUpgradeTitle(st, false); const key = versionUpgradeKey(st); return '
' + versionUpgradeHiveHTML(key) + '
' + escapeHtml(title) + '
' + @@ -46725,8 +47005,9 @@

Configure LiteLLM

const target = st.targetShort || versionShortSHA(st.target || ''); const elapsed = versionElapsedText(st.startedAt); const complete = !!st.completedAt; - const title = complete ? 'Upgrade complete ✓' : 'Upgrading…'; - const status = complete ? (target || '') : ((target ? '→ ' + target : versionUpgradeProgressStatus(v || {}, st)) + (elapsed ? ' · ' + elapsed : '')); + const title = versionUpgradeTitle(st, true); + const status = st.source === 'roll' ? versionRollNavbarStatus(st, v || {}) : + complete ? (target || '') : ((target ? '→ ' + target : versionUpgradeProgressStatus(v || {}, st)) + (elapsed ? ' · ' + elapsed : '')); const key = versionUpgradeKey(st); return '' + versionUpgradeHiveHTML(key) + '' + escapeHtml(title) + (complete ? '' : ' ') + '' + @@ -47008,6 +47289,7 @@

Configure LiteLLM

_upgradeTargetHash = null; } let upgradeProgress = versionReconcileUpgradeProgress(v); + if (!upgradeProgress) upgradeProgress = versionAdoptServerRollProgress(v); if (!upgradeProgress) upgradeProgress = versionAdoptHubUpgradeProgress(v); const upgradeCurrentHash = String(v.hash || '').toLowerCase(); const upgradeTargetHash = String(_upgradeTargetHash || '').toLowerCase(); @@ -47695,12 +47977,16 @@

Configure LiteLLM

dashboardSetInterval('version-reload-check', function() { fetch('/api/version').then(function(r) { return r.json(); }).then(function(d) { var current = d.hash || d.short || ''; + if (versionRollReloadDeferred(versionReadUpgradeProgress())) return; if (_initialVersionHash && current && current !== _initialVersionHash) { console.log('[hive] version changed from', _initialVersionHash, 'to', current, '— reloading'); reloadForNewVersion(); } }).catch(function() {}); }, VERSION_CHECK_INTERVAL_MS); + if (versionDemoRequested(window.location && window.location.search)) { + setTimeout(versionPreviewUpgradeDemo, VERSION_ROLL_DEMO_START_MS); + } } // startVersionCheck() — deferred to _deferredInit var _eventSource = null; @@ -47825,10 +48111,21 @@

Configure LiteLLM

} }); + // The pod announces its own roll before the stream drops (#15788). + source.addEventListener('upgrading', (e) => { + try { + versionHandleUpgradingEvent(JSON.parse(e.data)); + } catch (err) { + console.error('SSE upgrading parse error:', err); + } + }); + source.onerror = () => { if (conn) { + const roll = typeof versionReadUpgradeProgress === 'function' ? versionReadUpgradeProgress() : null; + const rolling = roll && roll.source === 'roll' && !roll.completedAt; conn.className = 'connection'; - conn.innerHTML = '● reconnecting...'; + conn.innerHTML = '● ' + (rolling ? (roll.target ? 'upgrading · reconnecting…' : 'restarting · reconnecting…') : 'reconnecting...'); } source.close(); if (_eventSource === source) _eventSource = null; diff --git a/src/pkg/dashboard/upgrade_announce.go b/src/pkg/dashboard/upgrade_announce.go new file mode 100644 index 0000000000..d5147025d0 --- /dev/null +++ b/src/pkg/dashboard/upgrade_announce.go @@ -0,0 +1,408 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/hub/spoke" +) + +// Every roll gets the upgrade animation (hivecommons/hive#15788). The spoke's +// upgrade state machine (upgrade_progress.go) used to derive its state only +// from the self-upgrade path — drain latch, PVC marker, landed outcome — so a +// hub-managed kubectl roll, an operator's `kubectl rollout restart` or a +// plain SIGTERM showed nothing until the SSE stream dropped. Two layers fix +// that, both rendered through the same UpgradeProgress the self-upgrade uses: +// +// - INTENT before the kill: AnnounceUpgrade (POST /api/upgrade/announce, or +// the heartbeat's upgrade_announce from the hub) marks the progress +// in-flight with phase=announced and the target, and publishes an SSE +// "upgrading" event. +// - FALLBACK at the kill: AnnounceRestart runs from the SIGTERM hook, +// publishes "upgrading" with phase=restarting (target from the announce +// or the hub's armed/target SHA when known) and marks the progress +// rolling before the process exits. +// +// The SPA adopts either into the bee animation and, after reconnecting, +// compares the new build's SHA and process start to say "Upgraded → " or +// "Restarted". + +// upgradeAnnounceStaleAfter bounds how long an announce without a kill keeps +// the progress in flight. A hub may abort a roll it announced, an operator +// script may fail between the announce and the restart; after this the pill +// falls back to the scheduled state instead of claiming an upgrade forever. +const upgradeAnnounceStaleAfter = 15 * time.Minute + +// upgradeAnnounceMaxField caps the target/reason strings an announce may +// carry, so a stray body cannot bloat /api/status. +const upgradeAnnounceMaxField = 200 + +// sseUpgradingEvent is the SSE event name the dashboard listens for. +const sseUpgradingEvent = "upgrading" + +// upgradeAnnounceState is the live announce/restart record behind +// buildUpgradeProgress's Announce input. +type upgradeAnnounceState struct { + Target string + Source string + Reason string + // At is when the announce arrived; StartedAt for the progress. + At time.Time + // Restarting is set by AnnounceRestart: the process is exiting now. + Restarting bool + // RestartAt is when the SIGTERM hook ran. + RestartAt time.Time +} + +// upgradeAnnounceStore guards the record; a zero value is usable so tests +// may build a bare Server. +type upgradeAnnounceStore struct { + mu sync.Mutex + state *upgradeAnnounceState +} + +func (st *upgradeAnnounceStore) get() *upgradeAnnounceState { + st.mu.Lock() + defer st.mu.Unlock() + if st.state == nil { + return nil + } + cp := *st.state + return &cp +} + +func (st *upgradeAnnounceStore) set(a *upgradeAnnounceState) { + st.mu.Lock() + st.state = a + st.mu.Unlock() +} + +// upgradeAnnounceEvent is the JSON body of the SSE "upgrading" event and of +// the announce endpoint's response. Field names mirror UpgradeProgress so the +// SPA can adopt either shape. +type upgradeAnnounceEvent struct { + Phase string `json:"phase"` + State string `json:"state"` + Source string `json:"source,omitempty"` + Target string `json:"target,omitempty"` + From string `json:"from,omitempty"` + Reason string `json:"reason,omitempty"` + StartedAt string `json:"startedAt,omitempty"` + // ProcessStartedAt identifies the process that announced, so the SPA can + // tell "same process, roll aborted" from "new process, restarted". + ProcessStartedAt string `json:"processStartedAt,omitempty"` + Detail string `json:"detail"` +} + +// liveUpgradeAnnounce returns the announce record if it is still current: +// a restart never expires (the process is exiting), an announce without a +// kill expires after upgradeAnnounceStaleAfter. +func liveUpgradeAnnounce(a *upgradeAnnounceState, now time.Time) *upgradeAnnounceState { + if a == nil { + return nil + } + if a.Restarting { + return a + } + if a.At.IsZero() || now.Sub(a.At) > upgradeAnnounceStaleAfter { + return nil + } + return a +} + +// announceProgress renders the announce/restart record in the shared state +// vocabulary: announced → pulling (the instruction is delivered, the pod is +// about to be rolled), restarting → rolling (the pod is going down now). +func announceProgress(a *upgradeAnnounceState, runningSHA, nextWindow string, now time.Time) *spoke.UpgradeProgress { + if a == nil { + return nil + } + rfc := func(t time.Time) string { + if t.IsZero() { + return "" + } + return t.UTC().Format(time.RFC3339) + } + target := shortSHADashboard(a.Target) + p := &spoke.UpgradeProgress{ + Target: target, + From: shortSHADashboard(runningSHA), + StartedAt: rfc(a.At), + NextWindowAt: nextWindow, + Reason: a.Reason, + Source: a.Source, + } + who := a.Source + if who == "" { + who = "the " + spoke.UpgradeSourceOperator + } else if who == spoke.UpgradeSourceHub || who == spoke.UpgradeSourceOperator { + who = "the " + who + } + if a.Restarting { + p.State = spoke.UpgradeStateRolling + p.Phase = spoke.UpgradePhaseRestarting + if a.Source == "" { + p.Source = spoke.UpgradeSourceSignal + } + if !a.RestartAt.IsZero() { + if a.At.IsZero() { + p.StartedAt = rfc(a.RestartAt) + } + } + if target != "" { + p.Detail = "restarting onto " + target + " · reconnecting" + } else { + p.Detail = "restarting · reconnecting" + } + return p + } + p.State = spoke.UpgradeStatePulling + p.Phase = spoke.UpgradePhaseAnnounced + if a.Source == "" { + p.Source = spoke.UpgradeSourceOperator + } + if target != "" { + p.Detail = "roll announced by " + who + ": restarting onto " + target + " " + spoke.FormatShortDuration(now.Sub(a.At)) + " ago" + } else { + p.Detail = "restart announced by " + who + " " + spoke.FormatShortDuration(now.Sub(a.At)) + " ago" + } + if a.Reason != "" { + p.Detail += " — " + a.Reason + } + return p +} + +// AnnounceUpgrade records a roll intent and publishes it on the SSE stream. +// A repeat announce for the same target refreshes the clock; a different +// target replaces the record. Returns the progress the announce renders as. +func (s *Server) AnnounceUpgrade(a spoke.UpgradeAnnounce, now time.Time) *spoke.UpgradeProgress { + if now.IsZero() { + now = time.Now() + } + source := strings.TrimSpace(a.Source) + if source != spoke.UpgradeSourceHub { + source = spoke.UpgradeSourceOperator + } + st := &upgradeAnnounceState{ + Target: clipAnnounceField(a.Target), + Source: source, + Reason: clipAnnounceField(a.Reason), + At: now, + } + if cur := liveUpgradeAnnounce(s.upgradeAnnounce.get(), now); cur != nil && !cur.Restarting && sameAnnounceTarget(cur.Target, st.Target) { + st.At = cur.At + } + s.upgradeAnnounce.set(st) + p := announceProgress(st, s.runningVersionHash(), "", now) + s.broadcastUpgrading(p, now) + if s.logger != nil { + s.logger.Info("upgrade announced", "source", st.Source, "target", st.Target, "reason", st.Reason) + } + return p +} + +// AnnounceRestart is the SIGTERM hook: the process is going down. It keeps +// an announced target when one is live, else falls back to the hub's +// armed/target SHA when that differs from the running build, else announces +// a bare restart. Publishes the SSE "upgrading" event before returning so +// the dashboard shows the animation instead of a bare "reconnecting". +func (s *Server) AnnounceRestart(now time.Time) *spoke.UpgradeProgress { + if now.IsZero() { + now = time.Now() + } + st := &upgradeAnnounceState{Restarting: true, RestartAt: now, Source: spoke.UpgradeSourceSignal} + if cur := liveUpgradeAnnounce(s.upgradeAnnounce.get(), now); cur != nil { + st.Target, st.Source, st.Reason, st.At = cur.Target, cur.Source, cur.Reason, cur.At + } + if st.Target == "" { + st.Target = s.hubTargetForRestart() + } + if st.At.IsZero() { + st.At = now + } + s.upgradeAnnounce.set(st) + p := announceProgress(st, s.runningVersionHash(), "", now) + s.broadcastUpgrading(p, now) + if s.logger != nil { + s.logger.Info("restart announced to dashboard", "source", st.Source, "target", st.Target) + } + return p +} + +// hubTargetForRestart is the best guess at what the pod restarts onto when +// nobody announced: the hub's armed target, else its resolved target SHA, +// when either differs from the running build. Empty when unknown. +func (s *Server) hubTargetForRestart() string { + s.versionMu.RLock() + policy := s.hubUpgradePolicy + s.versionMu.RUnlock() + if policy == nil { + return "" + } + running := s.runningVersionHash() + for _, cand := range []string{policy.ArmedTarget, policy.TargetSHA} { + cand = strings.TrimSpace(cand) + if cand == "" || (running != "" && sameCommitDashboard(running, cand)) { + continue + } + return cand + } + return "" +} + +func (s *Server) runningVersionHash() string { + if versionHash == "unknown" { + return "" + } + return versionHash +} + +// broadcastUpgrading publishes the progress as an SSE "upgrading" event. +func (s *Server) broadcastUpgrading(p *spoke.UpgradeProgress, now time.Time) { + if p == nil { + return + } + ev := upgradeAnnounceEvent{ + Phase: p.Phase, + State: p.State, + Source: p.Source, + Target: p.Target, + From: p.From, + Reason: p.Reason, + StartedAt: p.StartedAt, + Detail: p.Detail, + } + if !s.startedAt.IsZero() { + ev.ProcessStartedAt = s.startedAt.UTC().Format(time.RFC3339) + } + data, err := json.Marshal(ev) + if err != nil { + return + } + s.broadcastFrame("event: " + sseUpgradingEvent + "\ndata: " + string(data) + "\n\n") +} + +// upgradeAnnounceRequest is the body of POST /api/upgrade/announce. +type upgradeAnnounceRequest struct { + Target string `json:"target"` + Version string `json:"version"` + Source string `json:"source"` + Reason string `json:"reason"` +} + +// handleUpgradeAnnounce — POST /api/upgrade/announce. Owner-only. Lets the +// hub or an operator script say "I am about to roll this pod" so the +// dashboard animates the roll before the kill. Body: {"target": "", +// "source": "hub"|"operator", "reason": "..."}; "version" is accepted as an +// alias of target. Responds with the UpgradeProgress the spoke now reports. +func (s *Server) handleUpgradeAnnounce(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + var req upgradeAnnounceRequest + if r.Body != nil { + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil && err.Error() != "EOF" { + jsonError(w, "invalid JSON body", http.StatusBadRequest) + return + } + } + target := strings.TrimSpace(req.Target) + if target == "" { + target = strings.TrimSpace(req.Version) + } + p := s.AnnounceUpgrade(spoke.UpgradeAnnounce{Target: target, Source: req.Source, Reason: req.Reason}, time.Now()) + s.AuditLog("dashboard", "upgrade_announce", "source="+p.Source+" target="+orDashDashboard(p.Target), "") + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "upgradeProgress": p}) +} + +func clipAnnounceField(v string) string { + v = strings.TrimSpace(v) + if len(v) > upgradeAnnounceMaxField { + v = v[:upgradeAnnounceMaxField] + } + return v +} + +func sameAnnounceTarget(a, b string) bool { + if a == "" || b == "" { + return a == b + } + return sameCommitDashboard(a, b) || strings.EqualFold(a, b) +} + +// Startup phases (#15788). cmd/hive names each boot phase as it starts; +// while the first status payload has not been published, /api/status and +// /api/version carry startupPhase so the dashboard reconnecting onto the +// new pod can show what it is waiting on. + +// SetStartupPhase records the boot phase now running. Empty clears it. +func (s *Server) SetStartupPhase(phase string) { + s.startupPhase.Store(strings.TrimSpace(phase)) +} + +// StartupPhase returns the recorded phase, "" once the first status has been +// published (the boot is over as far as the dashboard is concerned). +func (s *Server) StartupPhase() string { + s.statusMu.RLock() + ready := s.status != nil + s.statusMu.RUnlock() + if ready { + return "" + } + v, _ := s.startupPhase.Load().(string) + return v +} + +// startupPhaseLabels maps cmd/hive boot phase names to the words the banner +// shows. Unknown names fall back to the raw phase. +var startupPhaseLabels = map[string]string{ + "bootGitHub": "connecting to GitHub", + "bootGovernor": "starting governor", + "bootAdvisory": "opening mutation ledger", + "bootAgents": "preparing agents", + "bootState": "restoring state", + "bootDashboard": "serving dashboard", + "bootStores": "opening stores", + "bootCollectors": "starting collectors", + "bootKnowledge": "indexing knowledge", + "bootSupervision": "starting supervision", + "bootDashboardAPI": "wiring dashboard API", + "bootPolicies": "loading policies", + "bootWatchers": "starting watchers", + "bootProxy": "starting proxy", + "bootLaunch": "launching agents", + "bootHeartbeat": "registering with hub", + "bootLanes": "opening lanes", + "firstEval": "first eval", +} + +// StartupPhaseLabel is the human label for a phase name. +func StartupPhaseLabel(phase string) string { + if l, ok := startupPhaseLabels[phase]; ok { + return l + } + return phase +} + +// initializingStatus is the /api/status body before the first eval: the +// legacy {"status":"initializing"} plus the build identity and boot phase +// the upgrade banner needs to say "Upgraded → " before the first eval. +func (s *Server) initializingStatus() map[string]any { + out := map[string]any{"status": "initializing"} + if phase := s.StartupPhase(); phase != "" { + out["startupPhase"] = phase + out["startupPhaseLabel"] = StartupPhaseLabel(phase) + } + if h := s.runningVersionHash(); h != "" { + out["hash"] = h + out["short"] = shortSHADashboard(h) + } + if !s.startedAt.IsZero() { + out["startedAt"] = s.startedAt.UTC().Format(time.RFC3339) + } + return out +} diff --git a/src/pkg/dashboard/upgrade_announce_test.go b/src/pkg/dashboard/upgrade_announce_test.go new file mode 100644 index 0000000000..3d74830236 --- /dev/null +++ b/src/pkg/dashboard/upgrade_announce_test.go @@ -0,0 +1,190 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/hub/spoke" +) + +// #15788: every roll — hub-driven, operator kubectl, bare SIGTERM — must +// surface through the same upgradeProgress the self-upgrade uses, and the +// SIGTERM path must publish an SSE "upgrading" frame before the stream drops. + +func announceOwnerRequest(method, path, body string) *http.Request { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-Role", "owner") + req.Header.Set(ownerRoleVerifiedHeader, "true") + return req +} + +func TestUpgradeAnnounceRejectsNonOwner(t *testing.T) { + s := newTestServer() + req := httptest.NewRequest(http.MethodPost, "/api/upgrade/announce", strings.NewReader(`{"target":"abc1234"}`)) + req.Header.Set("X-Hive-Role", "read-write") + rr := httptest.NewRecorder() + s.handleUpgradeAnnounce(rr, req) + if rr.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403", rr.Code) + } + if s.upgradeAnnounce.get() != nil { + t.Fatal("a rejected announce must not be recorded") + } +} + +func TestUpgradeAnnounceMarksProgressAndBroadcasts(t *testing.T) { + s := newTestServer() + ch := make(chan []byte, 4) + s.sseClients[ch] = struct{}{} + s.UpdateStatus(minimalPayload()) + for len(ch) > 0 { // drop the status frame UpdateStatus just published + <-ch + } + + rr := httptest.NewRecorder() + s.handleUpgradeAnnounce(rr, announceOwnerRequest(http.MethodPost, "/api/upgrade/announce", + `{"version":"0123456789abcdef0123456789abcdef01234567","source":"hub","reason":"hub-managed upgrade"}`)) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rr.Code, rr.Body.String()) + } + var resp struct { + OK bool `json:"ok"` + Progress *spoke.UpgradeProgress `json:"upgradeProgress"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if !resp.OK || resp.Progress == nil { + t.Fatalf("resp = %s", rr.Body.String()) + } + if resp.Progress.State != spoke.UpgradeStatePulling || resp.Progress.Phase != spoke.UpgradePhaseAnnounced { + t.Fatalf("state/phase = %s/%s, want pulling/announced", resp.Progress.State, resp.Progress.Phase) + } + if resp.Progress.Target != "0123456" || resp.Progress.Source != spoke.UpgradeSourceHub { + t.Fatalf("target/source = %q/%q", resp.Progress.Target, resp.Progress.Source) + } + + // The same record drives /api/status's upgradeProgress — the component + // the self-upgrade renders through. + p := s.upgradeProgress(s.status, time.Now()) + if p == nil || p.Phase != spoke.UpgradePhaseAnnounced || p.Target != "0123456" { + t.Fatalf("upgradeProgress = %+v", p) + } + + select { + case frame := <-ch: + if !strings.HasPrefix(string(frame), "event: upgrading\n") { + t.Fatalf("frame = %q", frame) + } + var ev upgradeAnnounceEvent + if err := json.Unmarshal([]byte(strings.TrimSpace(strings.TrimPrefix(string(frame), "event: upgrading\ndata: "))), &ev); err != nil { + t.Fatal(err) + } + if ev.Phase != spoke.UpgradePhaseAnnounced || ev.Target != "0123456" { + t.Fatalf("event = %+v", ev) + } + default: + t.Fatal("announce published no SSE frame") + } +} + +func TestAnnounceRestartKeepsAnnouncedTargetAndPublishesRestarting(t *testing.T) { + s := newTestServer() + s.UpdateStatus(minimalPayload()) + now := time.Now() + s.AnnounceUpgrade(spoke.UpgradeAnnounce{Target: "feedfacefeedfacefeedfacefeedfacefeedface", Source: spoke.UpgradeSourceOperator}, now) + + ch := make(chan []byte, 4) + s.sseClients[ch] = struct{}{} + p := s.AnnounceRestart(now.Add(time.Second)) + if p.State != spoke.UpgradeStateRolling || p.Phase != spoke.UpgradePhaseRestarting { + t.Fatalf("state/phase = %s/%s", p.State, p.Phase) + } + if p.Target != "feedfac" || p.Source != spoke.UpgradeSourceOperator { + t.Fatalf("restart lost the announce: %+v", p) + } + if !strings.Contains(p.Detail, "reconnecting") { + t.Fatalf("detail = %q", p.Detail) + } + select { + case frame := <-ch: + if !strings.Contains(string(frame), `"phase":"restarting"`) || !strings.Contains(string(frame), `"processStartedAt"`) { + t.Fatalf("frame = %q", frame) + } + default: + t.Fatal("restart published no SSE frame") + } + // Restart wins over the drain/marker chain in buildUpgradeProgress. + if got := s.upgradeProgress(s.status, now.Add(2*time.Second)); got == nil || got.Phase != spoke.UpgradePhaseRestarting { + t.Fatalf("upgradeProgress = %+v", got) + } +} + +func TestAnnounceRestartFallsBackToHubTarget(t *testing.T) { + s := newTestServer() + s.SetHubUpgradePolicy(&spoke.HeartbeatUpgradePolicy{ArmedTarget: "cafebabecafebabecafebabecafebabecafebabe"}) + p := s.AnnounceRestart(time.Now()) + if p.Target != "cafebab" || p.Source != spoke.UpgradeSourceSignal { + t.Fatalf("progress = %+v", p) + } + + bare := newTestServer() + if got := bare.AnnounceRestart(time.Now()); got.Target != "" || got.Detail != "restarting · reconnecting" { + t.Fatalf("bare restart = %+v", got) + } +} + +func TestUpgradeAnnounceExpiresWithoutAKill(t *testing.T) { + now := time.Now() + st := &upgradeAnnounceState{Target: "abc", At: now} + if liveUpgradeAnnounce(st, now.Add(upgradeAnnounceStaleAfter-time.Minute)) == nil { + t.Fatal("fresh announce dropped") + } + if liveUpgradeAnnounce(st, now.Add(upgradeAnnounceStaleAfter+time.Minute)) != nil { + t.Fatal("stale announce kept — an aborted roll would animate forever") + } + restart := &upgradeAnnounceState{Restarting: true, RestartAt: now} + if liveUpgradeAnnounce(restart, now.Add(24*time.Hour)) == nil { + t.Fatal("a restart record must never expire: the process is exiting") + } +} + +func TestInitializingStatusCarriesStartupPhase(t *testing.T) { + s := newTestServer() + s.status = nil + s.SetStartupPhase("bootStores") + if got := s.StartupPhase(); got != "bootStores" { + t.Fatalf("StartupPhase = %q", got) + } + rr := httptest.NewRecorder() + s.handleStatus(rr, httptest.NewRequest(http.MethodGet, "/api/status", nil)) + var body map[string]any + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["status"] != "initializing" || body["startupPhase"] != "bootStores" { + t.Fatalf("body = %v", body) + } + if label, _ := body["startupPhaseLabel"].(string); label == "" || label == "bootStores" { + t.Fatalf("startupPhaseLabel = %q, want a human label", label) + } + if _, ok := body["startedAt"]; !ok { + t.Fatal("initializing status must carry the process startedAt") + } + + // Once the first status lands the phase is over, whatever was recorded. + s.UpdateStatus(minimalPayload()) + if got := s.StartupPhase(); got != "" { + t.Fatalf("StartupPhase after first status = %q, want empty", got) + } + rr = httptest.NewRecorder() + s.handleVersion(rr, httptest.NewRequest(http.MethodGet, "/api/version", nil)) + if !strings.Contains(rr.Body.String(), `"startedAt"`) || strings.Contains(rr.Body.String(), `"startupPhase"`) { + t.Fatalf("/api/version = %s", rr.Body.String()) + } +} diff --git a/src/pkg/dashboard/upgrade_progress.go b/src/pkg/dashboard/upgrade_progress.go index dfbedf0d7c..7d2706a132 100644 --- a/src/pkg/dashboard/upgrade_progress.go +++ b/src/pkg/dashboard/upgrade_progress.go @@ -22,8 +22,11 @@ func (s *Server) SetUpgradeDrainSource(fn func(now time.Time) *spoke.UpgradeDrai // upgradeProgressInput is what buildUpgradeProgress derives from, gathered // at serve time so the derivation is pure and table-testable. type upgradeProgressInput struct { - Policy *spoke.HeartbeatUpgradePolicy - Drain *spoke.UpgradeDrainReport + Policy *spoke.HeartbeatUpgradePolicy + Drain *spoke.UpgradeDrainReport + // Announce is the announced/restarting roll record (#15788), already + // filtered for staleness by the caller. + Announce *upgradeAnnounceState Marker map[string]any Outcome *upgradeOutcome RunningSHA string @@ -39,7 +42,9 @@ type upgradeProgressInput struct { // last landed outcome — plus the hub's policy (next window, history). It // uses the same state vocabulary as the hub card (#14856). // +// restart announced (SIGTERM) → rolling, phase restarting (#15788) // drain open → draining (countdown, agents in turn) +// roll announced, no kill yet → pulling, phase announced (#15788) // marker, attempts exhausted → missed (last error) // marker, retrying → pulling // outcome landed this boot → done @@ -69,6 +74,10 @@ func buildUpgradeProgress(in upgradeProgressInput) *spoke.UpgradeProgress { } history = spoke.UpgradeHistoryForDisplay(history, upgradedAt) + if a := in.Announce; a != nil && a.Restarting { + return announceProgress(a, in.RunningSHA, nextWindow, now) + } + if d := in.Drain; d != nil { turns := d.Turns if len(turns) == 0 { @@ -91,6 +100,10 @@ func buildUpgradeProgress(in upgradeProgressInput) *spoke.UpgradeProgress { return p } + if a := in.Announce; a != nil { + return announceProgress(a, in.RunningSHA, nextWindow, now) + } + if m := in.Marker; m != nil { target, _ := m["target"].(string) current, _ := m["current"].(string) @@ -203,6 +216,7 @@ func (s *Server) upgradeProgress(status *StatusPayload, now time.Time) *spoke.Up s.versionMu.RUnlock() in := upgradeProgressInput{ Policy: policy, + Announce: liveUpgradeAnnounce(s.upgradeAnnounce.get(), now), Marker: readUpgradeMarker(), Outcome: readUpgradeOutcome(), StartedAt: s.startedAt, diff --git a/src/pkg/dashboard/version_provenance_ui_test.go b/src/pkg/dashboard/version_provenance_ui_test.go index 7d0f79bd60..0aa09b257e 100644 --- a/src/pkg/dashboard/version_provenance_ui_test.go +++ b/src/pkg/dashboard/version_provenance_ui_test.go @@ -27,6 +27,7 @@ func TestVersionProvenanceRendering(t *testing.T) { source.WriteString(jsFunc(t, html, name)) source.WriteByte('\n') } + source.WriteString(jsRollUpgradeFuncs(t, html)) source.WriteString(versionProvenanceAssertions) if out, err := exec.Command(node, "-e", source.String()).CombinedOutput(); err != nil { t.Fatalf("version renderer failed: %v\n%s", err, out) diff --git a/src/pkg/hub/heartbeat.go b/src/pkg/hub/heartbeat.go index 6602b1c29b..730c5b76b8 100644 --- a/src/pkg/hub/heartbeat.go +++ b/src/pkg/hub/heartbeat.go @@ -456,10 +456,14 @@ type HeartbeatResponse struct { PendingGateway *HeartbeatGatewayConfig `json:"pending_gateway,omitempty"` ClusterID string `json:"cluster_id,omitempty"` UpgradePolicy *HeartbeatUpgradePolicy `json:"upgrade_policy,omitempty"` - SigHiveID string `json:"sig_hive_id,omitempty"` - SigSeq int64 `json:"sig_seq,omitempty"` - SigSignedAt int64 `json:"sig_ts,omitempty"` - SigVersion int `json:"sig_v,omitempty"` + // UpgradeAnnounce tells a hub-managed spoke its pod is about to be + // rolled (#15788); the spoke dashboard shows the upgrade animation + // before the kill. Decoded by spoke.HeartbeatResponse.UpgradeAnnounce. + UpgradeAnnounce *spoke.UpgradeAnnounce `json:"upgrade_announce,omitempty"` + SigHiveID string `json:"sig_hive_id,omitempty"` + SigSeq int64 `json:"sig_seq,omitempty"` + SigSignedAt int64 `json:"sig_ts,omitempty"` + SigVersion int `json:"sig_v,omitempty"` // SelfExperimentFlag is authoritative: nil/absent withdraws any prior assignment. SelfExperimentFlag *nous.SelfFlagAssignment `json:"self_experiment_flag,omitempty"` } diff --git a/src/pkg/hub/heartbeat_upgrade_announce.go b/src/pkg/hub/heartbeat_upgrade_announce.go new file mode 100644 index 0000000000..c09b961d1a --- /dev/null +++ b/src/pkg/hub/heartbeat_upgrade_announce.go @@ -0,0 +1,41 @@ +package hub + +import "github.com/hivecommons/hive/pkg/hub/spoke" + +// heartbeatUpgradeAnnounceInput is what decides whether a heartbeat +// response tells the spoke its pod is about to be rolled by the hub +// (#15788). Pure inputs so the rule is testable without a hub. +type heartbeatUpgradeAnnounceInput struct { + // HubManaged: the hub rolls this pod itself (kubectl), so the spoke's + // own self-upgrade machinery never opens its drain latch for it. + HubManaged bool + // LatchOpen/Target mirror the registry entry's Upgrading/UpgradeTarget. + LatchOpen bool + Target string + // Current is the SHA the spoke reported in this beat. + Current string + // SpokeReportedUpgrading: the spoke already knows (self-upgrade), so + // there is nothing to announce. + SpokeReportedUpgrading bool + // Restart: this response carries RestartSpoke. + Restart bool +} + +// heartbeatUpgradeAnnounce returns the announce the hub should attach to a +// heartbeat response, or nil. A hub-managed hive whose latch is open onto a +// target it is not yet running is about to be (or is being) rolled; a +// pending restart is a roll with no new build. Both show the spoke +// dashboard's upgrade animation before the kill rather than after the SSE +// stream drops. +func heartbeatUpgradeAnnounce(in heartbeatUpgradeAnnounceInput) *spoke.UpgradeAnnounce { + if in.Restart { + return &spoke.UpgradeAnnounce{Source: spoke.UpgradeSourceHub, Reason: "hub restart"} + } + if !in.HubManaged || !in.LatchOpen || in.SpokeReportedUpgrading { + return nil + } + if in.Target == "" || (!isReleaseChannel(in.Target) && sameCommit(in.Current, in.Target)) { + return nil + } + return &spoke.UpgradeAnnounce{Target: in.Target, Source: spoke.UpgradeSourceHub, Reason: "hub-managed upgrade"} +} diff --git a/src/pkg/hub/heartbeat_upgrade_announce_test.go b/src/pkg/hub/heartbeat_upgrade_announce_test.go new file mode 100644 index 0000000000..d0ac6e3b3b --- /dev/null +++ b/src/pkg/hub/heartbeat_upgrade_announce_test.go @@ -0,0 +1,41 @@ +package hub + +import ( + "testing" + + "github.com/hivecommons/hive/pkg/hub/spoke" +) + +// #15788: a hub-managed hive whose latch is open onto a build it is not +// running gets told in the heartbeat response that its pod is being rolled, +// so its dashboard animates the roll before the SSE stream drops. +func TestHeartbeatUpgradeAnnounce(t *testing.T) { + const target = "0123456789abcdef0123456789abcdef01234567" + cases := []struct { + name string + in heartbeatUpgradeAnnounceInput + want *spoke.UpgradeAnnounce + }{ + {"hub-managed open latch", heartbeatUpgradeAnnounceInput{HubManaged: true, LatchOpen: true, Target: target, Current: "deadbeef"}, + &spoke.UpgradeAnnounce{Target: target, Source: spoke.UpgradeSourceHub, Reason: "hub-managed upgrade"}}, + {"already on target", heartbeatUpgradeAnnounceInput{HubManaged: true, LatchOpen: true, Target: target, Current: "0123456"}, nil}, + {"channel target announces", heartbeatUpgradeAnnounceInput{HubManaged: true, LatchOpen: true, Target: "stable", Current: "deadbeef"}, + &spoke.UpgradeAnnounce{Target: "stable", Source: spoke.UpgradeSourceHub, Reason: "hub-managed upgrade"}}, + {"spoke-managed: it drives its own drain", heartbeatUpgradeAnnounceInput{HubManaged: false, LatchOpen: true, Target: target, Current: "deadbeef"}, nil}, + {"spoke already reports upgrading", heartbeatUpgradeAnnounceInput{HubManaged: true, LatchOpen: true, Target: target, Current: "deadbeef", SpokeReportedUpgrading: true}, nil}, + {"latch closed", heartbeatUpgradeAnnounceInput{HubManaged: true, Target: target, Current: "deadbeef"}, nil}, + {"restart announces without a target", heartbeatUpgradeAnnounceInput{Restart: true}, + &spoke.UpgradeAnnounce{Source: spoke.UpgradeSourceHub, Reason: "hub restart"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := heartbeatUpgradeAnnounce(tc.in) + if (got == nil) != (tc.want == nil) { + t.Fatalf("got %+v, want %+v", got, tc.want) + } + if got != nil && *got != *tc.want { + t.Fatalf("got %+v, want %+v", *got, *tc.want) + } + }) + } +} diff --git a/src/pkg/hub/server.go b/src/pkg/hub/server.go index 33926d44b5..aea97caa23 100644 --- a/src/pkg/hub/server.go +++ b/src/pkg/hub/server.go @@ -3270,6 +3270,17 @@ func (s *HubServer) handleHeartbeat(w http.ResponseWriter, r *http.Request) { resp.RestartSpoke = true s.logger.Info("heartbeat: delivering spoke restart", "hive_id", payload.HiveID, "reporter", payload.Reporter) } + // Intent before the kill (#15788): a hub-managed hive learns here that + // its pod is being rolled, so its dashboard shows the upgrade animation + // with the target instead of a bare "reconnecting" once the pod dies. + resp.UpgradeAnnounce = heartbeatUpgradeAnnounce(heartbeatUpgradeAnnounceInput{ + HubManaged: saasHive != nil && !spokeManaged, + LatchOpen: entry.Upgrading, + Target: entry.UpgradeTarget, + Current: payload.GitHash, + SpokeReportedUpgrading: payload.Upgrading, + Restart: resp.RestartSpoke, + }) if ghCfg := s.pendingAppIdentityForHeartbeat(&payload); ghCfg != nil { resp.GitHubAppConfig = ghCfg diff --git a/src/pkg/hub/spoke/heartbeat.go b/src/pkg/hub/spoke/heartbeat.go index 9a019dc83e..2fff3006f3 100644 --- a/src/pkg/hub/spoke/heartbeat.go +++ b/src/pkg/hub/spoke/heartbeat.go @@ -1378,6 +1378,7 @@ func StartHeartbeat(ctx context.Context, hubURL string, collect StatusCollector, var onBreaker BreakerCallback var freshCollect FreshStatusCollector var onUpgradePolicy UpgradePolicyCallback + var onUpgradeAnnounce UpgradeAnnounceCallback for _, cb := range callbacks { switch fn := cb.(type) { case UpgradeCallback: @@ -1408,6 +1409,8 @@ func StartHeartbeat(ctx context.Context, hubURL string, collect StatusCollector, freshCollect = fn case UpgradePolicyCallback: onUpgradePolicy = fn + case UpgradeAnnounceCallback: + onUpgradeAnnounce = fn } } @@ -1463,6 +1466,9 @@ func StartHeartbeat(ctx context.Context, hubURL string, collect StatusCollector, } // Descriptive only (#7262): the hub's upgrade posture for this spoke, // rendered by the dashboard. nil means the hub does not manage us. + if resp.UpgradeAnnounce != nil && onUpgradeAnnounce != nil { + onUpgradeAnnounce(resp.UpgradeAnnounce) + } if resp.UpgradePolicy != nil && onUpgradePolicy != nil { onUpgradePolicy(resp.UpgradePolicy) } @@ -2833,6 +2839,12 @@ type HeartbeatResponse struct { // on every beat for any hive the hub has an upgrade opinion about; nil // means "the hub does not manage this hive's upgrades". UpgradePolicy *HeartbeatUpgradePolicy `json:"upgrade_policy,omitempty"` + // UpgradeAnnounce rides on every beat while the hub holds an open + // upgrade latch for a hub-managed hive it is about to roll (or has + // rolled) itself, so the spoke dashboard shows the upgrade animation + // before the kill instead of a bare "reconnecting" (#15788). Absent on + // the self-upgrade path, where UpgradeTo already says it. + UpgradeAnnounce *UpgradeAnnounce `json:"upgrade_announce,omitempty"` // SigHiveID / SigSeq / SigSignedAt are authenticated by the detached // hub->spoke heartbeat response signature. They bind the response to this // hive and a monotonic sequence so signed responses cannot be replayed @@ -2952,6 +2964,10 @@ const ( // UpgradePolicy. nil is never delivered. type UpgradePolicyCallback func(p *HeartbeatUpgradePolicy) +// UpgradeAnnounceCallback is called on every beat whose response carries an +// UpgradeAnnounce (#15788). nil is never delivered. +type UpgradeAnnounceCallback func(a *UpgradeAnnounce) + // taskPushInterval is how often the spoke pushes task status to the hub. A var // (not a const) so tests can drive a single push quickly; production keeps the // default. diff --git a/src/pkg/hub/spoke/heartbeat_reconnect_upgrade_coverage_test.go b/src/pkg/hub/spoke/heartbeat_reconnect_upgrade_coverage_test.go index 4203b53b6a..a5341b0fd9 100644 --- a/src/pkg/hub/spoke/heartbeat_reconnect_upgrade_coverage_test.go +++ b/src/pkg/hub/spoke/heartbeat_reconnect_upgrade_coverage_test.go @@ -56,6 +56,7 @@ func TestStartHeartbeatProcessesFullResponse(t *testing.T) { PendingGateway: &HeartbeatGatewayConfig{Name: "gw", Key: "k"}, ClusterID: "vllm-d", RestartSpoke: true, + UpgradeAnnounce: &UpgradeAnnounce{Target: "deadbeef", Source: UpgradeSourceHub, Reason: "hub-managed upgrade"}, } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if beats.Add(1) == 1 { @@ -79,6 +80,7 @@ func TestStartHeartbeatProcessesFullResponse(t *testing.T) { gotGateway *HeartbeatGatewayConfig gotClusterID string gotRestart bool + gotAnnounce *UpgradeAnnounce gotSwitchBranch string ) fired := make(chan struct{}, 1) @@ -130,6 +132,11 @@ func TestStartHeartbeatProcessesFullResponse(t *testing.T) { gotSwitchBranch = tag mu.Unlock() }) + onAnnounce := UpgradeAnnounceCallback(func(a *UpgradeAnnounce) { + mu.Lock() + defer mu.Unlock() + gotAnnounce = a + }) onRestart := RestartSpokeCallback(func() { mu.Lock() gotRestart = true @@ -148,7 +155,7 @@ func TestStartHeartbeatProcessesFullResponse(t *testing.T) { go func() { defer close(done) StartHeartbeat(ctx, srv.URL, collect, 50*time.Millisecond, nil2Logger(), - onUpgrade, onApp, onBanner, onVis, onUsers, onProject, onGateway, onClusterID, onSwitch, onRestart) + onUpgrade, onApp, onBanner, onVis, onUsers, onProject, onGateway, onClusterID, onSwitch, onRestart, onAnnounce) }() // RestartSpoke is the last dispatch in processHeartbeatResponse, so once it @@ -200,6 +207,9 @@ func TestStartHeartbeatProcessesFullResponse(t *testing.T) { if !gotRestart { t.Error("restart-spoke callback did not record") } + if gotAnnounce == nil || gotAnnounce.Target != "deadbeef" || gotAnnounce.Source != UpgradeSourceHub { + t.Errorf("upgrade-announce callback got %+v, want hub announce for deadbeef (#15788)", gotAnnounce) + } } // TestStartHeartbeatSwitchToTagWins verifies the upgrade-target negotiation: a diff --git a/src/pkg/hub/spoke/upgrade_progress.go b/src/pkg/hub/spoke/upgrade_progress.go index fc0f04535b..ca3323cbdc 100644 --- a/src/pkg/hub/spoke/upgrade_progress.go +++ b/src/pkg/hub/spoke/upgrade_progress.go @@ -40,6 +40,29 @@ const ( UpgradeStateMissed = "missed" ) +// Upgrade phases qualify an in-flight state for rolls the spoke did not run +// itself (hivecommons/hive#15788): a hub-managed kubectl roll, an operator's +// `kubectl rollout restart`, a plain SIGTERM. Both render through the same +// spoke/hub state machine as a self-upgrade. +const ( + // UpgradePhaseAnnounced — someone said a roll is coming (POST + // /api/upgrade/announce or the heartbeat's upgrade_announce); the pod + // has not been killed yet. + UpgradePhaseAnnounced = "announced" + // UpgradePhaseRestarting — the process received SIGTERM and is exiting; + // the dashboard should expect the stream to drop and reconnect. + UpgradePhaseRestarting = "restarting" +) + +// Upgrade announce sources recorded in UpgradeProgress.Source. +const ( + UpgradeSourceHub = "hub" + UpgradeSourceOperator = "operator" + // UpgradeSourceSignal — nobody announced; the SIGTERM itself is the + // first the spoke heard of the roll. + UpgradeSourceSignal = "signal" +) + // Upgrade attempt outcomes recorded in UpgradeAttempt.Outcome. const ( UpgradeOutcomeDone = "done" @@ -109,6 +132,24 @@ type UpgradeProgress struct { Detail string `json:"detail"` // EndedAt is when a done/missed attempt closed (RFC3339 UTC). EndedAt string `json:"endedAt,omitempty"` + // Phase qualifies an in-flight roll the spoke did not run itself: + // UpgradePhaseAnnounced or UpgradePhaseRestarting (#15788). Empty for + // the self-upgrade path, whose State alone says enough. + Phase string `json:"phase,omitempty"` + // Source says who announced the roll Phase describes: hub, operator or + // signal. Empty when Phase is. + Source string `json:"source,omitempty"` +} + +// UpgradeAnnounce is a roll intent delivered to a spoke before the kill — +// by the hub in the heartbeat response or by an operator through POST +// /api/upgrade/announce (#15788). Target may be a commit SHA or a version +// tag; empty means "a restart, onto whatever the Deployment now says". +type UpgradeAnnounce struct { + Target string `json:"target,omitempty"` + // Source is UpgradeSourceHub or UpgradeSourceOperator. + Source string `json:"source,omitempty"` + Reason string `json:"reason,omitempty"` } // InFlight reports whether the state describes an attempt still under way.