From 348dce6d6f6594108ce95faf3b2f6616f2098162 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 12:19:14 -0400 Subject: [PATCH 1/5] =?UTF-8?q?=E2=9C=A8=20Activity=20monitor:=20decision?= =?UTF-8?q?=20badge=20shows=20what=20you=20chose=20and=20what=20hive=20did?= =?UTF-8?q?=20next?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner (2026-10-28): "I need a way to see if I selected an action on an item so I can keep track of whether or not I addressed it. Hovering over the indicator should show me what action I requested." - Server-side operator-action ledger (/data/operator-actions.json) recorded around the hold / decision / decide-delegated / send-to-human / accept-triage routes: {action, actor, at, note, target, outcome, detail, head_sha, stage}; Let hive decide settles when the job ends. - Tracker rows and linked PRs carry last_operator_action (derived state waiting|addressed|stuck|pending|failed, stuck window, followed[] hops) + operator_action_count; new GET /api/repos/{o}/{r}/items/{n} detail. - ✓ badge in the cap cell (green / amber when still at the same stage past the window / red failed / dotted while deciding) with an in-app, keyboard-reachable tooltip in plain words: what it is waiting on → what you chose, when → what the hive did next. Decisions filter: Awaiting my decision / I acted / Acted, still stuck. - Go + node tests, dashboard-sections.md legend, api-reference.md, changelog fragment. Requested by @clubanderson. Signed-off-by: Andrew Anderson --- changelog.d/added-operator-action-badge.md | 1 + src/docs/api-reference.md | 255 +++---- src/docs/dashboard-sections.md | 5 + src/pkg/dashboard/api.go | 13 +- .../api_repo_item_decide_delegated.go | 6 + src/pkg/dashboard/api_repo_item_decision.go | 4 +- src/pkg/dashboard/label_facets.test.js | 2 +- src/pkg/dashboard/operator_actions.go | 635 ++++++++++++++++++ src/pkg/dashboard/operator_actions_test.go | 251 +++++++ src/pkg/dashboard/server.go | 4 + src/pkg/dashboard/stage_tracker.go | 14 +- src/pkg/dashboard/stage_tracker_acted.test.js | 163 +++++ src/pkg/dashboard/static/index.html | 186 ++++- 13 files changed, 1399 insertions(+), 140 deletions(-) create mode 100644 changelog.d/added-operator-action-badge.md create mode 100644 src/pkg/dashboard/operator_actions.go create mode 100644 src/pkg/dashboard/operator_actions_test.go create mode 100644 src/pkg/dashboard/stage_tracker_acted.test.js diff --git a/changelog.d/added-operator-action-badge.md b/changelog.d/added-operator-action-badge.md new file mode 100644 index 0000000000..4256122686 --- /dev/null +++ b/changelog.d/added-operator-action-badge.md @@ -0,0 +1 @@ +- Activity monitor: a ✓ decision badge on every row you acted on from the dashboard — green once recorded, amber when the item is still at the same stage past the stuck window, red when the action failed — with a plain-words tooltip (what it is waiting on → what you chose, when → what the hive did next) and a **Decisions** filter (Awaiting my decision / I acted / Acted, still stuck). Actions are kept in a server-side ledger (`/data/operator-actions.json`), surface as `last_operator_action` on tracker rows and via `GET /api/repos/{owner}/{repo}/items/{number}`. Requested by @clubanderson. diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 5ce6900014..723201fc54 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -169,17 +169,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:304` | | `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:305` | | `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:308` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:351` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:352` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:353` | -| `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:343` | -| `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:344` | -| `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:345` | -| `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:346` | -| `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:347` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:348` | -| `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:349` | -| `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:517` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:354` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:355` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:356` | +| `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:346` | +| `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:347` | +| `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:348` | +| `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:349` | +| `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:350` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:351` | +| `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:352` | +| `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:520` | | `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:212` | | `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:213` | @@ -188,8 +188,8 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:222` | | `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:225` | | `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:226` | -| `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:513` | -| `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:514` | +| `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:516` | +| `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:517` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:229` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:232` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:238` | @@ -233,15 +233,15 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:169` | | `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:170` | | `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:231` | -| `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:492` | -| `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:495` | -| `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:496` | -| `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:500` | +| `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:495` | +| `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:498` | +| `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:499` | +| `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:503` | | `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:504` | -| `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:505` | -| `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:507` | -| `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:510` | +| `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:507` | +| `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:508` | +| `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:510` | +| `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:513` | | `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:310` | | `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:311` | | `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:312` | @@ -283,14 +283,15 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `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:332`, `pkg/dashboard/api_repo_hold.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:333`, `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", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. 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 only (409 otherwise). 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. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:334`, `pkg/dashboard/api_repo_item_decision.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. | `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:336`, `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", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. 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 only (409 otherwise). 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. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:337`, `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}, notes, error}`); 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}/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:524`, `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:338`, `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:339` | -| `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:340` | -| `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:342`, `pkg/dashboard/api_hive_advice.go` | +| `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:527`, `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:341`, `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:342` | +| `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:343` | +| `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:345`, `pkg/dashboard/api_hive_advice.go` | ## Cost, tokens, telemetry @@ -314,37 +315,37 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | 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:358` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:359` | -| `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:367` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:360` | -| `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:361` | -| `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:362` | -| `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:363` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:368` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:369` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:370` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:371` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:372` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:373` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:374` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:375` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:381` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:382` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:383` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:384` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:385` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:386` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:387` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:388` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:389` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:390` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:391` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:392` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:393` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:394` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:395` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:396` | +| `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:361` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:362` | +| `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:370` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:363` | +| `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:364` | +| `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:365` | +| `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:366` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:371` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:372` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:373` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:374` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:375` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:376` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:377` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:378` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:384` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:385` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:386` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:387` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:388` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:389` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:390` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:391` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:392` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:393` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:394` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:395` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:396` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:397` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:398` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:399` | | `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` | @@ -354,19 +355,19 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `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:406` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:407` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:408` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:409` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:410` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:411` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:412` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:413` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:414` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:415` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:416` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:379` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:380` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:409` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:410` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:411` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:412` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:413` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:415` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:416` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:418` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:419` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:382` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:383` | | `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` | @@ -478,67 +479,67 @@ always resolved server-side from the validated token. | 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:450` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:451` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:452` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:453` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:454` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:455` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:456` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:457` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:458` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:459` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:460` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:461` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:462` | -| `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:463` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:464` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:465` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:466` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:467` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:468` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:469` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:470` | -| `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:471` | -| `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:472` | -| `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:473` | -| `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:474` | +| `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:453` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:454` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:455` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:456` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:457` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:458` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:459` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:460` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:461` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:462` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:463` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:464` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:465` | +| `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:466` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:467` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:468` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:469` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:470` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:471` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:472` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:473` | +| `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:474` | +| `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:475` | +| `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:476` | +| `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:477` | ## Inception | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:421` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:422` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:423` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:424` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:425` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:426` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:427` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:428` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:429` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:430` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:431` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:432` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:433` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:434` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:424` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:425` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:426` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:427` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:428` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:429` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:430` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:431` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:432` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:433` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:434` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:435` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:436` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:437` | ## Beads | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:476` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:477` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:478` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:479` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:480` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:479` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:480` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:481` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:482` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:483` | ## Dashboard miscellaneous | 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:58` | -| `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:487` | +| `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:490` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:61` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:62` | | `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:63` | @@ -552,11 +553,11 @@ always resolved server-side from the validated token. | `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:254` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:439` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:442` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:443` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:445` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:446` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:442` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:445` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:446` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:448` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:449` | | `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` | @@ -572,11 +573,11 @@ always resolved server-side from the validated token. | `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:184` | | `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`, (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), 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. 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:185` | | `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:186` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:356` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:418` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:419` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:448` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:482` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:359` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:421` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:422` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:451` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:485` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:248` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:249` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:250` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 3b6a0acbe1..38d8711b96 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -678,6 +678,7 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p | `sentinel` (the trusted-author notice and the real `sentinel-alert` alike) | merge gate | PR at stage/080 or later; `sentinel_alert` itself stays truthful in the payload for the lane word and the Decide… preface | | `needs human` (`needs-human` label) | merge gate | PR at stage/080 or later; always on an issue at its own stage | | `needs human decision` (`needs-decision` labels on another stage) | merge gate | PR at stage/080 or later; always on an issue at its own stage | +| ✓ decision badge (`last_operator_action`) | before the pills; green / amber (still at the same stage past the stuck window) / red (failed) / dotted … (hive deciding) | always, once a row action was submitted from the dashboard; tooltip tells what you chose, when, and what the hive did next | **Adoption pill (072).** A nudged `author/clanker` pull request at `stage/072-returned-to-contributor` carries `adoption{author, due, blocked_by, since, nudges, author_online, author_registered, author_last_seen, author_maintainer, policy, action, text}` — the nudge count and first-nudge time from the stage record, the author's live hub presence (the same lookup the contributor-offline adoption itself consults), and, when the adoption engine judged adoption due and held it, why (`blocked_by: author-is-maintainer`). The row's caption and an amber pill say it in plain words instead of a bare "Returned to contributor": `waiting on @hanthor (maintainer, offline 26h) — adopt?` under `governor.labels.stage.adoption.maintainer_policy: ask`, `waiting on @zoe (offline 40m, 2 nudges)` while the default `adopt` policy's clock runs, `… — not adopted: maintainer_policy is never` under `never` ([hivecommons/hive#14524](https://github.com/hivecommons/hive/pull/14524): the PR sat 26h at 072 with its author's hive gone and nothing on screen saying why). When `action` is `decide:adopt` the row also carries `decision_needed` (question "@hanthor maintains this repository and has been offline for 26h; adopt the PR?", `blocker_reason: adoption:author-is-maintainer`, options Adopt then Hold/Release), so the lit 072 chevron and the `adopt?` pill open the Needs-human popover, and the row menu and the selection bar offer **Adopt (hive takes over)** — same action-id vocabulary as the other `decide:*` entries — which, after an in-app confirm, POSTs `{"decision":"adopt"}` to the item's decision endpoint: the hive posts an attributed note, sets `adoption/supersede` (the owner-delegate's request label) and the next sweep adopts the head on the existing adopt/supersede path; the toast reads `adoption-queued`. Write access required; the action is absent when nothing is the owner's to decide. @@ -689,6 +690,10 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Row gutter.** Every issue and PR row (never a column or repo-group header) carries a left gutter with a select checkbox and a ⋯ actions button that is always present and always visible: dimmed at rest (`--ham-tool-rest-opacity`), at full emphasis on the row under the pointer or holding focus, on a selected row, and on every row while anything is selected or the context menu is open — the only animation is the hover fade (`--ham-tool-fade-ms`, ≤ 120 ms), and nothing about it depends on scrolling, row position or which rows the live refresh re-created. +**Did I act on this? (the decision badge).** Owner (2026-10-28): "I need a way to see if I selected an action on an item so I can keep track of whether or not I addressed it. Hovering over the indicator should show me what action I requested." Every row action submitted from the dashboard — Approve, Give direction, Close as superseded, Close as won't-fix, Let hive decide, Hold / Release hold, Accept triage, Mark needs-human — is written to a server-side ledger (`/data/operator-actions.json`, `operator_actions.go`; newest 20 per item) as `{action, actor, at, note, target, outcome, detail, head_sha, stage}`, so the record survives reloads and shows in every browser. The tracker row carries the newest one as `last_operator_action` (+ `operator_action_count`) and `GET /api/repos/{owner}/{repo}/items/{number}` returns the full list. The row then wears a small **✓ badge** in the cap cell, before the state pills (`.ham-acted`): green once an action is recorded; **amber** when the item is still at the same stage past the stuck window (`HIVE_OPERATOR_ACTION_STUCK_AFTER`, default 30 min — "acted, but nothing happened"); red when the action itself failed; a dotted `…` while *Let hive decide* is still running. The in-flight spinner on the chevron is a different cue: that is the request still on the wire; the badge appears once the server has recorded it. Hover or focus (the badge is in the Tab order) opens an in-app tooltip — never a native `title` — written in plain words, no stage codes, in the order every cue on the row uses: **what it is waiting on → what you chose → what the hive did next**. E.g. `At Merge gate — waiting on CI.` / `You chose Approve · 15:55 (5 min ago) · done — released to the hive.` / `Then the hive moved it to Merged — a reviewer approved it · 1 min ago.` Once the item moves on, the badge stays and the first line reads `Addressed — now at `; while stuck it reads `Still at 42 min after you asked — hive says: `. Another operator's action is named (`@someone chose …`); your note and "N earlier actions on this item" follow. The **Decisions** select in the toolbar narrows the list: *Awaiting my decision* (parked on a person, no action recorded yet, or the last one failed), *I acted* (any badge), *Acted, still stuck* (amber badges only). + +**Legend — the three cues a row may carry** (shared with the in-flight and needs-human work landing beside this): the *state pill* says where the item is and what it is waiting on (`hold`, `needs human`, `stage ↓` …); the *working* spin on the lit chevron says the hive is doing something in that stage right now (a still chevron = waiting on something, its tooltip says what); the *decision badge* (✓) says a person acted here and what followed. Plain words throughout — working / waiting on X / set back by Y / merged — nothing else blinks. + **Row actions (right-click, ⋯, Shift+F10).** Right-clicking a row — or a nested PR sub-row — opens an in-app context menu of the actions that fit that item's current state; the ⋯ button in the row's left gutter opens the same menu for pointer-free use, and so do **Shift+F10** and the context-menu key while the row or anything in it has focus (every row is a tab stop). The menu is positioned at the pointer, clamped to the viewport, uses `menu` / `menuitem` roles, moves focus with ↑ ↓ Home End, opens the *Decide…* group with → and closes it with ←, and closes on Esc, Tab, click-away, scroll or resize, returning focus to the row. Shift+right-click keeps the browser's own menu. Entries, each shown only when it applies: **Decide…** on a row waiting on a person — a PR wearing the *Needs human decision* pill at 085 on the Merge gate column (the primary case: e.g. two competing `dibs` PRs), an issue row whose nested PR is parked there (the menu reads *Decide PR #458…* and acts on that PR, since the issue's own stage is only mirrored from it), or an issue parked at 045. The first entry is always *Let hive decide* (see [Let hive decide](#let-hive-decide) below): the hive decides as the owner's delegate and records it the way a person's decision is recorded. For a PR: *Approve (/lgtm + /approve)* posts those two commands as comments attributed to you and records your approval against the PR's current head as the human answer the row was parked for — a `requires_human` / decision-requested reviewer verdict, the hive's own `needs-human` park (a supersession question, say), the `sentinel-alert` label and the evidence bundle's sentinel findings are all released by it (the response's `released` lists what was: `approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`), the stage engine re-derives the stage on the spot and the tracker cache is dropped, so the row leaves *Needs human decision* for 080 *Awaiting merge admission* on the next read; the merge gate (and the auto-merge lanes, which honour the recorded approval on that head exactly as a trusted merger's GitHub Approve review) takes it from there; the dashboard never reviews as you and never merges. A new head carries no answer: pushing to the PR re-asks. The delegated *Let hive decide* path still posts the comments only — it recommends and never clears a sentinel alert — *Close as superseded by…* (a picker listing the other open PRs in the repo, or type `#458` / `owner/repo#458` / a URL; then an optional comment, then the sweep's labelled close), *Won't fix…* (a comment naming you, then a not-planned close) and *Give direction…* (your text is recorded as `/hive decision ` against the head, so the author agent pushes a new head; only on PRs the hive opened). For an issue: *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. Entries you may not use are greyed with the reason in their tooltip, never hidden. Confirmation and free-text input use the dashboard's own dialogs — no browser prompts. Every action is an existing audited dashboard endpoint (the decision endpoint is `POST /api/repos/{owner}/{repo}/items/{number}/decision` and triage acceptance is `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage`, see [api-reference.md](api-reference.md)); none of them bypasses the hive's governance or merges anything. **What a row tells you without a click (`tracker-cues`).** The owner's framing (2026-10-28): "Hive is doing the right things mostly; we now need to keep the user informed of it — like a video game they can watch and see what happens easily." Every row therefore reads, in this order, *where it is → whether work is happening on it → what it waits on → what just happened*, with at most three cue types drawing the eye and nothing else blinking. **Where it is** is the lit chevron (the state pill). **Working** — the chevron's icon turns slowly and the pill pulses only while a hive agent is actually on the item right now (the status payload's `agents[].lastAction` for the current round, matched to the row or to the PR shown on its row); its tooltip then leads with *Working now: scout commented · 2m ago —* before the stage words. A still chevron means **waiting**; its tooltip already says where it stands and whose move it is (*Needs decision — … · Next move: human*). **Acting** — from the moment you choose a row action the affected row (and the nested PR sub-row when the action targets it) draws faint stripes over its lit chevron and an *Approving… / Hive is deciding… / Holding…* caption with a small spinner; it clears when the tracker reports the target in a new state, at once on a no-op or an error, and never later than three minutes. **Event line** — one short plain sentence under the strip about the latest thing that happened to the row, from the difference between two tracker payloads (the poll / SSE refetch the tracker already makes; no extra requests): *Hive: moved to CI / Review · 12s ago*, *Hive: fell back to Claimed — a reviewer requested changes*, *Hive: waiting on a person*, *Hive: hold released*, *You: approved*. It lives two minutes, dims for its last third, and a row carries only its latest line. **Set back** — a row wearing `regressed` colours the line's lead red. **Merged** — see *Merged today* below. The CSS class names are shared so the sibling Activity Monitor PRs (needs-human options, decision trail) compose on them: `cue-working`, `cue-acting`, `cue-event`, `cue-setback`, `cue-merged`, `cue-decision` (badge, sibling PR), `cue-spin` (the one spin keyframe), `cue-token` / `ham-merged-count` (the merge counter); the colour tokens `--cue-state`, `--cue-work`, `--cue-decision` on `.ham-row` are declared in the *Cue tokens* paragraph under [Let hive decide](#let-hive-decide) below. Legend, in the operator's words: **working** (icon turns), **waiting on X** (still; tooltip names X), **set back by Y** (red lead on the event line), **merged** (✓ glows, token rises to the count). Under `prefers-reduced-motion: reduce` every cue animation stops; the words stay. diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index d75f93729f..a3b9059f37 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -330,9 +330,12 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("POST /api/repos/auto-merge", s.handleRepoAutoMerge) s.mux.HandleFunc("GET /api/repos/pauses", s.handleRepoPauses) s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/hold-permission", s.handleRepoHoldPermission) - s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/hold", s.handleRepoItemHold) - s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decision", s.handleRepoItemDecision) - s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.handleRepoItemDecideDelegated) + // Owner row actions are wrapped so the ledger behind the activity + // monitor's ✓ badge remembers them (operator_actions.go). + s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}", s.handleRepoItemDetail) + s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/hold", s.recordOperatorAction(s.handleRepoItemHold)) + s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decision", s.recordOperatorAction(s.handleRepoItemDecision)) + s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.recordOperatorAction(s.handleRepoItemDecideDelegated)) s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.handleRepoItemDecideDelegatedStatus) s.mux.HandleFunc("GET /api/acmm/evaluation", s.handleACMMEvaluation) @@ -498,7 +501,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // review stage (unreviewed … approved) with reviewers, severity counts, // loop counter and next action. Read-only; paged like /api/review/queue. s.mux.HandleFunc("GET /api/review/pipeline", s.handleReviewPipeline) - s.mux.HandleFunc("POST /api/review/pipeline/{owner}/{repo}/{number}/send-to-human", s.handleReviewPipelineSendToHuman) + s.mux.HandleFunc("POST /api/review/pipeline/{owner}/{repo}/{number}/send-to-human", s.recordOperatorAction(s.handleReviewPipelineSendToHuman)) // Review evidence (#11061): the per-PR evidence bundle as sealed on disk, // or zipped with the artifacts it references; owner/merger only. s.mux.HandleFunc("GET /api/review/evidence", s.handleReviewEvidence) @@ -521,7 +524,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // Per-agent Variables tab (#11458, api_variables.go). s.registerAgentVariableRoutes() // Activity monitor row menu: Accept triage (api_repo_item_accept_triage.go). - s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/accept-triage", s.handleRepoItemAcceptTriage) + s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/accept-triage", s.recordOperatorAction(s.handleRepoItemAcceptTriage)) } var ( diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index ec83d5d9e2..fce0c4a9d1 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -251,6 +251,9 @@ func (s *Server) runDelegatedDecision(ctx context.Context, key, repoFull string, j.Status = delegatedJobStatusFailed j.Error = err.Error() }) + if done, ok := s.delegatedJobs.get(key); ok { + s.settleOperatorAction(repoFull, number, &done) + } s.audit.LogRecord(user, auditRepoItemDecisionDelegated+"_failed", auditDetail("repo", repoFull, "number", strconv.Itoa(number), "error", err.Error()), "", repoFull, number) return } @@ -291,6 +294,9 @@ func (s *Server) runDelegatedDecision(ctx context.Context, key, repoFull string, } j.Status = delegatedJobStatusDone }) + if done, ok := s.delegatedJobs.get(key); ok { + s.settleOperatorAction(repoFull, number, &done) + } kinds := make([]string, 0, len(d.Actions)) for _, a := range d.Actions { kinds = append(kinds, string(a.Kind)) diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 04bc21d59f..880a81f19b 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -144,6 +144,8 @@ type repoItemDecisionResponse struct { Stage string `json:"stage,omitempty"` // Result is the shared row-action outcome for the dashboard's toast. Result *RowActionResult `json:"result,omitempty"` + // Head is the PR head an approve / direction was recorded against. + Head string `json:"head,omitempty"` } // repoItemDecisionResult reads a recorded human decision into the shared @@ -415,7 +417,7 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW // The row's park was just answered: serve the re-derived stage on the // next tracker read instead of the cached 085. s.invalidateStageTrackerForWebhook() - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", "", released)}) } diff --git a/src/pkg/dashboard/label_facets.test.js b/src/pkg/dashboard/label_facets.test.js index efb405d033..37e0ab77ae 100644 --- a/src/pkg/dashboard/label_facets.test.js +++ b/src/pkg/dashboard/label_facets.test.js @@ -30,7 +30,7 @@ const fnSrc = name => { }; const src = [ constLine('STAGE_TRACKER_PAGE_SIZES'), constLine('STAGE_TRACKER_DEFAULT_PAGE_SIZE'), constLine('STAGE_TRACKER_LABEL_CHIP_LIMIT'), - constLine('STAGE_TRACKER_AGE_MS'), constLine('STAGE_TRACKER_LABEL_FAMILIES'), constLine('STAGE_TRACKER_SORTS'), + constLine('STAGE_TRACKER_AGE_MS'), constLine('STAGE_TRACKER_LABEL_FAMILIES'), constLine('STAGE_TRACKER_SORTS'), constLine('STAGE_TRACKER_ACTED_FILTERS'), constLine('STAGE_TRACKER_NEEDS_HUMAN_STAGES'), constLine('STAGE_TRACKER_NEEDS_HUMAN_AUTHOR_STAGES'), constLine('STAGE_TRACKER_NEEDS_HUMAN_MODS'), fnSrc('stageTrackerDefaultFilter'), fnSrc('stageTrackerNormalizeFilter'), fnSrc('stageTrackerLabelFamily'), pick('label facet helpers begin', 'label facet helpers end'), diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go new file mode 100644 index 0000000000..369669b82d --- /dev/null +++ b/src/pkg/dashboard/operator_actions.go @@ -0,0 +1,635 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// Operator action ledger (hivecommons/hive: "I need a way to see if I +// selected an action on an item so I can keep track of whether or not I +// addressed it"). Every owner row action the activity monitor submits — +// approve, give-direction, close-superseded, wontfix, let-hive-decide, +// hold / release, accept-triage, mark-needs-human — is appended here on the +// server, keyed by repo#number, so the ✓ badge survives reloads and shows in +// every browser. The record is written by wrapping the existing endpoints +// (recordOperatorAction): it never changes what they do, only remembers +// that they were asked and what they answered. The stage tracker derives +// the row's `last_operator_action` from it (stageTrackerOperatorAction), +// and GET /api/repos/{owner}/{repo}/items/{number} lists the whole history. + +const ( + // Canonical action names (the dashboard's menu ids map onto these). + operatorActionApprove = "approve" + operatorActionGiveDirection = "give-direction" + operatorActionCloseSuperseded = "close-superseded" + operatorActionWontFix = "wontfix" + operatorActionLetHiveDecide = "let-hive-decide" + operatorActionHold = "hold" + operatorActionRelease = "release" + operatorActionAcceptTriage = "accept-triage" + operatorActionMarkNeedsHuman = "mark-needs-human" + + // Stored outcomes: what the endpoint answered when the action was + // submitted. `pending` is a delegated decision still running; the job's + // end settles it (settleOperatorAction). + operatorActionOutcomePending = "pending" + operatorActionOutcomeApplied = "applied" + operatorActionOutcomeNoOp = "no-op" + operatorActionOutcomeFailed = "failed" + // Derived only: a failed / no-op action whose item moved stage anyway. + operatorActionOutcomeSuperseded = "superseded-by-state-change" + + // Derived row states (StageTrackerOperatorAction.State). + operatorActionStateWaiting = "waiting" + operatorActionStateAddressed = "addressed" + operatorActionStateStuck = "stuck" + operatorActionStateFailed = "failed" + operatorActionStatePending = "pending" + + operatorActionsMaxPerItem = 20 + operatorActionNoteMax = 280 + operatorActionBodyMax = 64 << 10 + operatorActionStuckAfterDefault = 30 * time.Minute + // HIVE_OPERATOR_ACTION_STUCK_AFTER (Go duration) overrides how long a + // recorded action may sit at the same stage before the badge turns amber. + operatorActionStuckAfterEnv = "HIVE_OPERATOR_ACTION_STUCK_AFTER" +) + +// operatorActionsPath is where the ledger persists; tests point it at a +// temp file (or "" for memory only). +var operatorActionsPath = "/data/operator-actions.json" + +// OperatorAction is one recorded row action. +type OperatorAction struct { + Action string `json:"action"` + Actor string `json:"actor"` + At time.Time `json:"at"` + // Note is the comment / direction / reason the operator typed + // (truncated); Target names what the action pointed at (the superseding + // PR of a close-superseded). + Note string `json:"note,omitempty"` + Target string `json:"target,omitempty"` + Outcome string `json:"outcome"` + // Detail is the endpoint's status word (unparked, approval-commented, + // closed, …), the delegated verdict, or the error on a failure. + Detail string `json:"detail,omitempty"` + HeadSHA string `json:"head_sha,omitempty"` + // Stage is the item's stage number when the action was recorded (0 when + // unknown), so the tracker can tell "still at 085" from "moved on". + Stage int `json:"stage,omitempty"` +} + +type operatorActionStore struct { + mu sync.Mutex + path string + loaded bool + items map[string][]OperatorAction +} + +func newOperatorActionStore(path string) *operatorActionStore { + return &operatorActionStore{path: path, items: map[string][]OperatorAction{}} +} + +func operatorActionKey(repo string, number int) string { + return strings.ToLower(strings.TrimSpace(repo)) + "#" + strconv.Itoa(number) +} + +func (st *operatorActionStore) load() { + if st.loaded { + return + } + st.loaded = true + if st.path == "" { + return + } + data, err := os.ReadFile(st.path) + if err != nil { + return + } + var items map[string][]OperatorAction + if json.Unmarshal(data, &items) == nil && items != nil { + st.items = items + } +} + +func (st *operatorActionStore) persist() error { + if st.path == "" { + return nil + } + if err := os.MkdirAll(filepath.Dir(st.path), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(st.items, "", " ") + if err != nil { + return err + } + tmp := st.path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, st.path) +} + +// Record appends one action for repo#number, keeping the newest +// operatorActionsMaxPerItem. +func (st *operatorActionStore) Record(repo string, number int, a OperatorAction) error { + if st == nil { + return nil + } + st.mu.Lock() + defer st.mu.Unlock() + st.load() + key := operatorActionKey(repo, number) + list := append(st.items[key], a) + if len(list) > operatorActionsMaxPerItem { + list = list[len(list)-operatorActionsMaxPerItem:] + } + st.items[key] = list + return st.persist() +} + +// Settle updates the newest pending record of `action` on repo#number +// (a delegated decision whose job just ended). Returns false when there is +// none. +func (st *operatorActionStore) Settle(repo string, number int, action, outcome, detail string) (bool, error) { + if st == nil { + return false, nil + } + st.mu.Lock() + defer st.mu.Unlock() + st.load() + list := st.items[operatorActionKey(repo, number)] + for i := len(list) - 1; i >= 0; i-- { + if list[i].Action == action && list[i].Outcome == operatorActionOutcomePending { + list[i].Outcome = outcome + list[i].Detail = detail + return true, st.persist() + } + } + return false, nil +} + +// List returns a copy of the actions recorded for repo#number, oldest first. +func (st *operatorActionStore) List(repo string, number int) []OperatorAction { + if st == nil { + return nil + } + st.mu.Lock() + defer st.mu.Unlock() + st.load() + return slices.Clone(st.items[operatorActionKey(repo, number)]) +} + +// Keys returns every repo#number with at least one record. +func (st *operatorActionStore) Keys() []string { + if st == nil { + return nil + } + st.mu.Lock() + defer st.mu.Unlock() + st.load() + out := make([]string, 0, len(st.items)) + for k, v := range st.items { + if len(v) > 0 { + out = append(out, k) + } + } + return out +} + +// operatorActions is the server's ledger, opened on first use. +func (s *Server) operatorActions() *operatorActionStore { + if s == nil { + return nil + } + s.operatorActionsOnce.Do(func() { + if s.operatorActionStore == nil { + s.operatorActionStore = newOperatorActionStore(operatorActionsPath) + } + }) + return s.operatorActionStore +} + +// operatorActionStuckAfter is how long a recorded action may sit at the +// same stage before the row's badge turns amber. +func operatorActionStuckAfter() time.Duration { + if raw := strings.TrimSpace(os.Getenv(operatorActionStuckAfterEnv)); raw != "" { + if d, err := time.ParseDuration(raw); err == nil && d > 0 { + return d + } + } + return operatorActionStuckAfterDefault +} + +// operatorActionRequest is the request-side shape of a recorded action: +// which canonical name it takes and what the operator attached to it. +type operatorActionRequest struct { + Action string + Note string + Target string + Head string +} + +// operatorActionFromBody maps one endpoint's request body onto a canonical +// action. endpoint is the route's last path segment. ok=false means the +// request names no recordable action (an unknown decision verb, say). +func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest, bool) { + var raw struct { + Decision string `json:"decision"` + Comment string `json:"comment"` + SupersededBy string `json:"superseded_by"` + Held *bool `json:"held"` + Reason string `json:"reason"` + Head string `json:"head"` + } + if len(bytes.TrimSpace(body)) > 0 { + _ = json.Unmarshal(body, &raw) + } + out := operatorActionRequest{Head: strings.TrimSpace(raw.Head)} + switch endpoint { + case "decision": + switch strings.ToLower(strings.TrimSpace(raw.Decision)) { + case repoItemDecisionApprove: + out.Action = operatorActionApprove + case repoItemDecisionDirection: + out.Action = operatorActionGiveDirection + case repoItemDecisionCloseSuperseded: + out.Action = operatorActionCloseSuperseded + out.Target = strings.TrimSpace(raw.SupersededBy) + case repoItemDecisionCloseWontFix: + out.Action = operatorActionWontFix + default: + return out, false + } + out.Note = truncateOperatorNote(raw.Comment) + case "decide-delegated": + out.Action = operatorActionLetHiveDecide + case "hold": + if raw.Held == nil { + return out, false + } + out.Action = operatorActionRelease + if *raw.Held { + out.Action = operatorActionHold + } + case "accept-triage": + out.Action = operatorActionAcceptTriage + case "send-to-human": + out.Action = operatorActionMarkNeedsHuman + out.Note = truncateOperatorNote(raw.Reason) + default: + return out, false + } + return out, true +} + +func truncateOperatorNote(s string) string { + s = strings.TrimSpace(s) + if len(s) > operatorActionNoteMax { + return s[:operatorActionNoteMax-1] + "…" + } + return s +} + +// operatorActionOutcome reads the endpoint's answer: HTTP status plus the +// JSON it wrote. record=false means the request never became an action +// (rejected before anything was asked of GitHub: bad body, no permission, +// unknown item). +func operatorActionOutcome(status int, body []byte) (outcome, detail, head string, record bool) { + var resp map[string]any + if len(bytes.TrimSpace(body)) > 0 { + _ = json.Unmarshal(body, &resp) + } + str := func(k string) string { + v, _ := resp[k].(string) + return strings.TrimSpace(v) + } + head = str("head") + switch { + case status == http.StatusAccepted: + return operatorActionOutcomePending, str("status"), head, true + case status >= 200 && status < 300: + if already, _ := resp["alreadyAccepted"].(bool); already { + return operatorActionOutcomeNoOp, "already accepted", head, true + } + detail = str("status") + if detail == "" { + if released, ok := resp["released"].([]any); ok && len(released) > 0 { + parts := make([]string, 0, len(released)) + for _, r := range released { + if s, ok := r.(string); ok { + parts = append(parts, s) + } + } + detail = strings.Join(parts, ", ") + } + } + if d, ok := resp["decision"].(map[string]any); ok && status == http.StatusOK { + if v, _ := d["verdict"].(string); v != "" { + detail = "hive decided: " + v + if rule, _ := d["rule"].(string); rule != "" { + detail += " (" + rule + ")" + } + } + if st, _ := resp["status"].(string); st == delegatedJobStatusFailed { + return operatorActionOutcomeFailed, str("error"), head, true + } + } + return operatorActionOutcomeApplied, detail, head, true + case status == http.StatusConflict: + return operatorActionOutcomeNoOp, str("error"), head, true + case status >= 500: + return operatorActionOutcomeFailed, str("error"), head, true + default: + return "", "", head, false + } +} + +// operatorActionWriter captures what an item-action handler answers so the +// ledger can record it after the fact. +type operatorActionWriter struct { + http.ResponseWriter + status int + body bytes.Buffer +} + +func (w *operatorActionWriter) WriteHeader(code int) { + if w.status == 0 { + w.status = code + } + w.ResponseWriter.WriteHeader(code) +} + +func (w *operatorActionWriter) Write(p []byte) (int, error) { + if w.status == 0 { + w.status = http.StatusOK + } + if w.body.Len() < operatorActionBodyMax { + w.body.Write(p) + } + return w.ResponseWriter.Write(p) +} + +func (w *operatorActionWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// recordOperatorAction wraps an item-action handler so the action it +// performs lands in the ledger with the outcome the handler answered. The +// handler itself is untouched: the body is re-supplied to it and the +// response passes straight through. +func (s *Server) recordOperatorAction(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(io.LimitReader(r.Body, operatorActionBodyMax)) + _ = r.Body.Close() + r.Body = io.NopCloser(bytes.NewReader(body)) + segs := strings.Split(strings.Trim(r.URL.Path, "/"), "/") + endpoint := segs[len(segs)-1] + req, known := operatorActionFromBody(endpoint, body) + cw := &operatorActionWriter{ResponseWriter: w} + h(cw, r) + if !known { + return + } + outcome, detail, head, record := operatorActionOutcome(cw.status, cw.body.Bytes()) + if !record { + return + } + owner, repoName := r.PathValue("owner"), r.PathValue("repo") + number, err := strconv.Atoi(r.PathValue("number")) + if owner == "" || repoName == "" || err != nil || number <= 0 { + return + } + repoFull := owner + "/" + repoName + if head == "" { + head = req.Head + } + a := OperatorAction{ + Action: req.Action, Actor: requestUser(r), At: time.Now().UTC(), + Note: req.Note, Target: req.Target, Outcome: outcome, Detail: detail, HeadSHA: head, + } + if rec, ok := s.stageStoreOrShared().Get(stagelabels.Key(repoFull, number)); ok { + a.Stage = rec.Stage.Number() + } + if err := s.operatorActions().Record(repoFull, number, a); err != nil && s.logger != nil { + s.logger.Warn("operator action ledger write failed", "path", operatorActionsPath, "error", err) + } + s.invalidateStageTrackerCache() + } +} + +// settleOperatorAction closes the pending let-hive-decide record once the +// delegated job ends. +func (s *Server) settleOperatorAction(repoFull string, number int, job *delegatedDecisionJob) { + if s == nil || job == nil { + return + } + outcome, detail := operatorActionOutcomeApplied, "" + if job.Decision != nil { + detail = "hive decided: " + string(job.Decision.Verdict) + if job.Decision.Rule != "" { + detail += " (" + job.Decision.Rule + ")" + } + if job.Decision.KeepsPark { + detail += " — kept for the owner" + } + } + if job.Status == delegatedJobStatusFailed { + outcome, detail = operatorActionOutcomeFailed, job.Error + } + if _, err := s.operatorActions().Settle(repoFull, number, operatorActionLetHiveDecide, outcome, detail); err != nil && s.logger != nil { + s.logger.Warn("operator action ledger write failed", "path", operatorActionsPath, "error", err) + } + s.invalidateStageTrackerCache() +} + +// StageTrackerOperatorAction is the row-payload view of the newest recorded +// action: the record plus what the tracker can say about it now. +type StageTrackerOperatorAction struct { + Action string `json:"action"` + Actor string `json:"actor"` + At time.Time `json:"at"` + Note string `json:"note,omitempty"` + Target string `json:"target,omitempty"` + Outcome string `json:"outcome"` + Detail string `json:"detail,omitempty"` + HeadSHA string `json:"head_sha,omitempty"` + // StageAt is the stage the item was on when the action was recorded. + StageAt int `json:"stage_at,omitempty"` + // State is the at-a-glance verdict: addressed (the item moved on, or + // the control the action asked for is in effect), waiting (same stage, + // recently), stuck (same stage past the stuck window), pending (a + // delegated decision still running) or failed. + State string `json:"state"` + // StuckAfterSeconds is the window `stuck` is judged against. + StuckAfterSeconds int64 `json:"stuck_after_seconds,omitempty"` + // Followed is what the hive did next: the stage hops recorded after the + // action, oldest first (capped), so the row can tell the decision trail + // — owner's choice, then the hive's moves — in order. + Followed []StageTrackerHop `json:"followed,omitempty"` +} + +const operatorActionFollowedMax = 5 + +// operatorActionFollowed picks the hops that came after the action. +func operatorActionFollowed(a OperatorAction, history []StageTrackerHop) []StageTrackerHop { + var out []StageTrackerHop + for _, h := range history { + if !a.At.IsZero() && h.At.After(a.At) { + out = append(out, h) + } + } + if len(out) > operatorActionFollowedMax { + out = out[len(out)-operatorActionFollowedMax:] + } + return out +} + +// operatorActionAddressed says whether the item now shows what the action +// asked for: a hold / release / needs-human by its modifier, anything else +// by having left the stage it was recorded on (a close leaves the list). +func operatorActionAddressed(a OperatorAction, stage int, modifiers []string) bool { + switch a.Action { + case operatorActionHold: + return slices.Contains(modifiers, modHold) + case operatorActionRelease: + return !slices.Contains(modifiers, modHold) + case operatorActionMarkNeedsHuman: + return slices.Contains(modifiers, modNeedsHuman) + case operatorActionAcceptTriage: + return !slices.Contains(modifiers, modNeedsTriage) && stage != stagelabels.TriageNeeded.Number() + } + return a.Stage != 0 && stage != a.Stage +} + +// stageTrackerOperatorAction derives the row view of the newest record. +func stageTrackerOperatorAction(actions []OperatorAction, stage int, modifiers []string, history []StageTrackerHop, now time.Time, stuckAfter time.Duration) *StageTrackerOperatorAction { + if len(actions) == 0 { + return nil + } + a := actions[len(actions)-1] + out := &StageTrackerOperatorAction{ + Action: a.Action, Actor: a.Actor, At: a.At, Note: a.Note, Target: a.Target, Outcome: a.Outcome, Detail: a.Detail, + HeadSHA: a.HeadSHA, StageAt: a.Stage, StuckAfterSeconds: int64(stuckAfter / time.Second), + Followed: operatorActionFollowed(a, history), + } + addressed := operatorActionAddressed(a, stage, modifiers) + switch { + case a.Outcome == operatorActionOutcomePending: + out.State = operatorActionStatePending + case addressed: + out.State = operatorActionStateAddressed + if a.Outcome == operatorActionOutcomeFailed || a.Outcome == operatorActionOutcomeNoOp { + out.Outcome = operatorActionOutcomeSuperseded + } + case a.Outcome == operatorActionOutcomeFailed: + out.State = operatorActionStateFailed + case !a.At.IsZero() && now.Sub(a.At) >= stuckAfter: + out.State = operatorActionStateStuck + default: + out.State = operatorActionStateWaiting + } + return out +} + +// applyOperatorActions stamps last_operator_action / operator_action_count +// onto every tracker item with a record. +func (s *Server) applyOperatorActions(items []StageTrackerItem, now time.Time) { + st := s.operatorActions() + if st == nil { + return + } + keys := st.Keys() + if len(keys) == 0 { + return + } + have := map[string]bool{} + for _, k := range keys { + have[k] = true + } + stuckAfter := operatorActionStuckAfter() + for i := range items { + it := &items[i] + if !have[operatorActionKey(it.Repo, it.Number)] { + continue + } + actions := st.List(it.Repo, it.Number) + it.OperatorActionCount = len(actions) + it.LastOperatorAction = stageTrackerOperatorAction(actions, it.Stage, it.Modifiers, it.History, now, stuckAfter) + } +} + +// repoItemDetailResponse is GET /api/repos/{owner}/{repo}/items/{number}. +type repoItemDetailResponse struct { + Repo string `json:"repo"` + Number int `json:"number"` + Stage int `json:"stage,omitempty"` + StageSlug string `json:"stage_slug,omitempty"` + OperatorActions []OperatorAction `json:"operator_actions"` + OperatorActionCount int `json:"operator_action_count"` + LastOperatorAction *StageTrackerOperatorAction `json:"last_operator_action,omitempty"` +} + +// handleRepoItemDetail answers the per-item detail: the stage the ledger +// knows and the full operator-action history. +func (s *Server) handleRepoItemDetail(w http.ResponseWriter, r *http.Request) { + owner, repoName, number, ok := s.parseRepoItemPath(w, r) + if !ok { + return + } + repoFull := owner + "/" + repoName + actions := s.operatorActions().List(repoFull, number) + if actions == nil { + actions = []OperatorAction{} + } + resp := repoItemDetailResponse{Repo: repoFull, Number: number, OperatorActions: actions, OperatorActionCount: len(actions)} + var modifiers []string + var history []StageTrackerHop + if rec, ok := s.stageStoreOrShared().Get(stagelabels.Key(repoFull, number)); ok && rec.Stage != stagelabels.None { + resp.Stage = rec.Stage.Number() + resp.StageSlug = rec.Stage.Slug() + history = stageTrackerHistory(rec) + } + if it, ok := s.stageTrackerItemFor(repoFull, number); ok { + resp.Stage, resp.StageSlug, modifiers, history = it.Stage, it.StageSlug, it.Modifiers, it.History + } + resp.LastOperatorAction = stageTrackerOperatorAction(actions, resp.Stage, modifiers, history, time.Now().UTC(), operatorActionStuckAfter()) + jsonResponse(w, resp) +} + +// stageTrackerItemFor finds repo#number in the current tracker payload. +func (s *Server) stageTrackerItemFor(repoFull string, number int) (StageTrackerItem, bool) { + s.statusMu.RLock() + status := s.status + s.statusMu.RUnlock() + if status == nil { + return StageTrackerItem{}, false + } + body, _, _, _ := s.stageTrackerPayload(status, time.Now().UTC()) + if body == nil { + return StageTrackerItem{}, false + } + var resp StageTrackerResponse + if json.Unmarshal(body, &resp) != nil { + return StageTrackerItem{}, false + } + for _, it := range resp.Items { + if it.Number == number && strings.EqualFold(it.Repo, repoFull) { + return it, true + } + } + return StageTrackerItem{}, false +} diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go new file mode 100644 index 0000000000..ac3a71d4ce --- /dev/null +++ b/src/pkg/dashboard/operator_actions_test.go @@ -0,0 +1,251 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func TestOperatorActionStoreRecordSettlePersist(t *testing.T) { + path := filepath.Join(t.TempDir(), "ops.json") + st := newOperatorActionStore(path) + at := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + if err := st.Record("Org/Repo", 7, OperatorAction{Action: operatorActionLetHiveDecide, Actor: "clubanderson", At: at, Outcome: operatorActionOutcomePending, Stage: 45}); err != nil { + t.Fatal(err) + } + if got := st.List("org/repo", 7); len(got) != 1 || got[0].Outcome != operatorActionOutcomePending { + t.Fatalf("list after record = %+v", got) + } + ok, err := st.Settle("org/repo", 7, operatorActionLetHiveDecide, operatorActionOutcomeApplied, "hive decided: approve") + if err != nil || !ok { + t.Fatalf("settle ok=%v err=%v", ok, err) + } + if ok, _ := st.Settle("org/repo", 7, operatorActionLetHiveDecide, operatorActionOutcomeApplied, "again"); ok { + t.Fatal("settle must only close a pending record") + } + for i := 0; i < operatorActionsMaxPerItem+3; i++ { + _ = st.Record("org/repo", 7, OperatorAction{Action: operatorActionApprove, At: at.Add(time.Duration(i) * time.Minute), Outcome: operatorActionOutcomeApplied}) + } + if got := st.List("org/repo", 7); len(got) != operatorActionsMaxPerItem { + t.Fatalf("cap: %d records, want %d", len(got), operatorActionsMaxPerItem) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("ledger not persisted: %v", err) + } + again := newOperatorActionStore(path) + if got := again.List("org/repo", 7); len(got) != operatorActionsMaxPerItem || got[len(got)-1].Action != operatorActionApprove { + t.Fatalf("reload = %d records, last %+v", len(got), got[len(got)-1]) + } + if keys := again.Keys(); len(keys) != 1 || keys[0] != "org/repo#7" { + t.Fatalf("keys = %v", keys) + } +} + +func TestOperatorActionFromBody(t *testing.T) { + cases := []struct { + endpoint, body string + want operatorActionRequest + ok bool + }{ + {"decision", `{"decision":"approve","head":"abc"}`, operatorActionRequest{Action: operatorActionApprove, Head: "abc"}, true}, + {"decision", `{"decision":"direction","comment":" ship B "}`, operatorActionRequest{Action: operatorActionGiveDirection, Note: "ship B"}, true}, + {"decision", `{"decision":"close-superseded","superseded_by":"#41"}`, operatorActionRequest{Action: operatorActionCloseSuperseded, Target: "#41"}, true}, + {"decision", `{"decision":"close-wontfix"}`, operatorActionRequest{Action: operatorActionWontFix}, true}, + {"decision", `{"decision":"bogus"}`, operatorActionRequest{}, false}, + {"decide-delegated", ``, operatorActionRequest{Action: operatorActionLetHiveDecide}, true}, + {"hold", `{"held":true}`, operatorActionRequest{Action: operatorActionHold}, true}, + {"hold", `{"held":false}`, operatorActionRequest{Action: operatorActionRelease}, true}, + {"hold", `{}`, operatorActionRequest{}, false}, + {"accept-triage", ``, operatorActionRequest{Action: operatorActionAcceptTriage}, true}, + {"send-to-human", `{"reason":"needs a human eye"}`, operatorActionRequest{Action: operatorActionMarkNeedsHuman, Note: "needs a human eye"}, true}, + {"labels", `{}`, operatorActionRequest{}, false}, + } + for _, c := range cases { + got, ok := operatorActionFromBody(c.endpoint, []byte(c.body)) + if ok != c.ok || (ok && got != c.want) { + t.Errorf("%s %s: got %+v ok=%v, want %+v ok=%v", c.endpoint, c.body, got, ok, c.want, c.ok) + } + } +} + +func TestOperatorActionOutcome(t *testing.T) { + cases := []struct { + status int + body string + outcome string + detail string + head string + record bool + description string + }{ + {200, `{"ok":true,"status":"unparked","head":"feedface"}`, operatorActionOutcomeApplied, "unparked", "feedface", true, "approve"}, + {200, `{"ok":true,"alreadyAccepted":true}`, operatorActionOutcomeNoOp, "already accepted", "", true, "accept-triage twice"}, + {200, `{"ok":true,"released":["hold","needs-human"]}`, operatorActionOutcomeApplied, "hold, needs-human", "", true, "release"}, + {200, `{"status":"done","decision":{"verdict":"approve","rule":"auto-merge"}}`, operatorActionOutcomeApplied, "hive decided: approve (auto-merge)", "", true, "delegated sync done"}, + {200, `{"status":"failed","error":"boom","decision":{"verdict":""}}`, operatorActionOutcomeFailed, "boom", "", true, "delegated sync failed"}, + {202, `{"status":"running"}`, operatorActionOutcomePending, "running", "", true, "delegated async"}, + {409, `{"error":"not parked"}`, operatorActionOutcomeNoOp, "not parked", "", true, "conflict"}, + {502, `{"error":"github down"}`, operatorActionOutcomeFailed, "github down", "", true, "upstream"}, + {400, `{"error":"bad"}`, "", "", "", false, "rejected input"}, + {403, ``, "", "", "", false, "forbidden"}, + } + for _, c := range cases { + outcome, detail, head, record := operatorActionOutcome(c.status, []byte(c.body)) + if outcome != c.outcome || detail != c.detail || head != c.head || record != c.record { + t.Errorf("%s: got (%q,%q,%q,%v) want (%q,%q,%q,%v)", c.description, outcome, detail, head, record, c.outcome, c.detail, c.head, c.record) + } + } +} + +func TestStageTrackerOperatorActionStates(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + window := 30 * time.Minute + rec := func(action, outcome string, ago time.Duration, stage int) []OperatorAction { + return []OperatorAction{{Action: action, Actor: "o", At: now.Add(-ago), Outcome: outcome, Stage: stage}} + } + if got := stageTrackerOperatorAction(nil, 85, nil, nil, now, window); got != nil { + t.Fatalf("no records → nil, got %+v", got) + } + cases := []struct { + name string + actions []OperatorAction + stage int + mods []string + wantSt string + wantOutc string + }{ + {"fresh same stage", rec(operatorActionApprove, operatorActionOutcomeApplied, 5*time.Minute, 85), 85, nil, operatorActionStateWaiting, operatorActionOutcomeApplied}, + {"aged same stage", rec(operatorActionApprove, operatorActionOutcomeApplied, 42*time.Minute, 85), 85, nil, operatorActionStateStuck, operatorActionOutcomeApplied}, + {"moved on", rec(operatorActionApprove, operatorActionOutcomeApplied, 42*time.Minute, 85), 100, nil, operatorActionStateAddressed, operatorActionOutcomeApplied}, + {"failed then moved anyway", rec(operatorActionApprove, operatorActionOutcomeFailed, 42*time.Minute, 85), 100, nil, operatorActionStateAddressed, operatorActionOutcomeSuperseded}, + {"failed same stage", rec(operatorActionApprove, operatorActionOutcomeFailed, 5*time.Minute, 85), 85, nil, operatorActionStateFailed, operatorActionOutcomeFailed}, + {"pending", rec(operatorActionLetHiveDecide, operatorActionOutcomePending, 50*time.Minute, 45), 45, nil, operatorActionStatePending, operatorActionOutcomePending}, + {"hold in effect", rec(operatorActionHold, operatorActionOutcomeApplied, 50*time.Minute, 30), 30, []string{modHold}, operatorActionStateAddressed, operatorActionOutcomeApplied}, + {"hold not yet", rec(operatorActionHold, operatorActionOutcomeApplied, 50*time.Minute, 30), 30, nil, operatorActionStateStuck, operatorActionOutcomeApplied}, + {"release done", rec(operatorActionRelease, operatorActionOutcomeApplied, 1*time.Minute, 30), 30, nil, operatorActionStateAddressed, operatorActionOutcomeApplied}, + {"needs-human set", rec(operatorActionMarkNeedsHuman, operatorActionOutcomeApplied, 1*time.Minute, 85), 85, []string{modNeedsHuman}, operatorActionStateAddressed, operatorActionOutcomeApplied}, + {"triage accepted", rec(operatorActionAcceptTriage, operatorActionOutcomeApplied, 1*time.Minute, 15), 20, nil, operatorActionStateAddressed, operatorActionOutcomeApplied}, + {"triage still", rec(operatorActionAcceptTriage, operatorActionOutcomeApplied, 1*time.Minute, 15), 15, []string{modNeedsTriage}, operatorActionStateWaiting, operatorActionOutcomeApplied}, + } + for _, c := range cases { + got := stageTrackerOperatorAction(c.actions, c.stage, c.mods, nil, now, window) + if got == nil || got.State != c.wantSt || got.Outcome != c.wantOutc || got.StuckAfterSeconds != 1800 { + t.Errorf("%s: got %+v, want state=%s outcome=%s", c.name, got, c.wantSt, c.wantOutc) + } + } +} + +func TestStageTrackerOperatorActionFollowedTrail(t *testing.T) { + now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) + actions := []OperatorAction{ + {Action: operatorActionGiveDirection, At: now.Add(-time.Hour), Outcome: operatorActionOutcomeApplied, Stage: 45}, + {Action: operatorActionApprove, At: now.Add(-10 * time.Minute), Outcome: operatorActionOutcomeApplied, Stage: 85}, + } + history := []StageTrackerHop{ + {Number: 45, At: now.Add(-2 * time.Hour)}, + {Number: 85, At: now.Add(-30 * time.Minute)}, + {Number: 90, At: now.Add(-8 * time.Minute), Reason: "approved-direction"}, + {Number: 100, At: now.Add(-1 * time.Minute)}, + } + got := stageTrackerOperatorAction(actions, 100, nil, history, now, 30*time.Minute) + if got.Action != operatorActionApprove || got.State != operatorActionStateAddressed { + t.Fatalf("newest record wins: %+v", got) + } + if len(got.Followed) != 2 || got.Followed[0].Number != 90 || got.Followed[1].Number != 100 { + t.Fatalf("followed = %+v, want the two hops after the approve, oldest first", got.Followed) + } + many := make([]StageTrackerHop, 0, operatorActionFollowedMax+4) + for i := 0; i < operatorActionFollowedMax+4; i++ { + many = append(many, StageTrackerHop{Number: 50 + i, At: now.Add(-time.Duration(operatorActionFollowedMax+4-i) * time.Second)}) + } + if f := operatorActionFollowed(actions[1], many); len(f) != operatorActionFollowedMax || f[len(f)-1].Number != 50+operatorActionFollowedMax+3 { + t.Fatalf("cap keeps the newest %d: %+v", operatorActionFollowedMax, f) + } +} + +// Posting a row action through the dashboard records it; the tracker row +// and the item detail both carry it afterwards. +func TestOperatorActionRecordedByDecisionEndpoint(t *testing.T) { + mock := &repoItemDecisionMock{issueLabels: []string{"bug", "stage/045-needs-decision"}} + srv := newRepoItemDecisionServer(t, mock) + srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) + srv.stageStore = stagelabels.NewStore("", func() time.Time { return time.Now().UTC() }) + srv.stageStore.Observe(stagelabels.Key("testorg/testrepo", 7), stagelabels.NeedsDecision, "test") + + if w := postRepoItemDecision(t, srv, 7, "reader", `{"decision":"approve"}`); w.Code != http.StatusForbidden { + t.Fatalf("reader: code=%d body=%s", w.Code, w.Body.String()) + } + if got := srv.operatorActions().List("testorg/testrepo", 7); len(got) != 0 { + t.Fatalf("a rejected request must not be recorded: %+v", got) + } + + if w := postRepoItemDecision(t, srv, 7, "writer", `{"decision":"approve","comment":"looks right"}`); w.Code != http.StatusOK { + t.Fatalf("approve: code=%d body=%s", w.Code, w.Body.String()) + } + got := srv.operatorActions().List("testorg/testrepo", 7) + if len(got) != 1 { + t.Fatalf("records = %+v", got) + } + a := got[0] + if a.Action != operatorActionApprove || a.Actor != "writer" || a.Outcome != operatorActionOutcomeApplied || a.Detail != "unparked" || a.Note != "looks right" || a.Stage != stagelabels.NeedsDecision.Number() || a.At.IsZero() { + t.Fatalf("record = %+v", a) + } + + // A second approve on the now un-parked issue is a 409: recorded as + // a no-op so the owner sees "nothing to change", not nothing. + mock.issueLabels = []string{"bug"} + if w := postRepoItemDecision(t, srv, 7, "writer", `{"decision":"approve"}`); w.Code != http.StatusConflict { + t.Fatalf("second approve: code=%d body=%s", w.Code, w.Body.String()) + } + got = srv.operatorActions().List("testorg/testrepo", 7) + if len(got) != 2 || got[1].Outcome != operatorActionOutcomeNoOp { + t.Fatalf("records after conflict = %+v", got) + } + + req := httptest.NewRequest(http.MethodGet, "/api/repos/testorg/testrepo/items/7", nil) + req.Header.Set("X-Hive-User", "writer") + w := httptest.NewRecorder() + srv.mux.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("detail: code=%d body=%s", w.Code, w.Body.String()) + } + var detail repoItemDetailResponse + if err := json.Unmarshal(w.Body.Bytes(), &detail); err != nil { + t.Fatal(err) + } + if detail.Repo != "testorg/testrepo" || detail.Number != 7 || detail.OperatorActionCount != 2 || len(detail.OperatorActions) != 2 || detail.LastOperatorAction == nil { + t.Fatalf("detail = %s", w.Body.String()) + } + if detail.LastOperatorAction.Action != operatorActionApprove || detail.LastOperatorAction.Outcome != operatorActionOutcomeNoOp { + t.Fatalf("last = %+v", detail.LastOperatorAction) + } + var raw map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &raw) + for _, k := range []string{"operator_actions", "operator_action_count", "last_operator_action", "stage"} { + if _, ok := raw[k]; !ok { + t.Errorf("detail payload lacks %q: %s", k, w.Body.String()) + } + } + + items := []StageTrackerItem{{Repo: "testorg/testrepo", Number: 7, Stage: 45}, {Repo: "testorg/testrepo", Number: 8, Stage: 85}} + srv.applyOperatorActions(items, time.Now().UTC()) + if items[0].OperatorActionCount != 2 || items[0].LastOperatorAction == nil || (items[0].LastOperatorAction.Outcome != operatorActionOutcomeNoOp && items[0].LastOperatorAction.Outcome != operatorActionOutcomeSuperseded) || items[0].LastOperatorAction.State == "" { + t.Fatalf("tracker item count=%d last=%+v", items[0].OperatorActionCount, items[0].LastOperatorAction) + } + if items[1].OperatorActionCount != 0 || items[1].LastOperatorAction != nil { + t.Fatalf("untouched item must stay bare: %+v", items[1]) + } + payload, _ := json.Marshal(items[0]) + for _, k := range []string{`"last_operator_action":{`, `"operator_action_count":2`, `"state":"`, `"stuck_after_seconds":`} { + if !strings.Contains(string(payload), k) { + t.Errorf("row payload lacks %s: %s", k, payload) + } + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 448923a4ae..4796a15b99 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -194,6 +194,10 @@ type Server struct { // delegatedJobs tracks "Let hive decide" jobs by repo#number // (api_repo_item_decide_delegated.go). delegatedJobs delegatedDecisionJobs + // operatorActionStore is the owner row-action ledger behind the + // activity monitor's ✓ badge (operator_actions.go), opened on first use. + operatorActionStore *operatorActionStore + operatorActionsOnce sync.Once // acmmLinearBaseURL overrides the Linear GraphQL endpoint the ACMM // "Open Issue" path posts issueCreate to. Empty = production; tests // point it at an httptest server. diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index b2f901d014..0f5d2473ad 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -427,7 +427,13 @@ type StageTrackerItem struct { // chip. StateReason "not_planned" adds an "issue closed (not planned)" // chip so the reader can tell the PR may be moot (hivecommons/hive#14655). ClosedIssue *StageTrackerLinkedIssue `json:"closed_issue,omitempty"` - History []StageTrackerHop `json:"history"` + // LastOperatorAction is the newest owner row action recorded for the + // item (approve, give-direction, hold, let-hive-decide, …) with what + // became of it, and OperatorActionCount how many were recorded; the + // row's ✓ badge and its hover read these (operator_actions.go). + LastOperatorAction *StageTrackerOperatorAction `json:"last_operator_action,omitempty"` + OperatorActionCount int `json:"operator_action_count,omitempty"` + History []StageTrackerHop `json:"history"` } // StageTrackerLinkedIssue is one issue a PR closes, as its row's issue @@ -482,6 +488,10 @@ type StageTrackerLinkedPR struct { DecisionNeeded *StageTrackerDecision `json:"decision_needed,omitempty"` // Adoption mirrors the nested PR's own row field (hivecommons/hive#14524). Adoption *StageTrackerAdoption `json:"adoption,omitempty"` + // LastOperatorAction / OperatorActionCount mirror the nested PR's own + // row fields so its sub-row wears the ✓ badge too. + LastOperatorAction *StageTrackerOperatorAction `json:"last_operator_action,omitempty"` + OperatorActionCount int `json:"operator_action_count,omitempty"` } // Stage numbers the tracker lays out by. Pinned to stagelabels.Table in @@ -1765,6 +1775,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } } resp.OpenIssues, resp.OpenPRs = stageTrackerOpenCounts(resp.Items) + s.applyOperatorActions(resp.Items, now) resp.NeedsHuman, resp.OnHold = stageTrackerHumanCounts(resp.Items) stageTrackerResolveLinkedPRs(resp.Items) sort.SliceStable(resp.Items, stageTrackerLess(resp.Items)) @@ -2495,6 +2506,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem) { lp.HumanMergeReason, lp.HumanMergeReasonText = pr.HumanMergeReason, pr.HumanMergeReasonText lp.BaseRef = pr.BaseRef lp.DecisionNeeded = pr.DecisionNeeded + lp.LastOperatorAction, lp.OperatorActionCount = pr.LastOperatorAction, pr.OperatorActionCount if len(pr.Modifiers) > 0 { lp.Modifiers = append([]string(nil), pr.Modifiers...) } diff --git a/src/pkg/dashboard/stage_tracker_acted.test.js b/src/pkg/dashboard/stage_tracker_acted.test.js new file mode 100644 index 0000000000..c10547517b --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_acted.test.js @@ -0,0 +1,163 @@ +// "Did I act on this?" badge in the Hive activity monitor: the tracker +// payload carries `last_operator_action` (operator_actions.go) and the row +// wears a ✓ badge whose in-app tooltip names the action, when, the outcome +// and the current stage; amber once the row has sat at the same stage past +// the window; a Decisions filter narrows to awaiting / acted / stuck. The +// functions are lifted straight out of index.html so this runs against the +// shipped source. +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 pick(re, what) { + const m = html.match(re); + assert.ok(m, what + ' not found in index.html'); + return m[0]; +} + +const src = [ + 'const window = { _hiveUser: "clubanderson" };', + 'const _stageTracker = { stages: [{ number: 85, short: "Merge gate" }, { number: 100, short: "Merged" }] };', + 'function esc(s) { return String(s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); }', + 'function agentNowClockTime(ms) { return new Date(ms).toISOString().slice(11, 16); }', + 'function stageTrackerDecisionTarget(item) { return item && item.parked ? item : null; }', + pick(/function stageTrackerStageWord\(n\) \{[\s\S]*?\n \}\n/, 'stageTrackerStageWord'), + pick(/const STAGE_TRACKER_ACTED_LABELS = \{[\s\S]*?\n \};\n/, 'STAGE_TRACKER_ACTED_LABELS'), + pick(/const STAGE_TRACKER_ACTED_STATES = [^\n]*\n/, 'STAGE_TRACKER_ACTED_STATES'), + pick(/const STAGE_TRACKER_ACTED_FILTERS = [^\n]*\n/, 'STAGE_TRACKER_ACTED_FILTERS'), + pick(/const STAGE_TRACKER_ACTED_STUCK_DEFAULT_S = [^\n]*\n/, 'STAGE_TRACKER_ACTED_STUCK_DEFAULT_S'), + pick(/const STAGE_TRACKER_ACTED_GLYPH = [^\n]*\n/, 'STAGE_TRACKER_ACTED_GLYPH'), + pick(/function stageTrackerActedLabel\(action\) \{[^\n]*\n/, 'stageTrackerActedLabel'), + pick(/function stageTrackerActedSource\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedSource'), + pick(/function stageTrackerActedState\(action, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedState'), + pick(/function stageTrackerActedAgo\(ms\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedAgo'), + pick(/function stageTrackerActedOutcomeWords\(action\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedOutcomeWords'), + pick(/function stageTrackerActedStageName\(n\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedStageName'), + pick(/const STAGE_TRACKER_ACTED_PLAIN = \{[\s\S]*?\n \};\n/, 'STAGE_TRACKER_ACTED_PLAIN'), + pick(/function stageTrackerActedPlain\(text\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedPlain'), + pick(/function stageTrackerActedTip\(item, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedTip'), + pick(/function stageTrackerActedBadgeHtml\(item, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedBadgeHtml'), + pick(/function stageTrackerActedMatches\(item, mode, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedMatches'), +].join('\n'); +const api = new Function(src + '; return { plain: stageTrackerActedPlain, state: stageTrackerActedState, tip: stageTrackerActedTip, badge: stageTrackerActedBadgeHtml, matches: stageTrackerActedMatches, source: stageTrackerActedSource };')(); + +const NOW = Date.parse('2026-10-28T16:00:00Z'); +function act(over) { + return Object.assign({ action: 'approve', actor: 'clubanderson', at: new Date(NOW - 5 * 60000).toISOString(), outcome: 'applied', stage_at: 85, state: 'waiting', stuck_after_seconds: 1800 }, over || {}); +} +function row(over) { + return Object.assign({ repo: 'hivecommons/hive', number: 42, kind: 'pr', stage: 85, modifiers: [], caption: 'waiting on merge gate', last_operator_action: act(), operator_action_count: 1 }, over || {}); +} + +test('no recorded action: no badge, acted filters exclude, awaiting includes parked rows', () => { + const bare = { repo: 'r', number: 1, kind: 'pr', stage: 85, parked: true }; + assert.strictEqual(api.badge(bare, NOW), ''); + assert.strictEqual(api.matches(bare, 'any', NOW), true); + assert.strictEqual(api.matches(bare, 'acted', NOW), false); + assert.strictEqual(api.matches(bare, 'stuck', NOW), false); + assert.strictEqual(api.matches(bare, 'awaiting', NOW), true); + assert.strictEqual(api.matches({ repo: 'r', number: 2, kind: 'pr', stage: 30 }, 'awaiting', NOW), false); +}); + +test('fresh action: green ✓ badge with an in-app tooltip, no native title', () => { + const h = api.badge(row(), NOW); + assert.match(h, /class="ham-badge ham-acted ham-acted-waiting config-info"/); + assert.match(h, /tabindex="0"/); + assert.match(h, /data-action="gh3" data-stop="1"/); + assert.match(h, /aria-describedby="ham-acted-tip-hivecommons-hive-42"/); + assert.match(h, //); + assert.doesNotMatch(h, / title="/); + const tip = api.tip(row(), NOW); + assert.strictEqual(tip, 'At Merge gate — waiting on merge gate.\nYou chose Approve · 15:55 (5 min ago) · done.'); + assert.doesNotMatch(tip, /085/); + assert.strictEqual(api.matches(row(), 'acted', NOW), true); + assert.strictEqual(api.matches(row(), 'awaiting', NOW), false); + assert.strictEqual(api.matches(row(), 'stuck', NOW), false); +}); + +test('another operator acted: tooltip names them', () => { + assert.match(api.tip(row({ last_operator_action: act({ actor: 'someone-else' }) }), NOW), /\n@someone-else chose Approve/); +}); + +test('addressed: stage moved on, badge stays green, tooltip says addressed — now at ', () => { + const r = row({ stage: 100, last_operator_action: act({ state: 'addressed' }) }); + assert.match(api.badge(r, NOW), /ham-acted-addressed/); + assert.match(api.tip(r, NOW), /^Addressed — now at Merged\.\nYou chose Approve/); + assert.strictEqual(api.matches(r, 'stuck', NOW), false); +}); + +test('stuck: server-derived or aged client-side past the window → amber, "requested … still at …; hive says"', () => { + const server = row({ last_operator_action: act({ state: 'stuck', at: new Date(NOW - 42 * 60000).toISOString() }) }); + assert.match(api.badge(server, NOW), /ham-acted-stuck/); + assert.strictEqual(api.tip(server, NOW).split('\n')[0], 'Still at Merge gate 42 min after you asked — hive says: waiting on merge gate.'); + assert.strictEqual(api.matches(server, 'stuck', NOW), true); + // Still `waiting` in the payload but older than the window by now. + const aged = row({ last_operator_action: act({ at: new Date(NOW - 31 * 60000).toISOString() }) }); + assert.strictEqual(api.state(aged.last_operator_action, NOW), 'stuck'); + assert.strictEqual(api.state(act(), NOW), 'waiting'); +}); + +test('pending and failed states', () => { + const pending = row({ last_operator_action: act({ action: 'let-hive-decide', outcome: 'pending', state: 'pending' }) }); + assert.match(api.badge(pending, NOW), /ham-acted-pending config-info"[^>]*>…]*>✗ { + const r = row({ operator_action_count: 3, last_operator_action: act({ action: 'close-superseded', target: '#41', note: 'dup' }) }); + const tip = api.tip(r, NOW); + assert.match(tip, /chose Close as superseded #41 · /); + assert.match(tip, /Your note: dup<\/b>/); + assert.match(tip, /2 earlier actions on this item\./); + const h = api.badge(r, NOW); + assert.match(h, /Your note: <b>dup<\/b>/); + assert.match(h, /
/); +}); + +test('issue row drawn over a single covering PR borrows that PR\'s action', () => { + const issue = { repo: 'r', number: 7, kind: 'issue', stage: 85, linked_prs: [{ number: 8, stage: 85, last_operator_action: act(), operator_action_count: 1 }] }; + const s = api.source(issue); + assert.ok(s); + assert.strictEqual(s.item.number, 8); + assert.match(api.badge(issue, NOW), /ham-acted-tip-r-8/); + const two = Object.assign({}, issue, { linked_prs: [issue.linked_prs[0], { number: 9 }] }); + assert.strictEqual(api.source(two), null); +}); + +test('toolbar carries the Decisions select and the filter plumbing knows `acted`', () => { + assert.match(html, / + @@ -14074,7 +14088,7 @@

Where to get help

var _stageTrackerGroup = STAGE_TRACKER_GROUP_DEFAULT; var _stageTrackerCollapsed = {}; function stageTrackerDefaultFilter() { - return { kind: 'all', repo: '', q: '', labels: [], needsHuman: false, onHold: false, age: 'any', author: 'any', attention: false, sort: 'furthest', dir: 'desc', size: STAGE_TRACKER_DEFAULT_PAGE_SIZE, page: 1 }; + return { kind: 'all', repo: '', q: '', labels: [], needsHuman: false, onHold: false, age: 'any', author: 'any', attention: false, acted: 'any', sort: 'furthest', dir: 'desc', size: STAGE_TRACKER_DEFAULT_PAGE_SIZE, page: 1 }; } var _stageTrackerFilter = stageTrackerDefaultFilter(); // Type-to-filter text of the "all labels" dialog (not persisted). @@ -14595,6 +14609,163 @@

Where to get help

return sentinel + `${inner}`; } + /* ---- "Did I act on this?" badge ------------------------------------ + Owner (2026-10-28): "I need a way to see if I selected an action on + an item so I can keep track of whether or not I addressed it. + Hovering over the indicator should show me what action I requested." + The server keeps a ledger of every row action submitted from the + dashboard (operator_actions.go) and the tracker payload carries the + newest one per item as `last_operator_action` with a derived state: + waiting (same stage, recent), addressed (the item moved on, or the + control asked for is in effect), stuck (same stage past the window), + pending (Let hive decide still running), failed. The row wears a ✓ + badge in the cap cell — green at rest, amber when stuck, red when + failed, dotted while pending — whose in-app tooltip names the action, + when, the outcome and what hive did next. The in-flight spinner (the + request still on the wire) is a different thing drawn on the chevron; + this badge appears once the server has recorded the action. */ + const STAGE_TRACKER_ACTED_LABELS = { + approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", + 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', + }; + const STAGE_TRACKER_ACTED_STATES = ['waiting', 'addressed', 'stuck', 'pending', 'failed']; + const STAGE_TRACKER_ACTED_FILTERS = ['any', 'awaiting', 'acted', 'stuck']; + const STAGE_TRACKER_ACTED_STUCK_DEFAULT_S = 30 * 60; + const STAGE_TRACKER_ACTED_GLYPH = { waiting: '✓', addressed: '✓', stuck: '✓', pending: '…', failed: '✗' }; + function stageTrackerActedLabel(action) { return STAGE_TRACKER_ACTED_LABELS[action] || String(action || '').replace(/-/g, ' '); } + // Pure: the record a row's badge reads — the item's own, else (an issue + // row drawn over its single covering PR) that PR's; null when none. + function stageTrackerActedSource(item) { + if (!item) return null; + if (item.last_operator_action) return { item, action: item.last_operator_action, count: Number(item.operator_action_count) || 1 }; + const linked = Array.isArray(item.linked_prs) ? item.linked_prs : []; + if (item.kind === 'issue' && linked.length === 1 && linked[0].last_operator_action) { + return { item: { repo: item.repo, number: linked[0].number, kind: 'pr', stage: linked[0].stage || 0, modifiers: linked[0].modifiers || [], reason: linked[0].reason || '', caption: linked[0].caption || '' }, action: linked[0].last_operator_action, count: Number(linked[0].operator_action_count) || 1 }; + } + return null; + } + // Pure: the badge state as of nowMs. The server judges `stuck` when it + // builds the payload; a row still `waiting` ages into `stuck` here once + // the window passes, so the badge turns amber between refreshes too. + function stageTrackerActedState(action, nowMs) { + if (!action) return ''; + let state = STAGE_TRACKER_ACTED_STATES.indexOf(action.state) >= 0 ? action.state : 'waiting'; + if (state === 'waiting') { + const at = Date.parse(action.at || ''); + const windowMs = (Number(action.stuck_after_seconds) || STAGE_TRACKER_ACTED_STUCK_DEFAULT_S) * 1000; + if (at && (Number(nowMs) || Date.now()) - at >= windowMs) state = 'stuck'; + } + return state; + } + // Pure: minutes/hours/days in words for the badge tooltip. + function stageTrackerActedAgo(ms) { + const min = Math.max(0, Math.floor((Number(ms) || 0) / 60000)); + if (min < 1) return 'just now'; + if (min < 60) return min + ' min ago'; + const h = Math.floor(min / 60); + if (h < 48) return h + ' h ago'; + return Math.floor(h / 24) + ' d ago'; + } + function stageTrackerActedOutcomeWords(action) { + switch (action.outcome) { + case 'applied': return 'done' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); + case 'no-op': return 'nothing to change' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); + case 'failed': return 'failed' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); + case 'pending': return 'the hive is deciding…'; + case 'superseded-by-state-change': return 'the item moved on by itself'; + } + return action.outcome || ''; + } + // Pure: the stage in plain words, never a code ("Merge gate", not 085). + function stageTrackerActedStageName(n) { + const num = Number(n) || 0; + const st = ((_stageTracker && _stageTracker.stages) || []).find(s => Number(s.number) === num); + return st && (st.short || st.label) ? (st.short || st.label) : (num ? 'stage ' + num : 'an unknown stage'); + } + // Pure: operator-facing gloss for the slugs the hive writes into stage + // reasons and endpoint status words. Unknown input is returned with its + // dashes and colons spelled as words so nothing reads like a code. + const STAGE_TRACKER_ACTED_PLAIN = { + 'contributor-lane:changes-requested': 'a reviewer requested changes; needs a new commit', + 'contributor-lane:approved': 'a reviewer approved it', + 'contributor-lane:ci-failed': 'CI failed on the latest commit', + 'needs-rebase': 'needs a rebase onto the base branch', + 'needs-human': 'waiting on a person', + 'needs-decision': 'waiting on your decision', + unparked: 'released to the hive', + 'approval-commented': 'your approval was posted as a comment', + closed: 'closed on GitHub', + held: 'put on hold', + released: 'hold released', + 'already accepted': 'it was already accepted', + }; + function stageTrackerActedPlain(text) { + const t = String(text || '').trim(); + if (!t) return ''; + if (STAGE_TRACKER_ACTED_PLAIN[t]) return STAGE_TRACKER_ACTED_PLAIN[t]; + if (/^hive decided: /.test(t)) return t.replace(/^hive decided: /, 'the hive decided: ').replace(/ \(([^)]+)\)/, (m, r) => ' (rule: ' + r.replace(/[-_:]/g, ' ') + ')'); + return /^[a-z0-9]+([-_:][a-z0-9]+)+$/.test(t) ? t.replace(/[-_:]/g, ' ') : t; + } + // Pure: the tooltip — the decision trail in plain words, in the order + // every cue on the row uses: what it is waiting on → what you chose → + // what the hive did next (who, when). ≤ 2 short lines per fact. + function stageTrackerActedTip(item, nowMs) { + const src = stageTrackerActedSource(item); + if (!src) return ''; + const a = src.action; + nowMs = Number(nowMs) || Date.now(); + const state = stageTrackerActedState(a, nowMs); + const atMs = Date.parse(a.at || '') || nowMs; + const me = !a.actor || (window._hiveUser && a.actor.toLowerCase() === String(window._hiveUser).toLowerCase()); + const who = me ? 'You' : '@' + a.actor; + const label = stageTrackerActedLabel(a.action) + (a.target ? ' ' + a.target : ''); + const ago = stageTrackerActedAgo(nowMs - atMs); + const stageNow = stageTrackerActedStageName(src.item.stage); + const waitingOn = stageTrackerActedPlain(src.item.caption || src.item.reason); + const lines = []; + if (state === 'addressed') lines.push('Addressed — now at ' + stageNow + '.'); + else if (state === 'stuck') lines.push('Still at ' + stageNow + ' ' + ago.replace(/ ago$/, '') + ' after you asked' + (waitingOn ? ' — hive says: ' + waitingOn : '') + '.'); + else if (state === 'pending') lines.push('At ' + stageNow + ' while the hive decides.'); + else if (state === 'failed') lines.push('Still at ' + stageNow + ' — try again, or act on GitHub.'); + else lines.push('At ' + stageNow + (waitingOn ? ' — ' + waitingOn : '') + '.'); + lines.push(who + ' chose ' + label + ' · ' + agentNowClockTime(atMs, nowMs) + ' (' + ago + ') · ' + stageTrackerActedOutcomeWords(a) + '.'); + if (a.note) lines.push('Your note: ' + a.note); + const followed = Array.isArray(a.followed) ? a.followed : []; + followed.slice(-3).forEach(h => { + const hopMs = Date.parse(h.at || '') || nowMs; + lines.push('Then the hive ' + (h.regressed ? 'sent it back to ' : 'moved it to ') + stageTrackerActedStageName(h.number) + (h.reason ? ' — ' + stageTrackerActedPlain(h.reason) : '') + ' · ' + stageTrackerActedAgo(nowMs - hopMs) + '.'); + }); + if (src.count > 1) lines.push((src.count - 1) + ' earlier action' + (src.count > 2 ? 's' : '') + ' on this item.'); + return lines.join('\n'); + } + // Pure: the badge HTML ('' when the row has no recorded action). An + // in-app tooltip (the shared .config-info portal: hover or focus), + // never a native title. + function stageTrackerActedBadgeHtml(item, nowMs) { + const src = stageTrackerActedSource(item); + if (!src) return ''; + const state = stageTrackerActedState(src.action, nowMs); + const id = 'ham-acted-tip-' + String((src.item.repo || '') + '-' + (Number(src.item.number) || 0)).replace(/[^A-Za-z0-9_-]/g, '-'); + const tip = stageTrackerActedTip(item, nowMs); + const short = stageTrackerActedLabel(src.action.action); + return `${STAGE_TRACKER_ACTED_GLYPH[state] || '✓'}${esc(tip).replace(/\n/g, '
')}
`; + } + // Pure: the Decisions filter. awaiting = parked on a person with no + // action recorded yet (or the last one failed / was overtaken without + // moving it); acted = any action recorded; stuck = acted and still at + // the same stage past the window. + function stageTrackerActedMatches(item, mode, nowMs) { + if (!mode || mode === 'any') return true; + const src = stageTrackerActedSource(item); + const state = src ? stageTrackerActedState(src.action, nowMs) : ''; + switch (mode) { + case 'acted': return !!src; + case 'stuck': return state === 'stuck'; + case 'awaiting': return !!stageTrackerDecisionTarget(item) && (!src || state === 'failed'); + } + return true; + } + // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) // the given refs, and the cap cell the modifier chip, bottom-aligned so @@ -14651,7 +14822,8 @@

Where to get help

function stageTrackerSubRowHtml(lp, issue, stages, nowMs, ctx) { const pr = { repo: issue.repo, number: lp.number, kind: 'pr', title: lp.title || '', url: lp.url || '', author: lp.author || '', author_kind: lp.author_kind || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', decision_needed: lp.decision_needed || null }; + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', decision_needed: lp.decision_needed || null, + last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0 }; let ref = stageTrackerPRRef(pr.number, pr.url, pr.author_kind, pr.author, pr.title, (pr.title ? pr.title + ' · ' : '') + stageTrackerTooltip(pr, nowMs) + ' · ' + stageTrackerLinkedTip(issue, pr.number, ctx)); if (lp.base_ref) ref += ` ${esc(lp.base_ref)}`; const chip = ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : ''; @@ -14659,7 +14831,7 @@

Where to get help

ref = STAGE_TRACKER_LINKED_GLYPH + ref; return `
- ${stageTrackerHeadColsHtml([ref], '', stageTrackerChipsHtml(pr))} + ${stageTrackerHeadColsHtml([ref], '', stageTrackerActedBadgeHtml(pr, nowMs) + stageTrackerChipsHtml(pr))}
    ${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}
@@ -14893,7 +15065,7 @@

Where to get help

return `
${stageTrackerRowToolsHtml(item)}
- ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerChipsHtml(shown))} + ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerActedBadgeHtml(item, nowMs) + stageTrackerChipsHtml(shown))}
    ${stageTrackerStripItems(shown, stages, range, nowMs, ctx)}
@@ -15553,6 +15725,7 @@

Where to get help

if (!(f.age in STAGE_TRACKER_AGE_MS) && f.age !== 'stale') f.age = 'any'; if (['human', 'clanker', 'hive'].indexOf(f.author) < 0) f.author = 'any'; f.attention = !!f.attention; + if (STAGE_TRACKER_ACTED_FILTERS.indexOf(f.acted) < 0) f.acted = 'any'; if (STAGE_TRACKER_SORTS.indexOf(f.sort) < 0) f.sort = 'furthest'; f.dir = f.dir === 'asc' ? 'asc' : 'desc'; f.size = STAGE_TRACKER_PAGE_SIZES.indexOf(Number(f.size)) >= 0 ? Number(f.size) : STAGE_TRACKER_DEFAULT_PAGE_SIZE; @@ -15562,7 +15735,7 @@

Where to get help

// True when any narrowing filter (not sort / paging) is set. function stageTrackerFilterActive(f) { - return f.kind !== 'all' || !!f.repo || !!f.q || f.labels.length > 0 || f.needsHuman || f.onHold || f.age !== 'any' || f.author !== 'any' || f.attention; + return f.kind !== 'all' || !!f.repo || !!f.q || f.labels.length > 0 || f.needsHuman || f.onHold || f.age !== 'any' || f.author !== 'any' || f.attention || f.acted !== 'any'; } // Does one item pass the narrowing filters? ctx.nowMs anchors the age @@ -15590,6 +15763,7 @@

Where to get help

if (f.onHold && !stageTrackerItemOnHold(item)) return false; if (f.author !== 'any' && (item.author_kind || '') !== f.author) return false; if (f.attention && !stageTrackerNeedsAttention(item)) return false; + if (f.acted !== 'any' && !stageTrackerActedMatches(item, f.acted, Number(ctx.nowMs) || Date.now())) return false; if (f.age !== 'any') { const nowMs = Number(ctx.nowMs) || Date.now(); const since = stageTrackerWaitSince(item); @@ -15805,6 +15979,7 @@

Where to get help

case 'age': f.age = value || 'any'; break; case 'author': f.author = value || 'any'; break; case 'attention': f.attention = value === 'toggle' ? !f.attention : !!value; break; + case 'acted': f.acted = value || 'any'; break; case 'sort': f.sort = value || 'furthest'; break; case 'dir': f.dir = value === 'toggle' ? (f.dir === 'asc' ? 'desc' : 'asc') : value; break; case 'size': f.size = Number(value) || STAGE_TRACKER_DEFAULT_PAGE_SIZE; break; @@ -15829,6 +16004,7 @@

Where to get help

setVal('activity-monitor-q', f.q); setVal('activity-monitor-age', f.age); setVal('activity-monitor-author', f.author); + setVal('activity-monitor-acted', f.acted); setVal('activity-monitor-sort', f.sort); setVal('activity-monitor-group', _stageTrackerGroup); setVal('activity-monitor-size', f.size); From 2369384d2de5b7aca20e164c588365fcba14f313 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 13:09:35 -0400 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=8C=B1=20Decision=20badge:=20document?= =?UTF-8?q?=20GET=20items/{number}=20in=20openapi.json;=20lift=20badge=20h?= =?UTF-8?q?elpers=20into=20tracker=20JS=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The row renderer now calls stageTrackerActedBadgeHtml and the filter reads STAGE_TRACKER_ACTED_FILTERS, so the Go tests that lift the tracker JS out of index.html need those helpers (stageTrackerActedJS). The route parity test wants the new GET documented. Signed-off-by: Andrew Anderson --- dashboard/openapi.json | 224 +++++++++++++++++- src/pkg/dashboard/operator_actions_test.go | 24 ++ .../stage_tracker_attention_order_test.go | 1 + .../dashboard/stage_tracker_motion_test.go | 2 + .../stage_tracker_repo_grouping_test.go | 1 + src/pkg/dashboard/stage_tracker_ui_test.go | 2 + 6 files changed, 250 insertions(+), 4 deletions(-) diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 146987408f..c699ec23aa 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -1786,10 +1786,22 @@ "type": "object", "description": "ADR-0025 central stage engine: governor.labels.stage.engine.mode and the process counters. Absent when the hive has no engine.", "properties": { - "mode": { "type": "string", "enum": ["shadow", "enforce"] }, - "derivations": { "type": "integer" }, - "anomalies": { "type": "integer" }, - "healed": { "type": "integer" } + "mode": { + "type": "string", + "enum": [ + "shadow", + "enforce" + ] + }, + "derivations": { + "type": "integer" + }, + "anomalies": { + "type": "integer" + }, + "healed": { + "type": "integer" + } } }, "overview_bands": { @@ -28204,6 +28216,210 @@ } } }, + "/api/repos/{owner}/{repo}/items/{number}": { + "get": { + "tags": [ + "Status" + ], + "summary": "Per-item detail: the operator-action ledger behind the activity monitor's decision badge", + "description": "Returns the stage the dashboard knows for one issue or pull request and every row action submitted for it from the dashboard (hold/release, decision, let-hive-decide, send-to-human, accept-triage), newest last, plus the derived last_operator_action the stage-tracker rows also carry. Persisted in /data/operator-actions.json; HIVE_OPERATOR_ACTION_STUCK_AFTER (default 30m) sets the window after which an unmoved item is reported as stuck.", + "parameters": [ + { + "name": "owner", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "number", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Item detail", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "repo": { + "type": "string" + }, + "number": { + "type": "integer" + }, + "stage": { + "type": "integer" + }, + "stage_slug": { + "type": "string" + }, + "operator_actions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "approve", + "give-direction", + "close-superseded", + "wontfix", + "let-hive-decide", + "hold", + "release", + "accept-triage", + "mark-needs-human" + ] + }, + "actor": { + "type": "string" + }, + "at": { + "type": "string", + "format": "date-time" + }, + "note": { + "type": "string" + }, + "target": { + "type": "string", + "description": "what the action pointed at, e.g. the superseding PR" + }, + "outcome": { + "type": "string", + "enum": [ + "pending", + "applied", + "no-op", + "failed" + ] + }, + "detail": { + "type": "string" + }, + "head_sha": { + "type": "string" + }, + "stage": { + "type": "integer", + "description": "stage number when the action was recorded" + } + } + } + }, + "operator_action_count": { + "type": "integer" + }, + "last_operator_action": { + "type": "object", + "nullable": true, + "properties": { + "action": { + "type": "string" + }, + "actor": { + "type": "string" + }, + "at": { + "type": "string", + "format": "date-time" + }, + "note": { + "type": "string" + }, + "target": { + "type": "string" + }, + "outcome": { + "type": "string", + "enum": [ + "pending", + "applied", + "no-op", + "failed", + "superseded-by-state-change" + ] + }, + "detail": { + "type": "string" + }, + "head_sha": { + "type": "string" + }, + "stage_at": { + "type": "integer" + }, + "state": { + "type": "string", + "enum": [ + "waiting", + "addressed", + "stuck", + "pending", + "failed" + ] + }, + "stuck_after_seconds": { + "type": "integer" + }, + "followed": { + "type": "array", + "description": "stage hops recorded after the action, oldest first", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "slug": { + "type": "string" + }, + "at": { + "type": "string", + "format": "date-time" + }, + "reason": { + "type": "string" + }, + "from": { + "type": "integer" + }, + "regressed": { + "type": "boolean" + } + } + } + } + } + } + } + } + } + } + }, + "400": { + "description": "Bad owner/repo/number" + } + } + } + }, "/api/repos/{owner}/{repo}/items/{number}/hold": { "post": { "tags": [ diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index ac3a71d4ce..4063840e7a 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -249,3 +249,27 @@ func TestOperatorActionRecordedByDecisionEndpoint(t *testing.T) { } } } + +// stageTrackerActedJS lifts the "did I act on this?" badge helpers the row +// renderer and the filter call (operator_actions.go payload fields). +func stageTrackerActedJS(t *testing.T, html string) string { + t.Helper() + return strings.Join([]string{ + jsConstBlock(t, html, "STAGE_TRACKER_ACTED_LABELS"), + jsConstLine(t, html, "STAGE_TRACKER_ACTED_STATES"), + jsConstLine(t, html, "STAGE_TRACKER_ACTED_FILTERS"), + jsConstLine(t, html, "STAGE_TRACKER_ACTED_STUCK_DEFAULT_S"), + jsConstLine(t, html, "STAGE_TRACKER_ACTED_GLYPH"), + jsConstBlock(t, html, "STAGE_TRACKER_ACTED_PLAIN"), + jsFunc(t, html, "stageTrackerActedLabel"), + jsFunc(t, html, "stageTrackerActedSource"), + jsFunc(t, html, "stageTrackerActedState"), + jsFunc(t, html, "stageTrackerActedAgo"), + jsFunc(t, html, "stageTrackerActedOutcomeWords"), + jsFunc(t, html, "stageTrackerActedStageName"), + jsFunc(t, html, "stageTrackerActedPlain"), + jsFunc(t, html, "stageTrackerActedTip"), + jsFunc(t, html, "stageTrackerActedBadgeHtml"), + jsFunc(t, html, "stageTrackerActedMatches"), + }, "\n") +} diff --git a/src/pkg/dashboard/stage_tracker_attention_order_test.go b/src/pkg/dashboard/stage_tracker_attention_order_test.go index 9de02cda8e..8078961453 100644 --- a/src/pkg/dashboard/stage_tracker_attention_order_test.go +++ b/src/pkg/dashboard/stage_tracker_attention_order_test.go @@ -119,6 +119,7 @@ func TestStageTrackerAttentionOrderJS(t *testing.T) { jsFunc(t, html, "stageTrackerRegressionHandled"), jsFunc(t, html, "stageTrackerNeedsAttention"), jsFunc(t, html, "stageTrackerWaitSince"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerNormalizeFilter"), jsFunc(t, html, "stageTrackerSort"), }, "\n") + ` diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index b6ec46ab7e..b8fc64ca8e 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -439,6 +439,7 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsFunc(t, html, "stageTrackerChipsHtml"), jsFunc(t, html, "stageTrackerHeadColsHtml"), jsFunc(t, html, "stageTrackerSinceHtml"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerSubRowHtml"), jsConstLine(t, html, "STAGE_TRACKER_LINKED_TIP"), jsFunc(t, html, "stageTrackerSharedPRs"), @@ -554,6 +555,7 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerChipsHtml"), jsFunc(t, html, "stageTrackerHeadColsHtml"), jsFunc(t, html, "stageTrackerSinceHtml"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerSubRowHtml"), jsConstLine(t, html, "STAGE_TRACKER_LINKED_TIP"), jsFunc(t, html, "stageTrackerSharedPRs"), diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index ff87da8b61..81ba3baa0c 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -122,6 +122,7 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { "var _stageTrackerFilter = stageTrackerDefaultFilter();", jsFunc(t, html, "stageTrackerWaitSince"), jsFunc(t, html, "stageTrackerLabelFamily"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerNormalizeFilter"), jsFunc(t, html, "stageTrackerFilterActive"), jsFunc(t, html, "stageTrackerMatches"), diff --git a/src/pkg/dashboard/stage_tracker_ui_test.go b/src/pkg/dashboard/stage_tracker_ui_test.go index 3b85b11118..137a9134e1 100644 --- a/src/pkg/dashboard/stage_tracker_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_test.go @@ -129,6 +129,7 @@ func TestStageTrackerRows(t *testing.T) { jsFunc(t, html, "stageTrackerItemNeedsHuman"), jsFunc(t, html, "stageTrackerLabelCompare"), jsFunc(t, html, "stageTrackerLabelDialogData"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerNormalizeFilter"), jsFunc(t, html, "stageTrackerFilterActive"), jsFunc(t, html, "stageTrackerMatches"), @@ -849,6 +850,7 @@ func TestStageTrackerFilterSortPage(t *testing.T) { jsFunc(t, html, "stageTrackerItemNeedsHuman"), jsFunc(t, html, "stageTrackerLabelCompare"), jsFunc(t, html, "stageTrackerLabelDialogData"), + stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerNormalizeFilter"), jsFunc(t, html, "stageTrackerFilterActive"), jsFunc(t, html, "stageTrackerMatches"), From 2b56462fd18e686dfa014bda62717c541d2b3b70 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 13:18:36 -0400 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=8C=B1=20Decision=20badge:=20keep=20.?= =?UTF-8?q?config-info=20rule=20discoverable;=20feed=20the=20tracker=20nod?= =?UTF-8?q?e=20fixture=20via=20stdin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cssRule() finds the first ".config-info {" so the badge override is spelled .config-info.ham-acted; TestStageTrackerRows' lifted script outgrew one argv entry (E2BIG) and now arrives on stdin. Signed-off-by: Andrew Anderson --- src/pkg/dashboard/stage_tracker_acted.test.js | 2 +- src/pkg/dashboard/static/index.html | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/pkg/dashboard/stage_tracker_acted.test.js b/src/pkg/dashboard/stage_tracker_acted.test.js index c10547517b..d51b0eb4a2 100644 --- a/src/pkg/dashboard/stage_tracker_acted.test.js +++ b/src/pkg/dashboard/stage_tracker_acted.test.js @@ -137,7 +137,7 @@ test('toolbar carries the Decisions select and the filter plumbing knows `acted` assert.match(html, /acted: 'any', sort: 'furthest'/); assert.match(html, /setVal\('activity-monitor-acted', f\.acted\);/); assert.match(html, /case 'acted': f\.acted = value \|\| 'any'; break;/); - assert.match(html, /\.ham-acted\.ham-acted-stuck\.config-info \{[^}]*var\(--yellow\)/); + assert.match(html, /\.config-info\.ham-acted\.ham-acted-stuck \{[^}]*var\(--yellow\)/); }); test('decision trail: the hive moves that followed are listed in order, in plain words', () => { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 9e74c59568..512e8ed314 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1504,13 +1504,13 @@ the action failed, dotted while the hive is still deciding. It rides the shared .config-info tooltip portal, so the circle recipe is undone here in favour of the pill. */ - .ham-acted.config-info { width: auto; height: auto; min-width: 1.6em; border-radius: var(--r-pill); margin-left: 0; padding: 0 var(--sp-2); background: color-mix(in srgb, var(--green) 14%, transparent); border-color: color-mix(in srgb, var(--green) 55%, transparent); color: var(--green); font-size: var(--fs-xs); font-weight: 600; cursor: help; } - .ham-acted.config-info:hover, .ham-acted.config-info:focus-visible { background: var(--green); border-color: var(--green); color: var(--bg); } - .ham-acted.ham-acted-stuck.config-info { background: color-mix(in srgb, var(--yellow) 16%, transparent); border-color: color-mix(in srgb, var(--yellow) 60%, transparent); color: var(--yellow); } - .ham-acted.ham-acted-stuck.config-info:hover, .ham-acted.ham-acted-stuck.config-info:focus-visible { background: var(--yellow); border-color: var(--yellow); color: var(--bg); } - .ham-acted.ham-acted-failed.config-info { background: color-mix(in srgb, var(--red) 14%, transparent); border-color: color-mix(in srgb, var(--red) 55%, transparent); color: var(--red); } - .ham-acted.ham-acted-failed.config-info:hover, .ham-acted.ham-acted-failed.config-info:focus-visible { background: var(--red); border-color: var(--red); color: var(--bg); } - .ham-acted.ham-acted-pending.config-info { border-style: dotted; color: var(--text-muted); background: transparent; } + .config-info.ham-acted { width: auto; height: auto; min-width: 1.6em; border-radius: var(--r-pill); margin-left: 0; padding: 0 var(--sp-2); background: color-mix(in srgb, var(--green) 14%, transparent); border-color: color-mix(in srgb, var(--green) 55%, transparent); color: var(--green); font-size: var(--fs-xs); font-weight: 600; cursor: help; } + .config-info.ham-acted:hover, .config-info.ham-acted:focus-visible { background: var(--green); border-color: var(--green); color: var(--bg); } + .config-info.ham-acted.ham-acted-stuck { background: color-mix(in srgb, var(--yellow) 16%, transparent); border-color: color-mix(in srgb, var(--yellow) 60%, transparent); color: var(--yellow); } + .config-info.ham-acted.ham-acted-stuck:hover, .config-info.ham-acted.ham-acted-stuck:focus-visible { background: var(--yellow); border-color: var(--yellow); color: var(--bg); } + .config-info.ham-acted.ham-acted-failed { background: color-mix(in srgb, var(--red) 14%, transparent); border-color: color-mix(in srgb, var(--red) 55%, transparent); color: var(--red); } + .config-info.ham-acted.ham-acted-failed:hover, .config-info.ham-acted.ham-acted-failed:focus-visible { background: var(--red); border-color: var(--red); color: var(--bg); } + .config-info.ham-acted.ham-acted-pending { border-style: dotted; color: var(--text-muted); background: transparent; } .ham-acted-tip { white-space: normal; text-align: left; font-weight: 400; } /* Sentinel-flagged PR, #13535 follow-up: the chip beside needs rebase / regressed, and the human-decision chevron itself when its word From d7f4046a34f3ffb0a261f1521d640001ada382aa Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 14:19:10 -0400 Subject: [PATCH 4/5] =?UTF-8?q?=F0=9F=93=96=20api-reference:=20refresh=20c?= =?UTF-8?q?itations=20after=20rebase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/docs/api-reference.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 723201fc54..83c4fe36d4 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -13,17 +13,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)) | `pkg/dashboard/api.go:42` | | `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:43` | | `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:64` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1526` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1527` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1528` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1534` | -| `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}` is the governor strip's `running N · $X this hour` figure; `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) | `pkg/dashboard/server.go:1539` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1540` | -| `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:1541` | -| `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:1542` | -| `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:1543` | -| `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:1544` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1545` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1530` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1531` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1532` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1538` | +| `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}` is the governor strip's `running N · $X this hour` figure; `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) | `pkg/dashboard/server.go:1543` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1544` | +| `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:1545` | +| `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:1546` | +| `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:1547` | +| `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:1548` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1549` | | `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` | @@ -66,7 +66,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:44` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1606` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1610` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:77` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:78` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:79` | @@ -94,9 +94,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1546` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1547` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1548` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1550` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1551` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1552` | ## Configuration @@ -595,7 +595,7 @@ always resolved server-side from the validated token. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:275` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:276` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:277` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1553` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1557` | ## Hub SaaS From 19b04bae344af043251db425d26d7678fa4099fd Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 14:32:27 -0400 Subject: [PATCH 5/5] =?UTF-8?q?=E2=9C=A8=20Decision=20badge:=20record=20an?= =?UTF-8?q?d=20explain=20no-op=20row=20actions;=20fix=20scale-envelope=20c?= =?UTF-8?q?itation=20drift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - settle let-hive-decide records on the delegated no-op path (was left pending) - derive outcome=no-op with a plain-words detail from the shared RowActionResult (what hive had already decided, when, what still blocks it) - tooltip: 'nothing changed: …' plus the remaining enabled options from decision_needed - translate lane slugs embedded in sentences; add Go + node no-op tests - scale-envelope.md: drop stale AgeMinutes anchor (pre-existing drift breaking the docs job) Signed-off-by: Andrew Anderson --- src/docs/scale-envelope.md | 2 +- .../api_repo_item_decide_delegated.go | 3 ++ src/pkg/dashboard/operator_actions.go | 38 +++++++++++++++++++ src/pkg/dashboard/operator_actions_test.go | 23 +++++++++++ src/pkg/dashboard/stage_tracker_acted.test.js | 21 ++++++++++ src/pkg/dashboard/static/index.html | 23 +++++++++-- 6 files changed, 106 insertions(+), 4 deletions(-) diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index b270ef9fc3..23427912bd 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:4772-4782`, descending `AgeMinutes`). + (`RankActionableIssues`, `src/pkg/github/client.go:4772-4782`, oldest first within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index fce0c4a9d1..e338e5238d 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -276,6 +276,9 @@ func (s *Server) runDelegatedDecision(ctx context.Context, key, repoFull string, j.Result = &res j.Status = delegatedJobStatusDone }) + if done, ok := s.delegatedJobs.get(key); ok { + s.settleOperatorAction(repoFull, number, &done) + } s.audit.LogRecord(user, auditRepoItemDecisionDelegated, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", itemType, "verdict", string(d.Verdict), "rule", d.Rule, "actions", "", "noop", "already-applied", "policy", delegatedecision.PolicyName, "decision", d.Text), "", repoFull, number) return diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go index 369669b82d..33cd290edb 100644 --- a/src/pkg/dashboard/operator_actions.go +++ b/src/pkg/dashboard/operator_actions.go @@ -335,6 +335,19 @@ func operatorActionOutcome(status int, body []byte) (outcome, detail, head strin detail = strings.Join(parts, ", ") } } + if res, ok := resp["result"].(map[string]any); ok { + if action, _ := res["action"].(string); action == rowActionNoop { + verdict := "" + if d, ok := resp["decision"].(map[string]any); ok { + verdict, _ = d["verdict"].(string) + } + var rr RowActionResult + if raw, err := json.Marshal(res); err == nil { + _ = json.Unmarshal(raw, &rr) + } + return operatorActionOutcomeNoOp, operatorActionNoopDetail(verdict, &rr), head, true + } + } if d, ok := resp["decision"].(map[string]any); ok && status == http.StatusOK { if v, _ := d["verdict"].(string); v != "" { detail = "hive decided: " + v @@ -447,6 +460,13 @@ func (s *Server) settleOperatorAction(repoFull string, number int, job *delegate detail += " — kept for the owner" } } + if job.Result != nil && job.Result.Action == rowActionNoop { + verdict := "" + if job.Decision != nil { + verdict = string(job.Decision.Verdict) + } + outcome, detail = operatorActionOutcomeNoOp, operatorActionNoopDetail(verdict, job.Result) + } if job.Status == delegatedJobStatusFailed { outcome, detail = operatorActionOutcomeFailed, job.Error } @@ -456,6 +476,24 @@ func (s *Server) settleOperatorAction(repoFull string, number int, job *delegate s.invalidateStageTrackerCache() } +// operatorActionNoopDetail spells a repeat decision out in plain words: +// what the hive had already decided, when, and what still blocks it. +func operatorActionNoopDetail(verdict string, res *RowActionResult) string { + out := "the hive had already decided" + if verdict != "" { + out += " '" + verdict + "'" + } + if res != nil && res.AppliedAt != nil && !res.AppliedAt.IsZero() { + out += " at " + res.AppliedAt.UTC().Format("15:04 UTC") + } + if res != nil { + if b, ok := strings.CutPrefix(res.Next, "Still blocked by "); ok { + out += " and it has not taken effect — still blocked: " + strings.TrimSuffix(b, ".") + } + } + return out +} + // StageTrackerOperatorAction is the row-payload view of the newest recorded // action: the record plus what the tracker can say about it now. type StageTrackerOperatorAction struct { diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index 4063840e7a..42d31e3da6 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/hivecommons/hive/pkg/delegatedecision" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -89,6 +90,7 @@ func TestOperatorActionOutcome(t *testing.T) { {200, `{"ok":true,"alreadyAccepted":true}`, operatorActionOutcomeNoOp, "already accepted", "", true, "accept-triage twice"}, {200, `{"ok":true,"released":["hold","needs-human"]}`, operatorActionOutcomeApplied, "hold, needs-human", "", true, "release"}, {200, `{"status":"done","decision":{"verdict":"approve","rule":"auto-merge"}}`, operatorActionOutcomeApplied, "hive decided: approve (auto-merge)", "", true, "delegated sync done"}, + {200, `{"status":"done","decision":{"verdict":"supersede","rule":"dup"},"result":{"action":"noop-already-applied","outcome":"No change — superseded at 2026-10-28T13:01:00Z","applied_at":"2026-10-28T13:01:00Z","next":"Still blocked by contributor-lane:changes-requested."}}`, operatorActionOutcomeNoOp, "the hive had already decided 'supersede' at 13:01 UTC and it has not taken effect — still blocked: contributor-lane:changes-requested", "", true, "delegated sync no-op"}, {200, `{"status":"failed","error":"boom","decision":{"verdict":""}}`, operatorActionOutcomeFailed, "boom", "", true, "delegated sync failed"}, {202, `{"status":"running"}`, operatorActionOutcomePending, "running", "", true, "delegated async"}, {409, `{"error":"not parked"}`, operatorActionOutcomeNoOp, "not parked", "", true, "conflict"}, @@ -104,6 +106,25 @@ func TestOperatorActionOutcome(t *testing.T) { } } +func TestSettleOperatorActionNoOp(t *testing.T) { + s := &Server{operatorActionStore: newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json"))} + at := time.Date(2026, 10, 28, 14, 23, 0, 0, time.UTC) + if err := s.operatorActions().Record("org/repo", 14822, OperatorAction{Action: operatorActionLetHiveDecide, Actor: "clubanderson", At: at, Outcome: operatorActionOutcomePending, Stage: 85}); err != nil { + t.Fatal(err) + } + res := rowActionNoopResult(rowActionTarget("org/repo", rowActionTargetPR, 14822), "superseded", at.Add(-82*time.Minute), "contributor-lane:changes-requested") + job := &delegatedDecisionJob{Status: delegatedJobStatusDone, Decision: &delegatedecision.Decision{Verdict: "supersede", Rule: "dup"}, Result: &res} + s.settleOperatorAction("org/repo", 14822, job) + got := s.operatorActions().List("org/repo", 14822) + if len(got) != 1 || got[0].Outcome != operatorActionOutcomeNoOp { + t.Fatalf("settle no-op = %+v", got) + } + want := "the hive had already decided 'supersede' at 13:01 UTC and it has not taken effect — still blocked: contributor-lane:changes-requested" + if got[0].Detail != want { + t.Fatalf("detail = %q\nwant %q", got[0].Detail, want) + } +} + func TestStageTrackerOperatorActionStates(t *testing.T) { now := time.Date(2026, 10, 28, 16, 0, 0, 0, time.UTC) window := 30 * time.Minute @@ -268,6 +289,8 @@ func stageTrackerActedJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerActedOutcomeWords"), jsFunc(t, html, "stageTrackerActedStageName"), jsFunc(t, html, "stageTrackerActedPlain"), + jsConstLine(t, html, "STAGE_TRACKER_ACTED_OPTION_ID"), + jsFunc(t, html, "stageTrackerActedOptions"), jsFunc(t, html, "stageTrackerActedTip"), jsFunc(t, html, "stageTrackerActedBadgeHtml"), jsFunc(t, html, "stageTrackerActedMatches"), diff --git a/src/pkg/dashboard/stage_tracker_acted.test.js b/src/pkg/dashboard/stage_tracker_acted.test.js index d51b0eb4a2..582965a93d 100644 --- a/src/pkg/dashboard/stage_tracker_acted.test.js +++ b/src/pkg/dashboard/stage_tracker_acted.test.js @@ -38,6 +38,8 @@ const src = [ pick(/function stageTrackerActedStageName\(n\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedStageName'), pick(/const STAGE_TRACKER_ACTED_PLAIN = \{[\s\S]*?\n \};\n/, 'STAGE_TRACKER_ACTED_PLAIN'), pick(/function stageTrackerActedPlain\(text\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedPlain'), + pick(/const STAGE_TRACKER_ACTED_OPTION_ID = [^\n]*\n/, 'STAGE_TRACKER_ACTED_OPTION_ID'), + pick(/function stageTrackerActedOptions\(item, action, state\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedOptions'), pick(/function stageTrackerActedTip\(item, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedTip'), pick(/function stageTrackerActedBadgeHtml\(item, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedBadgeHtml'), pick(/function stageTrackerActedMatches\(item, mode, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerActedMatches'), @@ -161,3 +163,22 @@ test('plain words: no slugs or codes reach the operator', () => { assert.strictEqual(api.plain('Waiting on CI'), 'Waiting on CI'); assert.strictEqual(api.plain(''), ''); }); + +test('no-op outcome still shows the badge and says what hive had already decided plus the remaining options', () => { + const a = act({ action: 'let-hive-decide', outcome: 'no-op', detail: "the hive had already decided 'supersede' at 13:01 UTC and it has not taken effect — still blocked: contributor-lane:changes-requested" }); + const item = { number: 14822, kind: 'pr', stage: 85, modifiers: [], last_operator_action: a, operator_action_count: 1, + decision_needed: { question: 'Merge or send back?', options: [ + { action: 'decide:delegate', label: 'Let hive decide', enabled: true }, + { action: 'decide:approve', label: 'Merge as maintainer', enabled: true }, + { action: 'decide:direction', label: 'Send back for a new commit', enabled: true }, + { action: 'hold', label: 'Hold', enabled: false, reason_if_disabled: 'already held' }, + ] } }; + const html = api.badge(item, NOW); + assert.match(html, /ham-acted/, 'badge renders for a no-op'); + const tip = api.tip(item, NOW); + assert.match(tip, /You chose Let hive decide/); + assert.match(tip, /nothing changed: the hive had already decided 'supersede' at 13:01 UTC/); + assert.match(tip, /still blocked: a reviewer requested changes; needs a new commit/, 'lane slug translated to plain words'); + assert.doesNotMatch(tip, /contributor-lane/); + assert.match(tip, /Options: Merge as maintainer · Send back for a new commit\./, 'offers the other enabled options, not the one just taken nor disabled ones'); +}); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 512e8ed314..30a37b4b35 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14640,7 +14640,7 @@

Where to get help

if (item.last_operator_action) return { item, action: item.last_operator_action, count: Number(item.operator_action_count) || 1 }; const linked = Array.isArray(item.linked_prs) ? item.linked_prs : []; if (item.kind === 'issue' && linked.length === 1 && linked[0].last_operator_action) { - return { item: { repo: item.repo, number: linked[0].number, kind: 'pr', stage: linked[0].stage || 0, modifiers: linked[0].modifiers || [], reason: linked[0].reason || '', caption: linked[0].caption || '' }, action: linked[0].last_operator_action, count: Number(linked[0].operator_action_count) || 1 }; + return { item: { repo: item.repo, number: linked[0].number, kind: 'pr', stage: linked[0].stage || 0, modifiers: linked[0].modifiers || [], reason: linked[0].reason || '', caption: linked[0].caption || '', decision_needed: linked[0].decision_needed || null }, action: linked[0].last_operator_action, count: Number(linked[0].operator_action_count) || 1 }; } return null; } @@ -14669,7 +14669,7 @@

Where to get help

function stageTrackerActedOutcomeWords(action) { switch (action.outcome) { case 'applied': return 'done' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); - case 'no-op': return 'nothing to change' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); + case 'no-op': return 'nothing changed' + (action.detail ? ': ' + stageTrackerActedPlain(action.detail) : ''); case 'failed': return 'failed' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'pending': return 'the hive is deciding…'; case 'superseded-by-state-change': return 'the item moved on by itself'; @@ -14704,7 +14704,22 @@

Where to get help

if (!t) return ''; if (STAGE_TRACKER_ACTED_PLAIN[t]) return STAGE_TRACKER_ACTED_PLAIN[t]; if (/^hive decided: /.test(t)) return t.replace(/^hive decided: /, 'the hive decided: ').replace(/ \(([^)]+)\)/, (m, r) => ' (rule: ' + r.replace(/[-_:]/g, ' ') + ')'); - return /^[a-z0-9]+([-_:][a-z0-9]+)+$/.test(t) ? t.replace(/[-_:]/g, ' ') : t; + if (/^[a-z0-9]+([-_:][a-z0-9]+)+$/.test(t)) return t.replace(/[-_:]/g, ' '); + // Slugs inside a sentence ("… — contributor-lane:changes-requested blocks it"). + return t.replace(/\b[a-z0-9]+(?:[-_:][a-z0-9]+)+\b/g, m => STAGE_TRACKER_ACTED_PLAIN[m] || (/[a-z]/.test(m) ? m.replace(/[-_:]/g, ' ') : m)); + } + // Row-menu action id each ledger action was submitted under, so the + // option the owner just took is not offered back to them. + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'accept-triage': 'accept-triage', hold: 'hold' }; + // Pure: what the owner can still do when their action changed nothing + // (no-op) or the item has not moved (stuck): the enabled options from + // the row's decision_needed payload, minus the one just taken. + function stageTrackerActedOptions(item, action, state) { + if (!(action.outcome === 'no-op' || state === 'stuck' || state === 'failed')) return ''; + const dn = item && item.decision_needed; + const opts = dn && Array.isArray(dn.options) ? dn.options : []; + const taken = STAGE_TRACKER_ACTED_OPTION_ID[action.action] || ''; + return opts.filter(o => o && o.enabled && o.action !== taken && o.label).map(o => o.label).join(' · '); } // Pure: the tooltip — the decision trail in plain words, in the order // every cue on the row uses: what it is waiting on → what you chose → @@ -14730,6 +14745,8 @@

Where to get help

else lines.push('At ' + stageNow + (waitingOn ? ' — ' + waitingOn : '') + '.'); lines.push(who + ' chose ' + label + ' · ' + agentNowClockTime(atMs, nowMs) + ' (' + ago + ') · ' + stageTrackerActedOutcomeWords(a) + '.'); if (a.note) lines.push('Your note: ' + a.note); + const options = stageTrackerActedOptions(src.item, a, state); + if (options) lines.push('Options: ' + options + '.'); const followed = Array.isArray(a.followed) ? a.followed : []; followed.slice(-3).forEach(h => { const hopMs = Date.parse(h.at || '') || nowMs;