From 626f1bce390512a1af5e5b6e32859408b2af3973 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 20:42:26 -0500 Subject: [PATCH 01/11] =?UTF-8?q?=E2=9C=A8=20ask:=20hub=20backend=20for=20?= =?UTF-8?q?optional=20Ask=20AI=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the ask config block and HIVE_ASK_* env (off by default, inert when unconfigured, key only from a file under the allowed secret dirs), the pkg/askai service (Kapa Chat API client pinned to the published QueryResponse schema, per-person consent store, credential-shape refusal, source allowlist, plain-text answers, per-person/per-hive/hub-wide limits, circuit breaker, content-free audit lines) and the hub routes GET /api/ask/status, PUT/DELETE /api/ask/consent, POST /api/ask and GET /api/ask/stats. Routes are registered only when the feature is on. Fixes #19180 Signed-off-by: Andy Anderson --- changelog.d/added-19180-ask-hub-backend.md | 1 + src/docs/api-reference/hub-saas.md | 5 + src/docs/env-vars.md | 14 + src/docs/hub-deployment.md | 65 ++++ src/docs/telemetry.md | 1 + src/pkg/askai/breaker.go | 103 ++++++ src/pkg/askai/consent.go | 183 ++++++++++ src/pkg/askai/kapa.go | 199 +++++++++++ src/pkg/askai/kapa_test.go | 144 ++++++++ src/pkg/askai/limits.go | 178 +++++++++ src/pkg/askai/sections.go | 69 ++++ src/pkg/askai/service.go | 323 +++++++++++++++++ src/pkg/askai/service_test.go | 398 +++++++++++++++++++++ src/pkg/askai/sources.go | 151 ++++++++ src/pkg/askai/store_test.go | 122 +++++++ src/pkg/askai/threads.go | 102 ++++++ src/pkg/config/ask.go | 339 ++++++++++++++++++ src/pkg/config/ask_test.go | 126 +++++++ src/pkg/hub/ask.go | 289 +++++++++++++++ src/pkg/hub/ask_test.go | 246 +++++++++++++ src/pkg/hub/saas.go | 1 + src/pkg/hub/saas_users_admin.go | 4 + src/pkg/hub/server.go | 1 + 23 files changed, 3064 insertions(+) create mode 100644 changelog.d/added-19180-ask-hub-backend.md create mode 100644 src/pkg/askai/breaker.go create mode 100644 src/pkg/askai/consent.go create mode 100644 src/pkg/askai/kapa.go create mode 100644 src/pkg/askai/kapa_test.go create mode 100644 src/pkg/askai/limits.go create mode 100644 src/pkg/askai/sections.go create mode 100644 src/pkg/askai/service.go create mode 100644 src/pkg/askai/service_test.go create mode 100644 src/pkg/askai/sources.go create mode 100644 src/pkg/askai/store_test.go create mode 100644 src/pkg/askai/threads.go create mode 100644 src/pkg/config/ask.go create mode 100644 src/pkg/config/ask_test.go create mode 100644 src/pkg/hub/ask.go create mode 100644 src/pkg/hub/ask_test.go diff --git a/changelog.d/added-19180-ask-hub-backend.md b/changelog.d/added-19180-ask-hub-backend.md new file mode 100644 index 0000000000..4e3dc2e1d7 --- /dev/null +++ b/changelog.d/added-19180-ask-hub-backend.md @@ -0,0 +1 @@ +- Hub operators can enable an optional Ask AI help backend that answers docs questions server side through the Kapa.ai Chat API: per-person consent, credential-shaped questions refused, only allowlisted cited sources, per-person and hub-wide limits, a circuit breaker and content-free audit lines. Off by default and inert until a key file, project id and integration id are configured; no panel yet ([#19180](https://github.com/hivecommons/hive/issues/19180)). diff --git a/src/docs/api-reference/hub-saas.md b/src/docs/api-reference/hub-saas.md index 3e39ebb680..5fb89d1f6f 100644 --- a/src/docs/api-reference/hub-saas.md +++ b/src/docs/api-reference/hub-saas.md @@ -111,3 +111,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/saas/admin/key-generations` | Hub admin | Token-Crypto Key Generations | `pkg/hub/saas.go:489` | | `POST` | `/api/saas/admin/rotate-master-key` | Hub admin | Rotate Token Master Key (double-call refused) | `pkg/hub/saas.go:490` | | `GET` | `/api/saas/admin/advisory-diagnostics` | Hub admin | Fleet Advisory/App-State Diagnostics | `pkg/hub/saas.go:516` | +| `GET` | `/api/ask/status` | Hub auth | Browser session only (no bearer, no impersonation). Ask AI help status for the signed-in person: `enabled`, `text_version`, `disclosure`, `consented`, `docs_url`, `ai_label`. Registered only when `HIVE_ASK_ENABLED` is on and fully configured; otherwise `404`. Never returns the vendor key, project id or integration id. See [Ask AI help](../hub-deployment.md#ask-ai-help) | `pkg/hub/ask.go:123` | +| `PUT` | `/api/ask/consent` | Hub auth | Browser session only. Record the person's consent to the Ask disclosure: body `{text_version}`; `409` when the page showed an older text; `204` on success. One audit line, no text | `pkg/hub/ask.go:124` | +| `DELETE` | `/api/ask/consent` | Hub auth | Browser session only. Withdraw Ask consent; takes effect on the next request; `204` | `pkg/hub/ask.go:125` | +| `POST` | `/api/ask` | Hub auth | Browser session only. Ask a docs-help question: body `{question, section?, conversation?}` (`section` is an id from the closed list in `pkg/askai/sections.go`; `conversation` is the opaque handle from the previous answer). Always `200` with `{outcome, answer?, sources[]?, uncertain?, conversation?, retry_after_seconds?, message?, ai_generated, docs_url}`; `outcome` is one of `ok`, `no_cited_answer`, `refused_secret_shape`, `rate_limited`, `breaker_open`, `upstream_error`, `not_consented`, `invalid_question`. Only the question and the section label are sent to Kapa.ai | `pkg/hub/ask.go:126` | +| `GET` | `/api/ask/stats` | Hub admin | Ask cost view: counts by outcome, today's total against the daily budget, breaker state, effective limits. No per-person data | `pkg/hub/ask.go:127` | diff --git a/src/docs/env-vars.md b/src/docs/env-vars.md index aa0267c1e0..e8d92339f3 100644 --- a/src/docs/env-vars.md +++ b/src/docs/env-vars.md @@ -94,6 +94,20 @@ behavior. [Maintenance limitations](#keeping-this-reference-current) still apply | `HIVE_HUB_SECRET` | Required for spokes registered to a protected hub; optional for a standalone hub with `/data/saas/hub-secret.key` | `/data/saas/hub-secret.key` on the hub when present; no fallback for spoke heartbeat auth | Bearer secret for spoke heartbeats and hub/spoke SaaS APIs. Self-hosted (`byo-`) hives registered through self-service never receive it: they hold only their own `HIVE_HEARTBEAT_KEY`, and the hub never tries `HIVE_HUB_SECRET` or anything derived from it for a `byo-` ID. | | `HIVE_HUB_SELFSERVICE_REGISTRATION` | No | off | Enables the self-service registration API (`/api/hub/selfservice/*`) that lets a signed-in user register a hive they run themselves under the reserved `byo---` ID namespace, after proving `permissions.admin` on every listed repo with their own GitHub token ([#18060](https://github.com/hivecommons/hive/issues/18060)). Accepts `1/true/yes/on`. When off, every route but `GET /api/hub/selfservice/status` answers `404` and the status reports `enabled: false`. Read per request; no restart needed. | | `HIVE_HUB_CUSTOMERS_SHARE_ENABLED` | No | off | Enables the hub's signed-in profile-sharing page and API for per-person, per-hive consent. Accepts `1/true/yes/on`. This phase sends no profile data to hives. See [Customer profile sharing](hub-deployment.md#customer-profile-sharing). | +| `HIVE_ASK_ENABLED` | No | off | Switches on Ask AI help ([#19177](https://github.com/hivecommons/hive/issues/19177)). Accepts `1/true/yes/on`. Inert until the Kapa values below are also set; a missing or unreadable value keeps it off with one warning that names no value. See [Ask AI help](hub-deployment.md#ask-ai-help). | +| `HIVE_ASK_MODE` | No | `off` | `off`, `direct` (this process calls Kapa.ai with its own key) or `hub` (a hosted hive uses the hub relay). The hub is always `direct` and ignores it. | +| `HIVE_ASK_KAPA_PROJECT_ID` | With Ask on in direct mode | none | Kapa.ai project id. Configuration only; never in the repo, never logged or returned by an API. | +| `HIVE_ASK_KAPA_INTEGRATION_ID` | With Ask on in direct mode | none | Kapa.ai HTTP API integration id. Configuration only; never logged or returned by an API. | +| `HIVE_ASK_KAPA_API_KEY_FILE` | With Ask on in direct mode | none | Path to the Kapa.ai API key file, under `/secrets` or `/data/secrets`, mounted from a Secret. A path elsewhere is never read. Secret. | +| `HIVE_ASK_SEND_SECTION_LABEL` | No | on | Whether the label of the dashboard section the person is in (from a closed list of our own ids) accompanies the question. | +| `HIVE_ASK_LIMIT_PERSON_PER_MINUTE` | No | `3` | Ask requests one person may make per minute. | +| `HIVE_ASK_LIMIT_PERSON_PER_HOUR` | No | `20` | Ask requests one person may make per hour. | +| `HIVE_ASK_LIMIT_HIVE_PER_HOUR` | No | `60` | Relayed Ask requests one hive may make per hour on the hub. | +| `HIVE_ASK_LIMIT_GLOBAL_PER_MINUTE` | No | `4` | Ask requests per minute across the whole process; capped at `10`, half the vendor's per-team limit of 20 a minute. | +| `HIVE_ASK_LIMIT_IN_FLIGHT` | No | `2` | Ask requests in flight at once across the process. | +| `HIVE_ASK_LIMIT_DAILY` | No | `500` | Ask requests per day across the process; when spent, the panel shows the docs link until the window resets. | +| `HIVE_ASK_RELAY_HIVES` | No | `hosted` | Hub only: which hives may use the Ask relay, `none` or `hosted` (`registered` is accepted and treated as `hosted` in this round). | +| `HIVE_ASK_RELAY_DISABLED_HIVES` | No | none | Hub only: comma-separated hive ids the Ask relay refuses. | | `HIVE_HUB_MAIL_TOKEN` | Only on a hub that routes mail from `hive-mx` | none | Bearer token `hive-mx` presents on `GET /api/mail/hosts` and `POST /api/mail/inbound` ([#18395](https://github.com/hivecommons/hive/issues/18395)); the same value as the `hive-mx` Secret. Unset: both endpoints answer `404`. Read per request. Secret. | | `HIVE_HUB_MAIL_MAX_BODY_BYTES` | No | `50331648` | Largest delivery `POST /api/mail/inbound` accepts from a `hive-mx` that sends routing headers (48 MiB, this route only; [#18564](https://github.com/hivecommons/hive/issues/18564)). Without routing headers the cap stays 8 MiB. | | `HIVE_HUB_MAIL_CHUNK_BYTES` | No | `786432` | Piece size when the hub relays a large mail-in delivery to the spoke (768 KiB, under the 1 MiB ingress default); clamped to 64 KiB to 8 MiB. | diff --git a/src/docs/hub-deployment.md b/src/docs/hub-deployment.md index 434ef38f74..2e6b774c98 100644 --- a/src/docs/hub-deployment.md +++ b/src/docs/hub-deployment.md @@ -102,6 +102,71 @@ administrator-entered, and inferred values are not eligible for sharing. A material disclosure change requires reconfirmation. This phase records consent on the hub only and does not send any profile fields to hives. +### Ask AI help + +Ask AI help is an optional docs-help backend for the hub dashboard (design: +[Dashboard Ask AI help](design/dashboard-ask-ai-help.md)). It is off by +default. With it off, or switched on but missing a value, the hub registers no +Ask route, reads no key and sends nothing. The hub calls the Kapa.ai Chat API +itself, server side; the browser only ever talks to the hub, and no +third-party script or Content-Security-Policy change is involved. + +To wire it once a Kapa API key exists: + +1. In the Kapa project, create an HTTP API integration and an API key. Keep + both out of the repository. +2. Store the key in a Kubernetes Secret and mount it under one of the allowed + secret dirs (`/secrets` or `/data/secrets`), for example: + + ```sh + kubectl -n create secret generic hive-ask-kapa \ + --from-file=api-key= + ``` + + and add a volume plus `volumeMounts: [{name: hive-ask-kapa, mountPath: /secrets/kapa, readOnly: true}]` + to the hub Deployment. +3. Set the hub environment: + + ```yaml + env: + - name: HIVE_ASK_ENABLED + value: "true" + - name: HIVE_ASK_KAPA_PROJECT_ID + value: + - name: HIVE_ASK_KAPA_INTEGRATION_ID + value: + - name: HIVE_ASK_KAPA_API_KEY_FILE + value: /secrets/kapa/api-key + ``` + + The project id and integration id may also come from the same Secret + through `valueFrom.secretKeyRef`. There is no env var that holds the key + itself. +4. Restart the hub. It logs `ask: enabled` with the effective limits, or one + `ask: requested but staying off` line with the reason. Neither line, nor any + API response, carries the key, the project id or the integration id. + +What leaves the hub per question: the question text (refused, not sent, when +it looks like a password, token or key), the label of the dashboard section +from a closed list of ids in `pkg/askai/sections.go` (set +`HIVE_ASK_SEND_SECTION_LABEL=false` to drop it), the integration id and, for a +follow-up, the vendor's thread id. No login, email, page content, URL, hive or +repo name is sent. Each person confirms a disclosure before their first +question and can withdraw; the record lives under `/data/saas/ask-consents/` +and is deleted with the user. Answers without an allowlisted source +(`docs.hivecommons.dev` or the GitHub docs path under `hivecommons/hive`) are +shown as "no cited answer" with a docs link. + +Limits (env overrides in [Environment variables](env-vars.md)): per person 3 a +minute, 20 an hour and one in flight; hub-wide 4 a minute (a fifth of the +vendor's 20 a minute per-team limit, and never more than half of it), 2 in +flight and 500 a day. A vendor `429` backs every caller off for its +`Retry-After`; three upstream failures in a row open a circuit breaker for five +minutes. Audit lines (`audit: ask request`, `audit: ask consent grant`, +`audit: ask consent withdraw`, `audit: ask breaker opened`, `audit: ask daily +budget spent`) carry outcomes and counts, never text. Hub admins can read the +counters at `GET /api/ask/stats`. + ### Reserved `byo-` hive IDs (credential fence) Hive IDs that start with `byo-` are reserved for hives that their owners run and register themselves ([#18060](https://github.com/hivecommons/hive/issues/18060)). A hub lists such a hive as directory metadata only, so its heartbeat response never carries hub-held credentials or management actions, whatever key the spoke authenticated with. The hub withholds these fields: the GitHub App config (including cluster, secondary and webhook relay keys), the pending gateway, the claimed project config, the cluster ID, the authorized-user list, visibility, upgrade and branch-switch instructions, the upgrade announcement and policy, spoke restarts, agent-restart resets, fleet-breaker instructions, and self-experiment flags. Display-only data such as admin banners still flows. When the fence withholds a field, the hub logs `heartbeat: credential fence withheld fields from self-service hive` with the field names, never the values. Do not give an operator-provisioned hive a `byo-` ID. diff --git a/src/docs/telemetry.md b/src/docs/telemetry.md index 9616a395b7..50a66a459b 100644 --- a/src/docs/telemetry.md +++ b/src/docs/telemetry.md @@ -12,6 +12,7 @@ Hive sends a small number of operational signals outside the running hive only t | Build-containment lookup | A commit SHA (the hive's running commit and the commit being asked about) or a PR number, sent as part of a GitHub REST `compare` or `pulls` request. Only when an operator runs a lookup (`GET /api/saas/build-contains` on the hub, `GET /api/version/contains` on a hive). No hive identifier, org, repo name or user is in the request. | `api.github.com`, the public `hivecommons/hive` repository, using the hub's read-only GitHub identity or the hive's own configured GitHub client. The answer is shown to the caller only. | On demand only; no background polling. A hive with no GitHub client answers `unknown` and sends nothing. | None stored; compare answers are cached in memory, for the life of the process. | Do not run the lookup; there is no setting because nothing is sent otherwise. | `src/pkg/buildcontains/buildcontains.go`; `src/pkg/hub/build_contains.go`; `src/pkg/dashboard/api_version_contains.go`. | | NPS prompt | Score 1-4, optional free text, hive ID, and dashboard version. The signed-in username is used only locally for rate limiting and is not sent. | Hub `POST /api/nps/ingest`, or an explicitly configured NPS relay for standalone hives; only hub admins can read stored responses. | Hosted spokes default on; self-hosted/federated/standalone default off. Standalone relay requires explicit `hub.nps_enabled`/`HIVE_NPS_ENABLED` and `hub.nps_relay_url`/`HIVE_NPS_RELAY_URL`. | Hub store keeps at most 1,000 responses per hive and 10,000 total, oldest dropped first. | `hub.nps_enabled: false` or `HIVE_NPS_ENABLED=false`; leave relay URL unset. | `src/docs/nps.md`; `src/docs/env-vars.md`; `src/pkg/dashboard/nps.go`; `src/pkg/hub/nps.go`. | | Hosted hub web analytics | GA4 page/event data from hub-hosted pages, including custom hub events such as hive creation/deletion. Existing event code includes hive IDs and creation inputs such as org, primary repo, ACMM level, and cluster ID. | Google Analytics via `www.googletagmanager.com`, property `G-4707R797K3`. | Loaded by hosted hub static HTML pages. This is website analytics, not spoke software telemetry, but it still needs privacy review because custom events may include project identifiers. | Google Analytics retention is controlled in the GA property, not in this repository. | Browser tracking protections or removing the hosted hub GA script; there is no repository config flag. | `src/pkg/hub/assets/dashboard.html`; `src/pkg/hub/saas_pages.go`; `src/pkg/hub/static/*.html` pages such as `reading.html` and `cncf-reference-architecture.html`. | +| Ask AI help (optional) | The question a signed-in person typed, after a credential-shape check that refuses rather than sends; the label of the dashboard section they are in, from a closed list of our own ids; the Kapa.ai integration id; and, for a follow-up, the vendor thread id. No login, email, page content, URL, hive, repo or agent name. | Kapa.ai Chat API (`api.kapa.ai`), called server side by the hub; the project's Kapa administrators can read questions in Kapa analytics. | Off by default (`HIVE_ASK_ENABLED`); inert until a key file, project id and integration id are configured; each person confirms a disclosure before their first question and can withdraw. | Kapa keeps conversations for the duration of the service; Hive stores no question or answer text, only the per-person consent record. | Leave `HIVE_ASK_ENABLED` unset, or withdraw consent per person. | `src/pkg/askai/service.go`; `src/pkg/askai/kapa.go`; `src/pkg/hub/ask.go`; [design](design/dashboard-ask-ai-help.md). | | Crash/error reporting | No Sentry/PostHog/Segment/Plausible crash reporter was found in `src` during the onboarding audit. Errors are logged locally; selected log-safe health/error strings can appear in hub heartbeats as described above. | Local logs and, for selected operational state, the configured hub. | No third-party crash reporting by default. | Local log/PVC retention is deployment-specific. | N/A for third-party crash reporting; disable hub link for heartbeat-carried operational errors. | Audit search: `telemetry|analytics|metrics push|phone.?home|posthog|segment|plausible|gtag|googletagmanager|sentry` over Go/HTML/JS/Markdown. | ## Linux Foundation telemetry-policy status diff --git a/src/pkg/askai/breaker.go b/src/pkg/askai/breaker.go new file mode 100644 index 0000000000..74de41ded7 --- /dev/null +++ b/src/pkg/askai/breaker.go @@ -0,0 +1,103 @@ +package askai + +import ( + "sync" + "time" +) + +const ( + // DefaultBreakerFailures consecutive upstream failures open the breaker. + DefaultBreakerFailures = 3 + // DefaultBreakerCooldown is how long an open breaker short-circuits to + // the docs link before one trial call is let through. + DefaultBreakerCooldown = 5 * time.Minute +) + +// breakerEvent reports a state change for the audit line. +type breakerEvent int + +const ( + breakerNoChange breakerEvent = iota + breakerOpened + breakerClosed +) + +// breaker is a consecutive-failure circuit breaker with a half-open trial. +type breaker struct { + mu sync.Mutex + threshold int + cooldown time.Duration + failures int + openUntil time.Time + open bool + trial bool +} + +func newBreaker(threshold int, cooldown time.Duration) *breaker { + if threshold <= 0 { + threshold = DefaultBreakerFailures + } + if cooldown <= 0 { + cooldown = DefaultBreakerCooldown + } + return &breaker{threshold: threshold, cooldown: cooldown} +} + +// allow reports whether a call may go out, and how long to wait if not. +// After the cool-down exactly one trial call is admitted at a time. +func (b *breaker) allow(now time.Time) (bool, time.Duration) { + b.mu.Lock() + defer b.mu.Unlock() + if !b.open { + return true, 0 + } + if now.Before(b.openUntil) { + return false, b.openUntil.Sub(now) + } + if b.trial { + return false, time.Second + } + b.trial = true + return true, 0 +} + +// cancelTrial returns an admitted trial slot that never reached the vendor +// (for example, the request was rate limited after allow). +func (b *breaker) cancelTrial() { + b.mu.Lock() + defer b.mu.Unlock() + b.trial = false +} + +func (b *breaker) success() breakerEvent { + b.mu.Lock() + defer b.mu.Unlock() + wasOpen := b.open + b.failures, b.open, b.trial = 0, false, false + if wasOpen { + return breakerClosed + } + return breakerNoChange +} + +func (b *breaker) failure(now time.Time) breakerEvent { + b.mu.Lock() + defer b.mu.Unlock() + b.failures++ + if b.open { + // A failed trial re-opens for another cool-down. + b.openUntil, b.trial = now.Add(b.cooldown), false + return breakerNoChange + } + if b.failures >= b.threshold { + b.open, b.openUntil, b.trial = true, now.Add(b.cooldown), false + return breakerOpened + } + return breakerNoChange +} + +func (b *breaker) isOpen() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.open +} diff --git a/src/pkg/askai/consent.go b/src/pkg/askai/consent.go new file mode 100644 index 0000000000..ff4e1b4898 --- /dev/null +++ b/src/pkg/askai/consent.go @@ -0,0 +1,183 @@ +package askai + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "regexp" + "sync" + "time" +) + +const ( + // ConsentTextVersion is bumped for any material change to ConsentText; + // a person who confirmed an older version is asked again. + ConsentTextVersion = "1" + // ConsentText is the disclosure the panel shows before the first + // question (design: "What leaves the deployment"). + ConsentText = "Your question, and the section you are in, are sent to Kapa.ai, an AI service. " + + "The maintainers of this project can read it in their analytics. " + + "Do not include secrets or private details. " + + "Withdrawing stops future questions; it cannot recall what Kapa.ai already holds." + + consentDirMode = 0o700 + consentFileMode = 0o600 + // consentFileSuffix is the per-person file extension. + consentFileSuffix = ".json" +) + +// consentStemPattern bounds a person key to a single safe path segment. +var consentStemPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$`) + +// ErrInvalidPerson is returned for a person key that is not a safe stem. +var ErrInvalidPerson = errors.New("ask: invalid person key") + +// Consent is one person's record. +type Consent struct { + Person string `json:"person"` + TextVersion string `json:"text_version"` + GrantedAt time.Time `json:"granted_at"` + UpdatedAt time.Time `json:"updated_at"` + WithdrawnAt *time.Time `json:"withdrawn_at,omitempty"` +} + +// Current reports a live consent to the current disclosure text. +func (c Consent) Current() bool { + return c.WithdrawnAt == nil && c.TextVersion == ConsentTextVersion && !c.GrantedAt.IsZero() +} + +// ConsentStore keeps one small file per person under Dir, separate from any +// other user record, written atomically with owner-only permissions. The +// file name is the same stem the person's user record uses, so a user +// deletion can find it. +type ConsentStore struct { + Dir string + mu sync.Mutex +} + +func (s *ConsentStore) path(person string) (string, error) { + if s == nil || s.Dir == "" || !consentStemPattern.MatchString(person) { + return "", ErrInvalidPerson + } + return filepath.Join(s.Dir, person+consentFileSuffix), nil +} + +// Get returns the person's record; a missing file is the zero Consent. +func (s *ConsentStore) Get(person string) (Consent, error) { + path, err := s.path(person) + if err != nil { + return Consent{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + return readConsent(path) +} + +// Has reports whether person holds a current consent. Any error is "no". +func (s *ConsentStore) Has(person string) bool { + c, err := s.Get(person) + return err == nil && c.Current() +} + +// Grant records consent to version, which must be the current text version. +func (s *ConsentStore) Grant(person, version string, now time.Time) (Consent, error) { + if version != ConsentTextVersion { + return Consent{}, ErrStaleConsentVersion + } + path, err := s.path(person) + if err != nil { + return Consent{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + c, err := readConsent(path) + if err != nil { + return Consent{}, err + } + now = now.UTC() + if c.GrantedAt.IsZero() || c.WithdrawnAt != nil || c.TextVersion != version { + c.GrantedAt = now + } + c.Person, c.TextVersion, c.UpdatedAt, c.WithdrawnAt = person, version, now, nil + return c, writeConsent(path, c) +} + +// Withdraw marks the record withdrawn. It takes effect on the next request. +// Withdrawing without a record is a no-op. +func (s *ConsentStore) Withdraw(person string, now time.Time) (bool, error) { + path, err := s.path(person) + if err != nil { + return false, err + } + s.mu.Lock() + defer s.mu.Unlock() + c, err := readConsent(path) + if err != nil { + return false, err + } + if c.GrantedAt.IsZero() || c.WithdrawnAt != nil { + return false, nil + } + now = now.UTC() + c.UpdatedAt, c.WithdrawnAt = now, &now + return true, writeConsent(path, c) +} + +// Delete removes the person's record (user deletion). +func (s *ConsentStore) Delete(person string) error { + path, err := s.path(person) + if err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +// ErrStaleConsentVersion means the page showed an older disclosure. +var ErrStaleConsentVersion = errors.New("ask: disclosure version changed") + +func readConsent(path string) (Consent, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return Consent{}, nil + } + if err != nil { + return Consent{}, err + } + var c Consent + if err := json.Unmarshal(data, &c); err != nil { + return Consent{}, err + } + return c, nil +} + +func writeConsent(path string, c Consent) error { + data, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, consentDirMode); err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".ask-consent-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if err := tmp.Chmod(consentFileMode); err != nil { + _ = tmp.Close() + return err + } + _, writeErr := tmp.Write(data) + closeErr := tmp.Close() + if err := errors.Join(writeErr, closeErr); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} diff --git a/src/pkg/askai/kapa.go b/src/pkg/askai/kapa.go new file mode 100644 index 0000000000..d66d017969 --- /dev/null +++ b/src/pkg/askai/kapa.go @@ -0,0 +1,199 @@ +// Package askai is the backend of the optional Ask AI help panel +// (src/docs/design/dashboard-ask-ai-help.md, #19177). A dashboard posts a +// question to its own backend; this package validates it, enforces consent and +// limits, refuses credential-shaped input, calls the Kapa.ai Chat API server +// side, keeps only allowlisted sources and returns plain text. Nothing here +// runs in the browser, and nothing here logs or stores what a person typed. +package askai + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "time" +) + +// Vendor contract, pinned from the public Kapa API reference ("Chat" and "Chat +// in thread", QueryResponse schema) and by TestKapaClientContract. +const ( + // KapaDefaultBaseURL is the vendor API host. + KapaDefaultBaseURL = "https://api.kapa.ai" + // kapaChatPath starts a conversation in a project. + kapaChatPath = "/query/v1/projects/%s/chat/" + // kapaThreadChatPath continues a conversation in an existing thread. + kapaThreadChatPath = "/query/v1/threads/%s/chat/" + // kapaAPIKeyHeader carries the key. It is set on the outbound request + // only and never logged. + kapaAPIKeyHeader = "X-API-KEY" + + // DefaultUpstreamTimeout bounds one vendor call (design: 30 s). + DefaultUpstreamTimeout = 30 * time.Second + // maxUpstreamResponseBytes caps what is read from the vendor. + maxUpstreamResponseBytes = 1 << 20 + // defaultRetryAfter is used when the vendor rate-limits without a + // usable Retry-After header. + defaultRetryAfter = 60 * time.Second + // maxRetryAfter keeps a hostile Retry-After from parking the feature. + maxRetryAfter = 15 * time.Minute +) + +// vendorIDPattern bounds ids interpolated into the vendor URL path. +var vendorIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`) + +// Upstream is whatever answers a question: the Kapa client in direct mode, +// a fake in tests. +type Upstream interface { + Chat(ctx context.Context, threadID, query string) (UpstreamAnswer, error) +} + +// UpstreamAnswer is the vendor's answer before filtering. +type UpstreamAnswer struct { + Answer string + ThreadID string + Uncertain bool + Sources []UpstreamSource +} + +// UpstreamSource is one source the vendor cited. +type UpstreamSource struct { + URL string + Title string + Internal bool +} + +// UpstreamStatusError is a non-2xx vendor response. It carries the status +// and a retry hint, never the body. +type UpstreamStatusError struct { + Status int + RetryAfter time.Duration +} + +func (e *UpstreamStatusError) Error() string { + return "ask upstream returned HTTP " + strconv.Itoa(e.Status) +} + +// RateLimited reports a vendor 429. +func (e *UpstreamStatusError) RateLimited() bool { return e.Status == http.StatusTooManyRequests } + +// KapaClient calls the Kapa Chat API. The key, the project id and the +// integration id stay in this struct: String and errors never print them. +type KapaClient struct { + baseURL string + projectID string + integrationID string + apiKey string + http *http.Client +} + +// NewKapaClient builds a client. baseURL "" means KapaDefaultBaseURL; a nil +// httpClient gets one bounded by DefaultUpstreamTimeout. +func NewKapaClient(baseURL, projectID, integrationID, apiKey string, httpClient *http.Client) (*KapaClient, error) { + if baseURL == "" { + baseURL = KapaDefaultBaseURL + } + if !vendorIDPattern.MatchString(projectID) || !vendorIDPattern.MatchString(integrationID) || strings.TrimSpace(apiKey) == "" { + return nil, errors.New("ask: vendor client is not configured") + } + if httpClient == nil { + httpClient = &http.Client{Timeout: DefaultUpstreamTimeout} + } + return &KapaClient{ + baseURL: strings.TrimRight(baseURL, "/"), + projectID: projectID, + integrationID: integrationID, + apiKey: strings.TrimSpace(apiKey), + http: httpClient, + }, nil +} + +// String never prints credentials. +func (c *KapaClient) String() string { return "KapaClient{configured}" } + +// kapaRequest is the ONLY body we send: the integration id and the query. +// No user object, no metadata (origin_url), no source filters. +type kapaRequest struct { + IntegrationID string `json:"integration_id"` + Query string `json:"query"` +} + +// kapaResponse mirrors the vendor's QueryResponse. +type kapaResponse struct { + Answer string `json:"answer"` + ThreadID string `json:"thread_id"` + QuestionAnswerID string `json:"question_answer_id"` + IsUncertain bool `json:"is_uncertain"` + RelevantSources []struct { + SourceURL string `json:"source_url"` + Title string `json:"title"` + ContainsInternalData bool `json:"contains_internal_data"` + } `json:"relevant_sources"` +} + +// Chat asks a question, in threadID when it is a valid vendor thread id. +func (c *KapaClient) Chat(ctx context.Context, threadID, query string) (UpstreamAnswer, error) { + path := fmt.Sprintf(kapaChatPath, url.PathEscape(c.projectID)) + if threadID != "" { + if !vendorIDPattern.MatchString(threadID) { + return UpstreamAnswer{}, errors.New("ask: invalid thread id") + } + path = fmt.Sprintf(kapaThreadChatPath, url.PathEscape(threadID)) + } + body, err := json.Marshal(kapaRequest{IntegrationID: c.integrationID, Query: query}) + if err != nil { + return UpstreamAnswer{}, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(body)) + if err != nil { + return UpstreamAnswer{}, errors.New("ask: could not build the vendor request") + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + req.Header.Set(kapaAPIKeyHeader, c.apiKey) + resp, err := c.http.Do(req) + if err != nil { + // Do not wrap: a url.Error would print the request URL, which + // carries the project id. + if ctx.Err() != nil { + return UpstreamAnswer{}, fmt.Errorf("ask: vendor call cancelled: %w", ctx.Err()) + } + return UpstreamAnswer{}, errors.New("ask: vendor unreachable") + } + defer resp.Body.Close() + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxUpstreamResponseBytes)) + return UpstreamAnswer{}, &UpstreamStatusError{Status: resp.StatusCode, RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After"))} + } + var out kapaResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, maxUpstreamResponseBytes)).Decode(&out); err != nil { + return UpstreamAnswer{}, errors.New("ask: vendor response was not valid JSON") + } + answer := UpstreamAnswer{Answer: out.Answer, Uncertain: out.IsUncertain} + if vendorIDPattern.MatchString(out.ThreadID) { + answer.ThreadID = out.ThreadID + } + for _, s := range out.RelevantSources { + answer.Sources = append(answer.Sources, UpstreamSource{URL: s.SourceURL, Title: s.Title, Internal: s.ContainsInternalData}) + } + return answer, nil +} + +// parseRetryAfter reads delta-seconds; anything else is the default. The +// result is clamped to maxRetryAfter. +func parseRetryAfter(v string) time.Duration { + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil || n <= 0 { + return defaultRetryAfter + } + if n > int(maxRetryAfter/time.Second) { + return maxRetryAfter + } + return time.Duration(n) * time.Second +} diff --git a/src/pkg/askai/kapa_test.go b/src/pkg/askai/kapa_test.go new file mode 100644 index 0000000000..1398514399 --- /dev/null +++ b/src/pkg/askai/kapa_test.go @@ -0,0 +1,144 @@ +package askai + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +const ( + testProjectID = "11111111-2222-3333-4444-555555555555" + testIntegrationID = "66666666-7777-8888-9999-000000000000" + testAPIKey = "kapa-test-key-value" +) + +// TestKapaClientContract pins the vendor contract: the path, the key header, +// a body with exactly integration_id and query, and the QueryResponse fields. +func TestKapaClientContract(t *testing.T) { + var mu sync.Mutex + var gotPath, gotKey, gotType string + var gotBody map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method %s, want POST", r.Method) + } + raw, _ := io.ReadAll(r.Body) + mu.Lock() + gotPath, gotKey, gotType = r.URL.Path, r.Header.Get("X-API-KEY"), r.Header.Get("Content-Type") + gotBody = nil + if err := json.Unmarshal(raw, &gotBody); err != nil { + t.Errorf("body is not JSON: %v", err) + } + mu.Unlock() + _, _ = io.WriteString(w, `{"answer":"Open Settings, Features.","thread_id":"aaaa-bbbb","question_answer_id":"qa-1","is_uncertain":true, + "relevant_sources":[{"source_url":"https://docs.hivecommons.dev/settings/","title":"Settings","contains_internal_data":false}, + {"source_url":"https://intranet.example/x","title":"Internal","contains_internal_data":true}]}`) + })) + defer srv.Close() + + c, err := NewKapaClient(srv.URL, testProjectID, testIntegrationID, testAPIKey, srv.Client()) + if err != nil { + t.Fatal(err) + } + got, err := c.Chat(context.Background(), "", "where is the pause button") + if err != nil { + t.Fatal(err) + } + type capture struct { + path, key, ctype string + body map[string]any + } + snap := func() capture { + mu.Lock() + defer mu.Unlock() + return capture{gotPath, gotKey, gotType, gotBody} + } + first := snap() + if first.path != "/query/v1/projects/"+testProjectID+"/chat/" { + t.Fatalf("path %q", first.path) + } + if first.key != testAPIKey || first.ctype != "application/json" { + t.Fatalf("headers key=%q type=%q", first.key, first.ctype) + } + if len(first.body) != 2 || first.body["integration_id"] != testIntegrationID || first.body["query"] != "where is the pause button" { + t.Fatalf("body must hold exactly integration_id and query, got %v", first.body) + } + if got.Answer != "Open Settings, Features." || got.ThreadID != "aaaa-bbbb" || !got.Uncertain || len(got.Sources) != 2 || + got.Sources[0].URL != "https://docs.hivecommons.dev/settings/" || got.Sources[0].Title != "Settings" || !got.Sources[1].Internal { + t.Fatalf("decoded %+v", got) + } + + if _, err := c.Chat(context.Background(), "aaaa-bbbb", "and then?"); err != nil { + t.Fatal(err) + } + if followUp := snap().path; followUp != "/query/v1/threads/aaaa-bbbb/chat/" { + t.Fatalf("follow-up path %q", followUp) + } + if _, err := c.Chat(context.Background(), "../../etc", "x"); err == nil { + t.Fatal("a thread id that is not a vendor id must be refused before any call") + } +} + +func TestKapaClientErrorsCarryNoCredentials(t *testing.T) { + var status atomic.Int32 + status.Store(http.StatusTooManyRequests) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Retry-After", "7") + w.WriteHeader(int(status.Load())) + _, _ = io.WriteString(w, `{"detail":"echo `+testAPIKey+`"}`) + })) + c, err := NewKapaClient(srv.URL, testProjectID, testIntegrationID, testAPIKey, srv.Client()) + if err != nil { + t.Fatal(err) + } + _, err = c.Chat(context.Background(), "", "q") + var se *UpstreamStatusError + if !errors.As(err, &se) || !se.RateLimited() || se.RetryAfter != 7*time.Second { + t.Fatalf("429: %v", err) + } + status.Store(http.StatusBadGateway) + _, err = c.Chat(context.Background(), "", "q") + if !errors.As(err, &se) || se.Status != http.StatusBadGateway || se.RateLimited() { + t.Fatalf("502: %v", err) + } + srv.Close() + _, err = c.Chat(context.Background(), "", "q") + if err == nil { + t.Fatal("closed server must fail") + } + for _, s := range []string{err.Error(), se.Error(), c.String()} { + for _, secret := range []string{testAPIKey, testProjectID, testIntegrationID} { + if strings.Contains(s, secret) { + t.Fatalf("%q leaks a credential", s) + } + } + } + if _, err := NewKapaClient("", "bad/id", testIntegrationID, testAPIKey, nil); err == nil { + t.Fatal("a project id with a slash must be refused") + } + if _, err := NewKapaClient("", testProjectID, testIntegrationID, " ", nil); err == nil { + t.Fatal("an empty key must be refused") + } +} + +func TestParseRetryAfter(t *testing.T) { + for in, want := range map[string]time.Duration{ + "": defaultRetryAfter, + "soon": defaultRetryAfter, + "-3": defaultRetryAfter, + "12": 12 * time.Second, + "99999999999": maxRetryAfter, + } { + if got := parseRetryAfter(in); got != want { + t.Errorf("parseRetryAfter(%q) = %v, want %v", in, got, want) + } + } +} diff --git a/src/pkg/askai/limits.go b/src/pkg/askai/limits.go new file mode 100644 index 0000000000..9f2c384c94 --- /dev/null +++ b/src/pkg/askai/limits.go @@ -0,0 +1,178 @@ +package askai + +import ( + "sync" + "time" +) + +const ( + minuteWindow = time.Minute + hourWindow = time.Hour + dayWindow = 24 * time.Hour + // personInFlight: one request in flight per person (design). + personInFlight = 1 + // maxTrackedKeys bounds the per-person and per-hive counter maps; expired + // windows are dropped first. + maxTrackedKeys = 10000 +) + +// Limits are the effective request limits (config.AskLimits, copied so this +// package does not import config). +type Limits struct { + PersonPerMinute int + PersonPerHour int + HivePerHour int + GlobalPerMinute int + InFlight int + Daily int +} + +// window is a fixed-window counter. +type window struct { + start time.Time + count int +} + +func (w *window) roll(now time.Time, size time.Duration) { + if w.start.IsZero() || !now.Before(w.start.Add(size)) { + w.start, w.count = now, 0 + } +} + +func (w *window) retryAfter(now time.Time, size time.Duration) time.Duration { + d := w.start.Add(size).Sub(now) + if d < time.Second { + return time.Second + } + return d +} + +type personState struct { + minute, hour window + inFlight int +} + +// limitDecision is the result of a reservation. +type limitDecision struct { + ok bool + retryAfter time.Duration + dailySpent bool +} + +// limiter enforces every cap in one place, all-or-nothing: a refused request +// consumes nothing. +type limiter struct { + mu sync.Mutex + limits Limits + persons map[string]*personState + hives map[string]*window + minute window + day window + inFlight int + backoffTo time.Time +} + +func newLimiter(l Limits) *limiter { + return &limiter{limits: l, persons: map[string]*personState{}, hives: map[string]*window{}} +} + +// reserve takes one slot for person (and hive when non-empty). release must +// be called exactly once after an ok reservation. +func (l *limiter) reserve(now time.Time, person, hive string) limitDecision { + l.mu.Lock() + defer l.mu.Unlock() + l.prune(now) + if now.Before(l.backoffTo) { + return limitDecision{retryAfter: l.backoffTo.Sub(now)} + } + p := l.persons[person] + if p == nil { + p = &personState{} + } + p.minute.roll(now, minuteWindow) + p.hour.roll(now, hourWindow) + l.minute.roll(now, minuteWindow) + l.day.roll(now, dayWindow) + var hw *window + if hive != "" { + hw = l.hives[hive] + if hw == nil { + hw = &window{} + } + hw.roll(now, hourWindow) + } + switch { + case p.inFlight >= personInFlight: + return limitDecision{retryAfter: time.Second} + case p.minute.count >= l.limits.PersonPerMinute: + return limitDecision{retryAfter: p.minute.retryAfter(now, minuteWindow)} + case p.hour.count >= l.limits.PersonPerHour: + return limitDecision{retryAfter: p.hour.retryAfter(now, hourWindow)} + case hw != nil && hw.count >= l.limits.HivePerHour: + return limitDecision{retryAfter: hw.retryAfter(now, hourWindow)} + case l.day.count >= l.limits.Daily: + return limitDecision{retryAfter: l.day.retryAfter(now, dayWindow), dailySpent: true} + case l.minute.count >= l.limits.GlobalPerMinute: + return limitDecision{retryAfter: l.minute.retryAfter(now, minuteWindow)} + case l.inFlight >= l.limits.InFlight: + return limitDecision{retryAfter: time.Second} + } + p.minute.count++ + p.hour.count++ + p.inFlight++ + l.persons[person] = p + if hw != nil { + hw.count++ + l.hives[hive] = hw + } + l.minute.count++ + l.day.count++ + l.inFlight++ + return limitDecision{ok: true} +} + +func (l *limiter) release(person string) { + l.mu.Lock() + defer l.mu.Unlock() + if p := l.persons[person]; p != nil && p.inFlight > 0 { + p.inFlight-- + } + if l.inFlight > 0 { + l.inFlight-- + } +} + +// backoff stops all calls until now+d, after a vendor 429. +func (l *limiter) backoff(now time.Time, d time.Duration) { + l.mu.Lock() + defer l.mu.Unlock() + if t := now.Add(d); t.After(l.backoffTo) { + l.backoffTo = t + } +} + +// dailyUsed reports today's count and the budget. +func (l *limiter) dailyUsed(now time.Time) (int, int) { + l.mu.Lock() + defer l.mu.Unlock() + l.day.roll(now, dayWindow) + return l.day.count, l.limits.Daily +} + +// prune drops idle counters once the maps grow large. Caller holds mu. +func (l *limiter) prune(now time.Time) { + if len(l.persons) >= maxTrackedKeys { + for k, p := range l.persons { + if p.inFlight == 0 && !now.Before(p.hour.start.Add(hourWindow)) { + delete(l.persons, k) + } + } + } + if len(l.hives) >= maxTrackedKeys { + for k, w := range l.hives { + if !now.Before(w.start.Add(hourWindow)) { + delete(l.hives, k) + } + } + } +} diff --git a/src/pkg/askai/sections.go b/src/pkg/askai/sections.go new file mode 100644 index 0000000000..0d37cd739f --- /dev/null +++ b/src/pkg/askai/sections.go @@ -0,0 +1,69 @@ +package askai + +import "sort" + +// sectionLabels is the closed vocabulary of dashboard section ids whose label +// may accompany a question (design: "What leaves the deployment"). The label +// comes from this list we ship, never from anything on screen: an id the list +// does not hold sends no label at all. Hive ids match DASHBOARD_SECTION_HELP +// in src/pkg/dashboard/static-src/js/sections.js; hub ids name the hub +// dashboard's own areas. +var sectionLabels = map[string]string{ + // Hub dashboard. + "hub-my-hives": "Hub, My Hives", + "hub-fleet": "Hub, Fleet", + "hub-add-hosted-hive": "Hub, Add Hosted Hive", + "hub-register-hive": "Hub, Register your own hive", + "hub-request-hive": "Hub, Request a hive", + "hub-profile-sharing": "Hub, Profile sharing", + "hub-operator-settings": "Hub, Operator settings", + "hub-hive-card": "Hub, Hive card", + + // Hive dashboard. + "overview-section": "Overview", + "governor-pr-models-section": "PRs by model", + "advisory-section": "Advisory", + "advisory-digest-section": "Advisory Digest", + "hive-advice-section": "Hive Advice", + "fleet-report-section": "Fleet Report Preview", + "acmm-reco-section": "Ready to level up?", + "lifecycle-section": "Lifecycle Timeline", + "pr-throughput-section": "Throughput", + "repos-section": "Projects", + "acmm-eval-section": "ACMM Eval", + "approvals-section": "Approvals", + "audit-section": "Audit Log", + "review-queue-section": "Review", + "nous-section": "Experiment Lab", + "sessions-section": "Inception (spek)", + "knowledge-section": "Knowledge", + "meetings-section": "Meetings", + "inbox-section": "Inbox", + "calendar-section": "Calendar", + "customers-section": "Customers", + "contributors-section": "Contributors", + "debug-section": "Diagnostics", + "logs-section": "Agent Logs", + "agents-section": "Agents", + "agent-activity-section": "Agent activity", + "activity-monitor-section": "Hive activity monitor", + "faq-section": "FAQ", + "settings": "Settings", + "settings-features": "Settings, Features", +} + +// SectionLabel returns the label for a known section id. +func SectionLabel(id string) (string, bool) { + label, ok := sectionLabels[id] + return label, ok +} + +// SectionIDs lists the vocabulary, sorted. +func SectionIDs() []string { + ids := make([]string, 0, len(sectionLabels)) + for id := range sectionLabels { + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} diff --git a/src/pkg/askai/service.go b/src/pkg/askai/service.go new file mode 100644 index 0000000000..c29c85f77d --- /dev/null +++ b/src/pkg/askai/service.go @@ -0,0 +1,323 @@ +package askai + +import ( + "context" + "errors" + "log/slog" + "math" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/hivecommons/hive/crux/logscrub" +) + +// Outcome is the result class of one request. Audit lines and counters use +// it; it never carries text. +type Outcome string + +const ( + OutcomeOK Outcome = "ok" + OutcomeNoCitedAnswer Outcome = "no_cited_answer" + OutcomeRefusedSecretShape Outcome = "refused_secret_shape" + OutcomeRateLimited Outcome = "rate_limited" + OutcomeBreakerOpen Outcome = "breaker_open" + OutcomeUpstreamError Outcome = "upstream_error" + OutcomeNotConsented Outcome = "not_consented" + OutcomeInvalidQuestion Outcome = "invalid_question" + OutcomeRelayDisabled Outcome = "relay_disabled" +) + +const ( + // MaxQuestionRunes caps the question text. + MaxQuestionRunes = 1000 + // sectionLabelPrefix introduces the closed-vocabulary section label in + // the query text. + sectionLabelPrefix = "Dashboard section: " +) + +// Plain-language messages the panel shows. None echoes input. +const ( + msgNoCitedAnswer = "No cited answer found in the docs. Try the docs link." + msgRefused = "This looks like it contains a password, token or key, so it was not sent. Remove it and ask again." + msgUnavailable = "Ask is unavailable right now. Try the docs link." + msgNotConsented = "Confirm the notice before asking." + msgRelayDisabled = "Ask is not available for this hive. Try the docs link." + msgBusyPrefix = "Busy, try again in " + msgBusySuffix = " seconds." +) + +var msgInvalid = "Ask a question of up to " + strconv.Itoa(MaxQuestionRunes) + " characters." + +// ConsentChecker answers whether a person holds a current consent. +type ConsentChecker interface { + Has(person string) bool +} + +// Options configure a Service. +type Options struct { + Upstream Upstream + Limits Limits + SendSectionLabel bool + Consent ConsentChecker + Logger *slog.Logger + // DocsURL is the fallback docs link; "" means DocsHomeURL. + DocsURL string + // UpstreamTimeout bounds one vendor call; 0 means DefaultUpstreamTimeout. + UpstreamTimeout time.Duration + BreakerFailures int + BreakerCooldown time.Duration + ConversationTTL time.Duration + // Now is the clock; nil means time.Now. + Now func() time.Time +} + +// Request is one question. Person is the stem other audit lines use; HiveID is +// set for relayed requests only. Section is an id from the closed vocabulary; +// anything else sends no label. Conversation is the handle from a previous +// Result. +type Request struct { + Person string `json:"-"` + HiveID string `json:"-"` + Question string `json:"question"` + Section string `json:"section,omitempty"` + Conversation string `json:"conversation,omitempty"` +} + +// Result is what the page receives. Answer is plain text; Sources passed the +// allowlist. AIGenerated is always true so the label is never optional. +type Result struct { + Outcome Outcome `json:"outcome"` + Answer string `json:"answer,omitempty"` + Sources []Source `json:"sources,omitempty"` + Uncertain bool `json:"uncertain,omitempty"` + Conversation string `json:"conversation,omitempty"` + RetryAfterSeconds int `json:"retry_after_seconds,omitempty"` + Message string `json:"message,omitempty"` + AIGenerated bool `json:"ai_generated"` + DocsURL string `json:"docs_url"` +} + +// Stats is the operator view: counts by outcome and today's total against +// the daily budget. No per-person data. +type Stats struct { + ByOutcome map[Outcome]uint64 `json:"by_outcome"` + Today int `json:"today"` + DailyBudget int `json:"daily_budget"` + BreakerOpen bool `json:"breaker_open"` +} + +// Service answers questions. It is safe for concurrent use. +type Service struct { + opts Options + limiter *limiter + breaker *breaker + convs *conversations + now func() time.Time + logger *slog.Logger + + mu sync.Mutex + counts map[Outcome]uint64 + limitAudited map[string]time.Time + dailyAudited time.Time +} + +// NewService builds a Service. A nil Upstream is a programming error. +func NewService(o Options) (*Service, error) { + if o.Upstream == nil { + return nil, errors.New("ask: no upstream") + } + if o.Logger == nil { + o.Logger = slog.Default() + } + if o.DocsURL == "" { + o.DocsURL = DocsHomeURL + } + if o.UpstreamTimeout <= 0 { + o.UpstreamTimeout = DefaultUpstreamTimeout + } + now := o.Now + if now == nil { + now = time.Now + } + return &Service{ + opts: o, + limiter: newLimiter(o.Limits), + breaker: newBreaker(o.BreakerFailures, o.BreakerCooldown), + convs: newConversations(o.ConversationTTL), + now: now, + logger: o.Logger, + counts: map[Outcome]uint64{}, + limitAudited: map[string]time.Time{}, + }, nil +} + +// Ask answers a question from a person signed in to this deployment's own +// dashboard. A current consent is required. +func (s *Service) Ask(ctx context.Context, req Request) Result { + return s.ask(ctx, req, true) +} + +// ValidateQuestion trims the question and reports whether it is usable and +// free of credential shapes. It is exported so a relaying hive can refuse +// before anything leaves it. +func ValidateQuestion(q string) (string, Outcome) { + q = strings.TrimSpace(q) + if q == "" || !utf8.ValidString(q) || utf8.RuneCountInString(q) > MaxQuestionRunes { + return "", OutcomeInvalidQuestion + } + if CredentialShaped(q) { + return "", OutcomeRefusedSecretShape + } + return q, OutcomeOK +} + +// CredentialShaped reports whether s holds anything the log scrubber treats +// as a credential, including the heuristic shapes FindSecret skips: refusing +// a question costs the person a rephrase, sending a token costs much more. +func CredentialShaped(s string) bool { + if _, found := logscrub.FindSecret(s); found { + return true + } + return logscrub.ScrubString(s) != s +} + +func (s *Service) ask(ctx context.Context, req Request, checkConsent bool) Result { + start := s.now() + question, outcome := ValidateQuestion(req.Question) + questionLen := utf8.RuneCountInString(strings.TrimSpace(req.Question)) + if outcome == OutcomeInvalidQuestion { + return s.finish(req, s.result(OutcomeInvalidQuestion, msgInvalid), questionLen, start) + } + if checkConsent && (s.opts.Consent == nil || !s.opts.Consent.Has(req.Person)) { + return s.finish(req, s.result(OutcomeNotConsented, msgNotConsented), questionLen, start) + } + if outcome == OutcomeRefusedSecretShape { + return s.finish(req, s.result(OutcomeRefusedSecretShape, msgRefused), questionLen, start) + } + if ok, wait := s.breaker.allow(start); !ok { + r := s.result(OutcomeBreakerOpen, msgUnavailable) + r.RetryAfterSeconds = seconds(wait) + return s.finish(req, r, questionLen, start) + } + decision := s.limiter.reserve(start, req.Person, req.HiveID) + if !decision.ok { + s.breaker.cancelTrial() + if decision.dailySpent { + s.auditDailySpent(start) + } + r := s.result(OutcomeRateLimited, busyMessage(decision.retryAfter)) + r.RetryAfterSeconds = seconds(decision.retryAfter) + return s.finish(req, r, questionLen, start) + } + defer s.limiter.release(req.Person) + + query := question + if s.opts.SendSectionLabel { + if label, ok := SectionLabel(req.Section); ok { + query = sectionLabelPrefix + label + ".\n\n" + question + } + } + thread := s.convs.thread(req.Conversation, req.Person, req.HiveID, start) + callCtx, cancel := context.WithTimeout(ctx, s.opts.UpstreamTimeout) + answer, err := s.opts.Upstream.Chat(callCtx, thread, query) + cancel() + if err != nil { + var status *UpstreamStatusError + if errors.As(err, &status) && status.RateLimited() { + s.breaker.cancelTrial() + s.limiter.backoff(s.now(), status.RetryAfter) + r := s.result(OutcomeRateLimited, busyMessage(status.RetryAfter)) + r.RetryAfterSeconds = seconds(status.RetryAfter) + return s.finish(req, r, questionLen, start) + } + if s.breaker.failure(s.now()) == breakerOpened { + s.logger.Warn("audit: ask breaker opened", "cooldown_s", seconds(s.breaker.cooldown)) + } + return s.finish(req, s.result(OutcomeUpstreamError, msgUnavailable), questionLen, start) + } + if s.breaker.success() == breakerClosed { + s.logger.Info("audit: ask breaker closed") + } + r := s.result(OutcomeOK, "") + r.Conversation = s.convs.remember(req.Conversation, req.Person, req.HiveID, answer.ThreadID, s.now()) + r.Sources = FilterSources(answer.Sources) + r.Answer = SanitizeAnswer(answer.Answer) + r.Uncertain = answer.Uncertain + if len(r.Sources) == 0 || r.Answer == "" { + // An uncited answer is not shown as an answer. + r.Outcome, r.Answer, r.Sources, r.Message, r.Uncertain = OutcomeNoCitedAnswer, "", nil, msgNoCitedAnswer, false + } + return s.finish(req, r, questionLen, start) +} + +func (s *Service) result(o Outcome, msg string) Result { + return Result{Outcome: o, Message: msg, AIGenerated: true, DocsURL: s.opts.DocsURL} +} + +// finish counts the outcome and writes the audit line: outcome and counts +// only, never the question, the answer, the sources or the thread. +func (s *Service) finish(req Request, r Result, questionLen int, start time.Time) Result { + s.mu.Lock() + s.counts[r.Outcome]++ + skip := false + if r.Outcome == OutcomeRateLimited { + // One audit line per person per window, not one per request. + key := req.HiveID + "/" + req.Person + if last, ok := s.limitAudited[key]; ok && start.Sub(last) < minuteWindow { + skip = true + } else { + if len(s.limitAudited) >= maxTrackedKeys { + s.limitAudited = map[string]time.Time{} + } + s.limitAudited[key] = start + } + } + s.mu.Unlock() + if !skip { + attrs := []any{"person", req.Person, "outcome", string(r.Outcome), "question_len", questionLen, + "sources_kept", len(r.Sources), "latency_ms", s.now().Sub(start).Milliseconds()} + if req.HiveID != "" { + attrs = append(attrs, "hive", req.HiveID) + } + s.logger.Info("audit: ask request", attrs...) + } + return r +} + +func (s *Service) auditDailySpent(now time.Time) { + s.mu.Lock() + day := now.Truncate(dayWindow) + already := s.dailyAudited.Equal(day) + s.dailyAudited = day + s.mu.Unlock() + if !already { + _, budget := s.limiter.dailyUsed(now) + s.logger.Warn("audit: ask daily budget spent", "daily_budget", budget) + } +} + +// Stats returns the operator counters. +func (s *Service) Stats() Stats { + s.mu.Lock() + by := make(map[Outcome]uint64, len(s.counts)) + for k, v := range s.counts { + by[k] = v + } + s.mu.Unlock() + today, budget := s.limiter.dailyUsed(s.now()) + return Stats{ByOutcome: by, Today: today, DailyBudget: budget, BreakerOpen: s.breaker.isOpen()} +} + +func busyMessage(d time.Duration) string { + return msgBusyPrefix + strconv.Itoa(seconds(d)) + msgBusySuffix +} + +func seconds(d time.Duration) int { + if d <= 0 { + return 0 + } + return int(math.Ceil(d.Seconds())) +} diff --git a/src/pkg/askai/service_test.go b/src/pkg/askai/service_test.go new file mode 100644 index 0000000000..fff981d0fe --- /dev/null +++ b/src/pkg/askai/service_test.go @@ -0,0 +1,398 @@ +package askai + +import ( + "bytes" + "context" + "log/slog" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +// fakeUpstream records every query and answers from a script. +type fakeUpstream struct { + mu sync.Mutex + queries []string + threads []string + answer UpstreamAnswer + err error + block chan struct{} +} + +func (f *fakeUpstream) Chat(ctx context.Context, thread, query string) (UpstreamAnswer, error) { + f.mu.Lock() + f.queries = append(f.queries, query) + f.threads = append(f.threads, thread) + block, answer, err := f.block, f.answer, f.err + f.mu.Unlock() + if block != nil { + select { + case <-block: + case <-ctx.Done(): + return UpstreamAnswer{}, ctx.Err() + } + } + return answer, err +} + +func (f *fakeUpstream) calls() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.queries) +} + +func (f *fakeUpstream) set(a UpstreamAnswer, err error) { + f.mu.Lock() + defer f.mu.Unlock() + f.answer, f.err = a, err +} + +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +type allowAll struct{} + +func (allowAll) Has(string) bool { return true } + +var generous = Limits{PersonPerMinute: 100, PersonPerHour: 100, HivePerHour: 100, GlobalPerMinute: 100, InFlight: 10, Daily: 1000} + +var citedAnswer = UpstreamAnswer{ + Answer: "Open Settings, then Features.", + ThreadID: "thread-1", + Sources: []UpstreamSource{{URL: "https://docs.hivecommons.dev/settings/#features", Title: "Settings"}}, +} + +func newTestService(t *testing.T, up *fakeUpstream, consent ConsentChecker, limits Limits, logs *bytes.Buffer, clock *fakeClock) *Service { + t.Helper() + if clock == nil { + clock = &fakeClock{t: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)} + } + logger := slog.Default() + if logs != nil { + logger = slog.New(slog.NewTextHandler(logs, nil)) + } + svc, err := NewService(Options{ + Upstream: up, Limits: limits, SendSectionLabel: true, Consent: consent, Logger: logger, Now: clock.now, + }) + if err != nil { + t.Fatal(err) + } + return svc +} + +// TestPayloadCarriesOnlyQuestionAndSectionLabel is the "what leaves" invariant: +// the vendor query is the question plus, at most, a label from our own closed +// list. Page data, the person, the hive and an unknown section id never appear. +func TestPayloadCarriesOnlyQuestionAndSectionLabel(t *testing.T) { + up := &fakeUpstream{answer: citedAnswer} + svc := newTestService(t, up, allowAll{}, generous, nil, nil) + const q = "Where do I pause an agent?" + seeded := []string{"alice-private-login", "acme-secret-hive", "acme/private-repo"} + + svc.Ask(context.Background(), Request{Person: seeded[0], HiveID: seeded[1], Question: q, Section: seeded[2]}) + svc.Ask(context.Background(), Request{Person: seeded[0], HiveID: seeded[1], Question: q, Section: "settings-features"}) + svc.opts.SendSectionLabel = false + svc.Ask(context.Background(), Request{Person: seeded[0], HiveID: seeded[1], Question: q, Section: "settings-features"}) + + want := []string{q, "Dashboard section: Settings, Features.\n\n" + q, q} + if len(up.queries) != len(want) { + t.Fatalf("queries %q", up.queries) + } + for i, got := range up.queries { + if got != want[i] { + t.Errorf("query %d = %q, want %q", i, got, want[i]) + } + for _, s := range seeded { + if strings.Contains(got, s) { + t.Errorf("query %d leaks %q", i, s) + } + } + } +} + +func TestConsentGatesEveryRequest(t *testing.T) { + store := &ConsentStore{Dir: t.TempDir()} + up := &fakeUpstream{answer: citedAnswer} + svc := newTestService(t, up, store, generous, nil, nil) + ask := func(person string) Outcome { + return svc.Ask(context.Background(), Request{Person: person, Question: "How do I add a repo?"}).Outcome + } + now := time.Now() + if got := ask("alice"); got != OutcomeNotConsented || up.calls() != 0 { + t.Fatalf("no consent: %s, calls %d", got, up.calls()) + } + if _, err := store.Grant("alice", ConsentTextVersion, now); err != nil { + t.Fatal(err) + } + if got := ask("alice"); got != OutcomeOK || up.calls() != 1 { + t.Fatalf("consented: %s, calls %d", got, up.calls()) + } + if got := ask("bob"); got != OutcomeNotConsented || up.calls() != 1 { + t.Fatalf("alice's consent covered bob: %s", got) + } + if _, err := store.Withdraw("alice", now); err != nil { + t.Fatal(err) + } + if got := ask("alice"); got != OutcomeNotConsented || up.calls() != 1 { + t.Fatalf("withdrawn: %s", got) + } + // A record for an older disclosure text does not count. + if err := writeConsent(store.Dir+"/carol.json", Consent{Person: "carol", TextVersion: "0", GrantedAt: now}); err != nil { + t.Fatal(err) + } + if got := ask("carol"); got != OutcomeNotConsented || up.calls() != 1 { + t.Fatalf("stale text version: %s", got) + } + // No checker at all is "no consent", never "allow". + open := newTestService(t, up, nil, generous, nil, nil) + if got := open.Ask(context.Background(), Request{Person: "alice", Question: "q?"}).Outcome; got != OutcomeNotConsented { + t.Fatalf("nil checker: %s", got) + } +} + +func TestCredentialShapedQuestionsAreRefusedAndNeverSent(t *testing.T) { + up := &fakeUpstream{answer: citedAnswer} + var logs bytes.Buffer + svc := newTestService(t, up, allowAll{}, generous, &logs, nil) + for _, q := range []string{ + "my token is ghp_abcdefghijklmnopqrstuvwxyz0123 why does it fail", + "Authorization: Bearer abcdefghijklmnopqrstuvwxyz012345", + "the key sk-abcdef123456 is rejected", + "AKIAABCDEFGHIJKLMNOP leaked?", + } { + r := svc.Ask(context.Background(), Request{Person: "alice", Question: q}) + if r.Outcome != OutcomeRefusedSecretShape || r.Message == "" || strings.Contains(r.Message, q) { + t.Errorf("%q: %+v", q, r) + } + } + if up.calls() != 0 { + t.Fatalf("a credential-shaped question reached the vendor %d times", up.calls()) + } + for _, frag := range []string{"ghp_", "sk-abcdef", "AKIA", "Bearer"} { + if strings.Contains(logs.String(), frag) { + t.Fatalf("audit log carries question text %q:\n%s", frag, logs.String()) + } + } + if !strings.Contains(logs.String(), "outcome=refused_secret_shape") { + t.Fatalf("no audit line:\n%s", logs.String()) + } + if _, o := ValidateQuestion(strings.Repeat("a", MaxQuestionRunes+1)); o != OutcomeInvalidQuestion { + t.Fatal("an over-long question must be invalid") + } + if _, o := ValidateQuestion(" "); o != OutcomeInvalidQuestion { + t.Fatal("an empty question must be invalid") + } +} + +func TestAnswersNeedAllowlistedSourcesAndRenderAsText(t *testing.T) { + up := &fakeUpstream{} + svc := newTestService(t, up, allowAll{}, generous, nil, nil) + ask := func() Result { return svc.Ask(context.Background(), Request{Person: "alice", Question: "where?"}) } + + up.set(UpstreamAnswer{Answer: "Somewhere.", Sources: []UpstreamSource{{URL: "https://evil.example/docs", Title: "x"}}}, nil) + if r := ask(); r.Outcome != OutcomeNoCitedAnswer || r.Answer != "" || len(r.Sources) != 0 || !r.AIGenerated || r.DocsURL == "" { + t.Fatalf("uncited answer shown as an answer: %+v", r) + } + up.set(UpstreamAnswer{ + Answer: "Click [here](https://evil.example/steal) or see https://evil.example/x and https://docs.hivecommons.dev/a/ ", + Sources: []UpstreamSource{ + {URL: "https://docs.hivecommons.dev/a/", Title: "A\u0007"}, + {URL: "https://docs.hivecommons.dev/a/", Title: "dup"}, + {URL: "javascript:alert(1)", Title: "js"}, + {URL: "https://github.com/hivecommons/hive/blob/v5/src/docs/settings.md#features", Title: "Settings"}, + {URL: "https://docs.hivecommons.dev/internal/", Title: "Internal", Internal: true}, + }, + }, nil) + r := ask() + if r.Outcome != OutcomeOK || len(r.Sources) != 2 || r.Sources[0].Title != "A" || + r.Sources[1].URL != "https://github.com/hivecommons/hive/blob/v5/src/docs/settings.md#features" { + t.Fatalf("sources: %+v", r) + } + if strings.Contains(r.Answer, "evil.example") || !strings.Contains(r.Answer, "Click here") || + !strings.Contains(r.Answer, "https://docs.hivecommons.dev/a/") { + t.Fatalf("answer links not reduced: %q", r.Answer) + } + // Markup survives only as inert text for the page to show with textContent. + if !strings.Contains(r.Answer, "") { + t.Fatalf("answer text altered unexpectedly: %q", r.Answer) + } +} + +func TestLimitsHoldPerPersonHiveAndGlobal(t *testing.T) { + clock := &fakeClock{t: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)} + up := &fakeUpstream{answer: citedAnswer} + limits := Limits{PersonPerMinute: 2, PersonPerHour: 3, HivePerHour: 4, GlobalPerMinute: 5, InFlight: 10, Daily: 8} + var logs bytes.Buffer + svc := newTestService(t, up, allowAll{}, limits, &logs, clock) + ask := func(person, hive string) Result { + return svc.Ask(context.Background(), Request{Person: person, HiveID: hive, Question: "q?"}) + } + ask("a", "") + ask("a", "") + if r := ask("a", ""); r.Outcome != OutcomeRateLimited || r.RetryAfterSeconds <= 0 { + t.Fatalf("per-person minute cap: %+v", r) + } + clock.advance(time.Minute) + ask("a", "") + clock.advance(time.Minute) + if r := ask("a", ""); r.Outcome != OutcomeRateLimited { + t.Fatalf("per-person hour cap: %+v", r) + } + // Hive cap: four relayed requests from different people of one hive. + clock.advance(time.Minute) + for _, p := range []string{"h1", "h2", "h1", "h2"} { + if r := ask(p, "hive-a"); r.Outcome != OutcomeOK { + t.Fatalf("hive request %s: %+v", p, r) + } + clock.advance(time.Minute) + } + if r := ask("h3", "hive-a"); r.Outcome != OutcomeRateLimited { + t.Fatalf("per-hive cap: %+v", r) + } + if r := ask("h3", "hive-b"); r.Outcome != OutcomeOK { + t.Fatalf("hive B must not be charged for hive A: %+v", r) + } + // That was the eighth call of the day: the daily budget is now spent for + // everyone, and nothing more reaches the vendor. + if r := ask("h4", "hive-c"); r.Outcome != OutcomeRateLimited { + t.Fatalf("daily budget: %+v", r) + } + if got := up.calls(); got != limits.Daily { + t.Fatalf("vendor calls %d, want exactly the daily budget %d", got, limits.Daily) + } + if !strings.Contains(logs.String(), "audit: ask daily budget spent") { + t.Fatalf("daily budget line missing:\n%s", logs.String()) + } + stats := svc.Stats() + if stats.DailyBudget != limits.Daily || stats.ByOutcome[OutcomeRateLimited] == 0 { + t.Fatalf("stats %+v", stats) + } +} + +func TestGlobalPerMinuteAndInFlight(t *testing.T) { + clock := &fakeClock{t: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)} + up := &fakeUpstream{answer: citedAnswer} + svc := newTestService(t, up, allowAll{}, Limits{PersonPerMinute: 10, PersonPerHour: 10, HivePerHour: 10, GlobalPerMinute: 2, InFlight: 1, Daily: 100}, nil, clock) + ask := func(p string) Outcome { + return svc.Ask(context.Background(), Request{Person: p, Question: "q?"}).Outcome + } + if ask("a") != OutcomeOK || ask("b") != OutcomeOK || ask("c") != OutcomeRateLimited { + t.Fatal("global per-minute cap did not hold") + } + clock.advance(time.Minute) + + up.mu.Lock() + up.block = make(chan struct{}) + up.mu.Unlock() + done := make(chan Outcome) + go func() { done <- ask("a") }() + for up.calls() < 3 { + time.Sleep(time.Millisecond) + } + if got := ask("b"); got != OutcomeRateLimited { + t.Fatalf("global in-flight cap: %s", got) + } + if got := ask("a"); got != OutcomeRateLimited { + t.Fatalf("per-person in-flight cap: %s", got) + } + close(up.block) + if got := <-done; got != OutcomeOK { + t.Fatalf("blocked call: %s", got) + } +} + +func TestUpstreamFailuresFallBackAndTripTheBreaker(t *testing.T) { + clock := &fakeClock{t: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)} + up := &fakeUpstream{} + var logs bytes.Buffer + svc := newTestService(t, up, allowAll{}, generous, &logs, clock) + ask := func() Result { return svc.Ask(context.Background(), Request{Person: "a", Question: "q?"}) } + + // A vendor 429 is "busy", backs everyone off and is not a breaker failure. + up.set(UpstreamAnswer{}, &UpstreamStatusError{Status: http.StatusTooManyRequests, RetryAfter: 10 * time.Second}) + if r := ask(); r.Outcome != OutcomeRateLimited || r.RetryAfterSeconds != 10 { + t.Fatalf("429: %+v", r) + } + calls := up.calls() + if r := ask(); r.Outcome != OutcomeRateLimited || up.calls() != calls { + t.Fatalf("backoff not honoured: %+v", r) + } + clock.advance(11 * time.Second) + + up.set(UpstreamAnswer{}, context.DeadlineExceeded) + for i := 0; i < DefaultBreakerFailures; i++ { + if r := ask(); r.Outcome != OutcomeUpstreamError || r.DocsURL == "" { + t.Fatalf("failure %d: %+v", i, r) + } + } + calls = up.calls() + if r := ask(); r.Outcome != OutcomeBreakerOpen || up.calls() != calls { + t.Fatalf("open breaker still called out: %+v", r) + } + if !strings.Contains(logs.String(), "audit: ask breaker opened") { + t.Fatal("no breaker-open audit line") + } + clock.advance(DefaultBreakerCooldown) + up.set(citedAnswer, nil) + if r := ask(); r.Outcome != OutcomeOK { + t.Fatalf("trial after cool-down: %+v", r) + } + if !strings.Contains(logs.String(), "audit: ask breaker closed") || svc.Stats().BreakerOpen { + t.Fatal("breaker did not close") + } + if strings.Contains(logs.String(), "q?") { + t.Fatal("audit lines carry the question") + } +} + +func TestUpstreamTimeoutIsAFallback(t *testing.T) { + up := &fakeUpstream{block: make(chan struct{})} + defer close(up.block) + svc, err := NewService(Options{Upstream: up, Limits: generous, Consent: allowAll{}, UpstreamTimeout: 10 * time.Millisecond}) + if err != nil { + t.Fatal(err) + } + if r := svc.Ask(context.Background(), Request{Person: "a", Question: "q?"}); r.Outcome != OutcomeUpstreamError { + t.Fatalf("timeout: %+v", r) + } +} + +func TestConversationsAreBoundToPersonAndHive(t *testing.T) { + up := &fakeUpstream{answer: citedAnswer} + svc := newTestService(t, up, allowAll{}, generous, nil, nil) + first := svc.Ask(context.Background(), Request{Person: "alice", HiveID: "hive-a", Question: "q?"}) + if first.Conversation == "" || strings.Contains(first.Conversation, citedAnswer.ThreadID) { + t.Fatalf("handle %q must be opaque", first.Conversation) + } + svc.Ask(context.Background(), Request{Person: "alice", HiveID: "hive-a", Question: "and?", Conversation: first.Conversation}) + svc.Ask(context.Background(), Request{Person: "bob", HiveID: "hive-a", Question: "and?", Conversation: first.Conversation}) + svc.Ask(context.Background(), Request{Person: "alice", HiveID: "hive-b", Question: "and?", Conversation: first.Conversation}) + want := []string{"", citedAnswer.ThreadID, "", ""} + for i, got := range up.threads { + if got != want[i] { + t.Fatalf("call %d used thread %q, want %q", i, got, want[i]) + } + } +} + +func TestNewServiceNeedsUpstream(t *testing.T) { + if _, err := NewService(Options{}); err == nil { + t.Fatal("a service without an upstream must be refused") + } +} diff --git a/src/pkg/askai/sources.go b/src/pkg/askai/sources.go new file mode 100644 index 0000000000..8a09918627 --- /dev/null +++ b/src/pkg/askai/sources.go @@ -0,0 +1,151 @@ +package askai + +import ( + "net/url" + "regexp" + "strings" + "unicode" + "unicode/utf8" +) + +const ( + // DocsHost is the published docs site, the source of record. + DocsHost = "docs.hivecommons.dev" + // DocsHomeURL is the fallback link when no section page applies. + DocsHomeURL = "https://" + DocsHost + "/" + // githubHost and githubDocsRepoPrefix admit the GitHub docs path the + // dashboard's own help marks point at (dashboardDocsHref). + githubHost = "github.com" + githubDocsRepoPrefix = "/hivecommons/hive/" + githubDocsPathMarker = "/src/docs/" + + // MaxSources caps the sources shown with one answer. + MaxSources = 5 + // maxSourceTitleRunes caps a source title. + maxSourceTitleRunes = 120 + // MaxAnswerRunes caps the answer text returned to the page. + MaxAnswerRunes = 4000 + // answerTruncatedSuffix marks a capped answer. + answerTruncatedSuffix = " [answer shortened]" + // removedLinkText replaces a URL that is not on the allowlist. + removedLinkText = "(link removed)" +) + +// githubDocsKinds are the GitHub URL kinds that show a docs file. +var githubDocsKinds = []string{"blob/", "tree/"} + +// Source is a citation that passed the allowlist. +type Source struct { + Title string `json:"title"` + URL string `json:"url"` +} + +// AllowedSourceURL reports whether raw is an https link to the docs site or +// to a docs page under hivecommons/hive on GitHub, and returns it in a +// canonical form (no userinfo, no port, no query). +func AllowedSourceURL(raw string) (string, bool) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || u.Opaque != "" { + return "", false + } + host := strings.ToLower(u.Hostname()) + switch host { + case DocsHost: + case githubHost: + rest, ok := strings.CutPrefix(u.Path, githubDocsRepoPrefix) + if !ok { + return "", false + } + kindOK := false + for _, kind := range githubDocsKinds { + if strings.HasPrefix(rest, kind) { + kindOK = true + } + } + if !kindOK || !strings.Contains(rest, githubDocsPathMarker) || strings.Contains(u.Path, "..") { + return "", false + } + default: + return "", false + } + clean := url.URL{Scheme: "https", Host: host, Path: u.Path, Fragment: u.Fragment} + return clean.String(), true +} + +// FilterSources keeps allowlisted, non-internal sources, deduplicated and +// capped at MaxSources. +func FilterSources(in []UpstreamSource) []Source { + seen := map[string]bool{} + var out []Source + for _, s := range in { + if s.Internal { + continue + } + u, ok := AllowedSourceURL(s.URL) + if !ok || seen[u] { + continue + } + seen[u] = true + title := cleanText(s.Title, maxSourceTitleRunes, "") + if title == "" { + title = u + } + out = append(out, Source{Title: title, URL: u}) + if len(out) == MaxSources { + break + } + } + return out +} + +var ( + // markdownLinkPattern matches [text](target) and ![alt](target). + markdownLinkPattern = regexp.MustCompile(`!?\[([^\]\n]*)\]\([^)\n]*\)`) + // bareURLPattern matches a scheme URL in running text. + bareURLPattern = regexp.MustCompile(`(?i)\b[a-z][a-z0-9+.-]*://[^\s<>()"']+`) +) + +// SanitizeAnswer turns vendor answer text into plain text for the panel: +// control characters dropped, markdown links reduced to their text (links are +// shown only from the filtered sources), any URL not on the allowlist removed, +// and the length capped. The page renders the result as text, never as HTML. +func SanitizeAnswer(s string) string { + s = markdownLinkPattern.ReplaceAllString(s, "$1") + s = bareURLPattern.ReplaceAllStringFunc(s, func(m string) string { + if u, ok := AllowedSourceURL(strings.TrimRight(m, ".,;:!?")); ok { + return u + } + return removedLinkText + }) + return cleanText(s, MaxAnswerRunes, answerTruncatedSuffix) +} + +// cleanText drops control characters (keeping newlines and tabs in answers), +// trims, and caps at maxRunes with suffix appended when it cut. +func cleanText(s string, maxRunes int, suffix string) string { + if !utf8.ValidString(s) { + s = strings.ToValidUTF8(s, "") + } + var b strings.Builder + keepLayout := suffix != "" + for _, r := range s { + if r == '\n' || r == '\t' { + if keepLayout { + b.WriteRune(r) + } else { + b.WriteRune(' ') + } + continue + } + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + continue + } + b.WriteRune(r) + } + out := strings.TrimSpace(b.String()) + if utf8.RuneCountInString(out) <= maxRunes { + return out + } + runes := []rune(out) + return strings.TrimSpace(string(runes[:maxRunes])) + suffix +} diff --git a/src/pkg/askai/store_test.go b/src/pkg/askai/store_test.go new file mode 100644 index 0000000000..cef0a62cba --- /dev/null +++ b/src/pkg/askai/store_test.go @@ -0,0 +1,122 @@ +package askai + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestAllowedSourceURL(t *testing.T) { + for raw, want := range map[string]string{ + "https://docs.hivecommons.dev/settings/#features": "https://docs.hivecommons.dev/settings/#features", + "https://DOCS.hivecommons.dev/a?utm=x": "https://docs.hivecommons.dev/a", + "https://github.com/hivecommons/hive/blob/v5/src/docs/dashboard-sections.md": "https://github.com/hivecommons/hive/blob/v5/src/docs/dashboard-sections.md", + "https://github.com/hivecommons/hive/tree/v5/src/docs/design": "https://github.com/hivecommons/hive/tree/v5/src/docs/design", + } { + got, ok := AllowedSourceURL(raw) + if !ok || got != want { + t.Errorf("AllowedSourceURL(%q) = %q, %v; want %q", raw, got, ok, want) + } + } + for _, raw := range []string{ + "http://docs.hivecommons.dev/a", + "https://docs.hivecommons.dev.evil.example/a", + "https://user:pw@docs.hivecommons.dev/a", + "https://docs.hivecommons.dev:8443/a", + "https://github.com/hivecommons/hive/blob/v5/src/pkg/hub/ask.go", + "https://github.com/someone/hive/blob/v5/src/docs/a.md", + "https://github.com/hivecommons/hive/issues/1", + "https://github.com/hivecommons/hive/blob/v5/src/docs/../../README.md", + "javascript:alert(1)", + "", + } { + if got, ok := AllowedSourceURL(raw); ok { + t.Errorf("AllowedSourceURL(%q) admitted %q", raw, got) + } + } +} + +func TestFilterSourcesCapsAndSanitizes(t *testing.T) { + var in []UpstreamSource + for i := 0; i < MaxSources+3; i++ { + in = append(in, UpstreamSource{URL: "https://docs.hivecommons.dev/p" + strings.Repeat("x", i), Title: strings.Repeat("t", maxSourceTitleRunes*2)}) + } + out := FilterSources(in) + if len(out) != MaxSources { + t.Fatalf("kept %d sources, want %d", len(out), MaxSources) + } + if n := len([]rune(out[0].Title)); n != maxSourceTitleRunes { + t.Fatalf("title length %d", n) + } + if got := FilterSources([]UpstreamSource{{URL: "https://docs.hivecommons.dev/a", Title: " "}}); got[0].Title != "https://docs.hivecommons.dev/a" { + t.Fatalf("empty title fallback: %+v", got) + } + long := SanitizeAnswer(strings.Repeat("a", MaxAnswerRunes+10)) + if !strings.HasSuffix(long, answerTruncatedSuffix) || len([]rune(long)) != MaxAnswerRunes+len([]rune(answerTruncatedSuffix)) { + t.Fatalf("answer cap: %d runes", len([]rune(long))) + } +} + +func TestSectionVocabularyIsClosed(t *testing.T) { + if _, ok := SectionLabel("settings-features"); !ok { + t.Fatal("settings-features must be in the vocabulary") + } + for _, id := range []string{"", "acme/private-repo", "` + +var ( + dashboardHTMLWithAsk = strings.Replace(dashboardHTML, askPanelMarker, askPanelTags, 1) + dashboardHTMLWithAskETag = webstatic.ETagFor([]byte(dashboardHTMLWithAsk)) +) + +// dashboardDocument returns the dashboard bytes and ETag for this hub: the +// panel tags only when Ask is on, the unchanged document otherwise. +func (s *HubServer) dashboardDocument() (string, string) { + if s.ask != nil { + return dashboardHTMLWithAsk, dashboardHTMLWithAskETag + } + return dashboardHTML, dashboardHTMLETag +} + +func serveAskAsset(contentType string, data []byte) http.HandlerFunc { + etag := webstatic.ETagFor(data) + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + if webstatic.WriteCacheHeaders(w, r, etag) { + return + } + _, _ = w.Write(data) + } } // requireAskSession admits the person's signed browser session only: no API diff --git a/src/pkg/hub/ask_panel_test.go b/src/pkg/hub/ask_panel_test.go new file mode 100644 index 0000000000..9558a298a6 --- /dev/null +++ b/src/pkg/hub/ask_panel_test.go @@ -0,0 +1,92 @@ +package hub + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestHubDashboardCarriesThePanelOnlyWhenAskIsOn is the "off is inert" +// tripwire for the hub panel: with Ask off the dashboard document is the +// embedded bytes unchanged, the panel assets are not served, and the +// security headers are identical on and off. +func TestHubDashboardCarriesThePanelOnlyWhenAskIsOn(t *testing.T) { + type snapshot struct { + body string + headers http.Header + asset int + } + take := func(on bool) snapshot { + s, _ := newAskTestHub(t, on, &askFakeUpstream{}) + s.mux.HandleFunc("GET /dashboard", s.handleDashboard) + w := askDo(s, "GET", "/dashboard", "", "alice", nil) + if w.Code != http.StatusOK { + t.Fatalf("dashboard %d", w.Code) + } + asset := askDo(s, "GET", askPanelJSPath, "", "alice", nil) + return snapshot{body: w.Body.String(), headers: w.Header(), asset: asset.Code} + } + off, on := take(false), take(true) + + if off.body != dashboardHTML || strings.Contains(off.body, askPanelJSPath) || off.asset != http.StatusNotFound { + t.Fatalf("off: document changed or panel served (asset %d)", off.asset) + } + if !strings.Contains(on.body, askPanelTags) || strings.Contains(on.body, askPanelMarker) || on.asset != http.StatusOK { + t.Fatalf("on: panel tags missing (asset %d)", on.asset) + } + if strings.Count(dashboardHTML, askPanelMarker) != 1 || strings.Count(dashboardHTML, `id="hive-ask-slot"`) != 1 { + t.Fatal("the dashboard must hold exactly one panel marker and one opener slot") + } + for _, h := range []string{"Content-Security-Policy", "Content-Security-Policy-Report-Only", "X-Frame-Options", "Referrer-Policy"} { + if off.headers.Get(h) != on.headers.Get(h) { + t.Errorf("%s differs with Ask on: %q vs %q", h, off.headers.Get(h), on.headers.Get(h)) + } + } + if off.headers.Get("ETag") == on.headers.Get("ETag") { + t.Error("the two documents must not share an ETag") + } + // The only additions are same-origin: no third-party host, no inline script. + added := strings.Replace(on.body, askPanelTags, "", 1) + if added != strings.Replace(dashboardHTML, askPanelMarker, "", 1) { + t.Fatal("Ask on changed the document beyond the panel tags") + } + for _, bad := range []string{"http://", "https://", " + diff --git a/src/pkg/hub/saas_pages.go b/src/pkg/hub/saas_pages.go index 13b1a8e934..c6957e846f 100644 --- a/src/pkg/hub/saas_pages.go +++ b/src/pkg/hub/saas_pages.go @@ -50,10 +50,11 @@ func (s *HubServer) handleDashboard(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "text/html; charset=utf-8") - if webstatic.WriteCacheHeaders(w, r, dashboardHTMLETag) { + doc, etag := s.dashboardDocument() + if webstatic.WriteCacheHeaders(w, r, etag) { return } - _, _ = fmt.Fprint(w, dashboardHTML) + _, _ = fmt.Fprint(w, doc) } func (s *HubServer) handleAccessDenied(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/hub/scale_settings.go b/src/pkg/hub/scale_settings.go index ecd8bc398c..c4332deba6 100644 --- a/src/pkg/hub/scale_settings.go +++ b/src/pkg/hub/scale_settings.go @@ -188,6 +188,8 @@ func (s *HubServer) handleGetScaleSettings(w http.ResponseWriter, r *http.Reques // the same number the operator typed. 0 = debouncing disabled. "upgrade_debounce_seconds": int(autoUpgradeDebounceInterval() / time.Second), "customers_share_enabled": customersShareEnabled(), + // Ask AI help (#19181): on only when switched on AND configured. + "ask_enabled": s.ask != nil, }, Clusters: rows, Defaults: map[string]int{ From 4b2c45e0c30b3721a0ec7106ed3cbeabf4f05fd4 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:14:40 -0500 Subject: [PATCH 05/11] =?UTF-8?q?=E2=9C=A8=20ask:=20hive=20backend=20and?= =?UTF-8?q?=20hub=20relay=20for=20optional=20Ask=20AI=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the ask block to hive.yaml (vendor ids never serialised to JSON and redacted in the config export), the hive dashboard routes GET /api/ask/status, PUT/DELETE /api/ask/consent and POST /api/ask (404 while off), per-person consent on the hive keyed by dashboard identity, direct mode with the hive's own key, and hub mode through a new POST /api/hub/ask/relay on the hub. The relay authenticates the hive with its per-hive heartbeat bearer, serves hosted hives only in this round, honours a per-hive disable list and an hourly per-hive quota, and binds conversation handles to the hive. Settings, Features gains the Ask switch, mode and section-label toggle. Fixes #19183 Signed-off-by: Andy Anderson --- changelog.d/added-19183-ask-hive-backend.md | 1 + dashboard/openapi.json | 217 ++++++++++++ src/docs/api-reference/agents-and-controls.md | 72 ++-- src/docs/api-reference/auth.md | 28 +- src/docs/api-reference/beads.md | 10 +- src/docs/api-reference/configuration.md | 192 +++++------ .../api-reference/cost-tokens-telemetry.md | 16 +- src/docs/api-reference/dashboard-misc.md | 70 ++-- .../api-reference/health-status-events.md | 38 +- src/docs/api-reference/hub-saas.md | 1 + src/docs/api-reference/hub-server.md | 68 ++-- src/docs/api-reference/inception.md | 28 +- src/docs/api-reference/knowledge.md | 92 ++--- src/docs/api-reference/nous.md | 50 +-- src/docs/api-reference/packs-and-acmm.md | 36 +- src/docs/api-reference/snapshots-and-style.md | 8 +- src/docs/ask-ai-help.md | 98 ++++++ src/docs/documentation-map.md | 1 + src/docs/hub-deployment.md | 10 + src/docs/settings.md | 1 + src/docs/telemetry.md | 2 +- src/pkg/askai/consent.go | 24 ++ src/pkg/askai/limits.go | 21 +- src/pkg/askai/relay.go | 213 ++++++++++++ src/pkg/askai/relay_test.go | 240 +++++++++++++ src/pkg/askai/service.go | 23 +- src/pkg/config/ask.go | 20 +- src/pkg/config/config.go | 4 + src/pkg/dashboard/api.go | 5 + src/pkg/dashboard/api_ask.go | 320 +++++++++++++++++ src/pkg/dashboard/api_ask_test.go | 324 ++++++++++++++++++ src/pkg/dashboard/api_config_export.go | 10 + src/pkg/dashboard/api_governor_features.go | 10 + .../dashboard/openapi_schema_parity_test.go | 5 + src/pkg/dashboard/server.go | 1 + .../static-src/js/config-features.js | 13 + src/pkg/dashboard/static/index.html | 13 + src/pkg/hub/ask.go | 3 + src/pkg/hub/ask_relay.go | 80 +++++ src/pkg/hub/ask_relay_test.go | 165 +++++++++ src/pkg/prosefilter/outbound_sites_test.go | 1 + 41 files changed, 2168 insertions(+), 366 deletions(-) create mode 100644 changelog.d/added-19183-ask-hive-backend.md create mode 100644 src/docs/ask-ai-help.md create mode 100644 src/pkg/askai/relay.go create mode 100644 src/pkg/askai/relay_test.go create mode 100644 src/pkg/dashboard/api_ask.go create mode 100644 src/pkg/dashboard/api_ask_test.go create mode 100644 src/pkg/hub/ask_relay.go create mode 100644 src/pkg/hub/ask_relay_test.go diff --git a/changelog.d/added-19183-ask-hive-backend.md b/changelog.d/added-19183-ask-hive-backend.md new file mode 100644 index 0000000000..f064fd2b11 --- /dev/null +++ b/changelog.d/added-19183-ask-hive-backend.md @@ -0,0 +1 @@ +- Hive owners can turn on Ask AI help in Settings, Features (`ask.enabled`, `ask.mode`): a hosted hive asks through a new hub relay with its existing per-hive heartbeat bearer and holds no Kapa key, a self-hosted hive can use direct mode with its own key. Per-person consent is kept on the hive, the hub charges each hive an hourly quota and serves hosted hives only in this round, and every route answers 404 while Ask is off ([#19183](https://github.com/hivecommons/hive/issues/19183)). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 95e1bec11f..03346cbd7d 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -29715,6 +29715,223 @@ } } }, + "/api/ask/status": { + "get": { + "tags": [ + "System" + ], + "summary": "Ask AI help status", + "description": "Whether the optional Ask AI help panel is on for the signed-in person, the disclosure they must confirm and whether they have. Answers 404 unless ask.enabled is on and fully configured (see src/docs/design/dashboard-ask-ai-help.md, #19183). Never returns the vendor key, project id or integration id.", + "responses": { + "200": { + "description": "Status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "text_version": { + "type": "string" + }, + "disclosure": { + "type": "string" + }, + "consented": { + "type": "boolean" + }, + "docs_url": { + "type": "string" + }, + "ai_label": { + "type": "string" + } + } + } + } + } + }, + "401": { + "description": "Not signed in" + }, + "404": { + "description": "Ask is off" + } + } + } + }, + "/api/ask/consent": { + "put": { + "tags": [ + "System" + ], + "summary": "Confirm the Ask disclosure", + "description": "Records the signed-in person's consent to the disclosure version the page showed. One audit line, no text. Answers 404 unless ask.enabled is on and fully configured (see src/docs/design/dashboard-ask-ai-help.md, #19183).", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "text_version": { + "type": "string" + } + }, + "required": [ + "text_version" + ] + } + } + } + }, + "responses": { + "204": { + "description": "Recorded" + }, + "400": { + "description": "Invalid JSON" + }, + "401": { + "description": "Not signed in" + }, + "404": { + "description": "Ask is off" + }, + "409": { + "description": "The disclosure text changed; reload and confirm again" + } + } + }, + "delete": { + "tags": [ + "System" + ], + "summary": "Withdraw Ask consent", + "description": "Withdraws the signed-in person's consent; takes effect on the next question. Answers 404 unless ask.enabled is on and fully configured (see src/docs/design/dashboard-ask-ai-help.md, #19183).", + "responses": { + "204": { + "description": "Withdrawn (or nothing to withdraw)" + }, + "401": { + "description": "Not signed in" + }, + "404": { + "description": "Ask is off" + } + } + } + }, + "/api/ask": { + "post": { + "tags": [ + "System" + ], + "summary": "Ask a docs-help question", + "description": "Validates the question (length cap; credential-shaped input is refused and nothing is sent), checks consent and limits, then asks Kapa.ai directly (ask.mode direct) or through the hub relay (ask.mode hub, hosted hives). Only the question and, when on, the label of the dashboard section from a closed list of ids leave the hive. Answers without an allowlisted source come back as no_cited_answer. Always 200 with an outcome. Answers 404 unless ask.enabled is on and fully configured (see src/docs/design/dashboard-ask-ai-help.md, #19183).", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "maxLength": 1000 + }, + "section": { + "type": "string" + }, + "conversation": { + "type": "string" + } + }, + "required": [ + "question" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Result", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "outcome": { + "type": "string", + "enum": [ + "ok", + "no_cited_answer", + "refused_secret_shape", + "rate_limited", + "breaker_open", + "upstream_error", + "not_consented", + "invalid_question", + "relay_disabled" + ] + }, + "answer": { + "type": "string", + "description": "Plain text; render as text, never as HTML." + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "url": { + "type": "string" + } + } + } + }, + "uncertain": { + "type": "boolean" + }, + "conversation": { + "type": "string", + "description": "Opaque follow-up handle bound to this person; the vendor thread id never leaves the server." + }, + "retry_after_seconds": { + "type": "integer" + }, + "message": { + "type": "string" + }, + "ai_generated": { + "type": "boolean" + }, + "docs_url": { + "type": "string" + } + } + } + } + } + }, + "400": { + "description": "Invalid JSON" + }, + "401": { + "description": "Not signed in" + }, + "404": { + "description": "Ask is off" + } + } + } + }, "/api/feedback/nps/status": { "get": { "tags": [ diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index 433c8c77ed..c3f51795fe 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -6,49 +6,49 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:121` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:125` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:126` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:130` | | `GET` | `/api/kick-outcomes` | Dashboard auth/session; detail for owner and read-write | What each kick of an agent came to ([#18916](https://github.com/hivecommons/hive/issues/18916)). Without `?agent=`, every agent's latest kick as `{kind, summary, at}` under `agents`. With `?agent=`, that agent's last ten kicks under `kicks`, newest first, each with `trigger_kind` (`dashboard`, `governor`, `workflow_dispatch`, `other`), `trigger_actor`, `started_at`, `ended_at`, `pr_url`/`pr_number`, `branch`/`sha`, `refusal_code` (a [kick-refusals](../kick-refusals.md) reason) and `quote`; a read-only session gets only the latest one-line summary. `kind` is one of `opened_pr`, `pushed_commit`, `commented`, `stood_down`, `refused`, `still_running`, `ended_no_visible_action`, derived from real signals only. `quote` is untrusted agent text (redacted, capped): escape it. Not reachable by agents. `503` without the store | `pkg/dashboard/api_kick_outcomes.go:49` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:126` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:127` | -| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:128` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:129` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:130` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:131` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:132` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:133` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:134` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:135` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:136` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:140` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:157` | -| `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, Wilson 95% `*_ci` intervals on the rates (omitted when the denominator is 0), a `coverage` block (closed-PR lookback and run-log partiality, as on `/api/contribute/effective-models`), `earliest_pr_created_at`, the top 10 most-reworked PRs, and per-bucket `hive_cost` (`usd`, `launches`, `prs_with_cost`, `usd_per_merged_pr`: the hive's estimated review/fix spend on that model's PRs from the cached `/api/launch-cost` snapshot; `usd` is `null`, not `0`, when nothing was attributed; omitted while the snapshot is not ready) with a top-level `hive_cost_coverage` (`ready`, `window_hours`, `unattributed_usd`, `backend_unsupported_usd`, `disclaimer`). Optional `model=` (matched after `modelfamily.Canonical`, so raw spellings such as `anthropic/claude-opus-5-5` work) adds `prs[]`: every PR in the window in that model's bucket, with the `most_reworked` fields plus `outcome` (`merged` / `closed_unmerged` / `open`), `agent`, `created_at`, `merged_at` and `first_pass`, sorted by review rounds + fix attempts then newest, capped at 200 with `prs_truncated: true` past that. An unknown model returns `prs: []`; without `model` the response is unchanged | `pkg/dashboard/api.go:158` | -| `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:221` | -| `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:505` | -| `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:508` | -| `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:509` | -| `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:513` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:131` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:132` | +| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:133` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:134` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:135` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:136` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:137` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:138` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:139` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:140` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:141` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:145` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:162` | +| `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, Wilson 95% `*_ci` intervals on the rates (omitted when the denominator is 0), a `coverage` block (closed-PR lookback and run-log partiality, as on `/api/contribute/effective-models`), `earliest_pr_created_at`, the top 10 most-reworked PRs, and per-bucket `hive_cost` (`usd`, `launches`, `prs_with_cost`, `usd_per_merged_pr`: the hive's estimated review/fix spend on that model's PRs from the cached `/api/launch-cost` snapshot; `usd` is `null`, not `0`, when nothing was attributed; omitted while the snapshot is not ready) with a top-level `hive_cost_coverage` (`ready`, `window_hours`, `unattributed_usd`, `backend_unsupported_usd`, `disclaimer`). Optional `model=` (matched after `modelfamily.Canonical`, so raw spellings such as `anthropic/claude-opus-5-5` work) adds `prs[]`: every PR in the window in that model's bucket, with the `most_reworked` fields plus `outcome` (`merged` / `closed_unmerged` / `open`), `agent`, `created_at`, `merged_at` and `first_pass`, sorted by review rounds + fix attempts then newest, capped at 200 with `prs_truncated: true` past that. An unknown model returns `prs: []`; without `model` the response is unchanged | `pkg/dashboard/api.go:163` | +| `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:226` | +| `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:510` | +| `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:513` | +| `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:514` | +| `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:518` | | `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:15` | -| `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:517` | -| `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:518` | -| `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:520` | -| `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), `outcomes_by_author_family` and `outcomes_by_author_model` (the same outcome fields keyed by the author's model family and by canonical author model, `human` / `unknown` when no model was recorded; [#18720](https://github.com/hivecommons/hive/issues/18720)), `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:523` | -| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:524` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:306` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:307` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:308` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:309` | +| `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:522` | +| `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:523` | +| `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:525` | +| `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), `outcomes_by_author_family` and `outcomes_by_author_model` (the same outcome fields keyed by the author's model family and by canonical author model, `human` / `unknown` when no model was recorded; [#18720](https://github.com/hivecommons/hive/issues/18720)), `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:528` | +| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:529` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:311` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:312` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:313` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:314` | | `GET` | `/api/agents/discovered` | Dashboard auth/session | Agents declared under `.hive/agents/*.yaml` in allowlisted managed repos, with `status` `pending` / `invalid` / `approved` / `rejected` / `orphaned`; `enabled: false` when discovery is not running ([agent configuration](../agent-configuration.md#agents-declared-in-a-managed-repo-hiveagents)) | `pkg/dashboard/api_repo_agents.go:23` | | `POST` | `/api/agents/discovered/approve` | Owner only | Register a pending discovered agent: body `{id, name?, backend?, model?, mode?}`; sets `definition_source` (marked `discovered`) and, with a sibling `.md`, `prompt_source`; backend, model and mode come from the request, never the file | `pkg/dashboard/api_repo_agents.go:24` | | `POST` | `/api/agents/discovered/reject` | Owner only | Decline a pending discovered agent (body `{id}`); stays declined until the file is removed | `pkg/dashboard/api_repo_agents.go:25` | | `POST` | `/api/agents/discovered/refresh` | Owner only | Rescan every managed repo's `.hive/agents/` now and return the list | `pkg/dashboard/api_repo_agents.go:26` | -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:108` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:112` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:115` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:116` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:117` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:139` | +| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:113` | +| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:117` | +| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:120` | +| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:121` | +| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:122` | +| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:144` | ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 7a02fd4b8d..0492562941 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -5,13 +5,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:162` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:163` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:164` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:165` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:166` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:167` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:168` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:167` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:168` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:169` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:170` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:171` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:172` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:173` | | `GET` | `/api/claude-auth/status` | Dashboard auth/session | Claude Auth Status | `pkg/dashboard/claude_auth.go:54` | | `POST` | `/api/claude-auth/start` | Dashboard auth/session | Claude Auth Start | `pkg/dashboard/claude_auth.go:55` | | `POST` | `/api/claude-auth/exchange` | Dashboard auth/session | Claude Auth Exchange | `pkg/dashboard/claude_auth.go:56` | @@ -24,10 +24,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1808` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1809` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1810` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:567` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:568` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:569` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:570` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1809` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1810` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1811` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:572` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:573` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:574` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:575` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index 77af2eaa7b..d18b555e02 100644 --- a/src/docs/api-reference/beads.md +++ b/src/docs/api-reference/beads.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:489` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:490` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:491` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:492` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:493` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:494` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:495` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:496` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:497` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:498` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 68a1c163ee..4df93e74be 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -13,13 +13,13 @@ JSON, see [Editing `hive.yaml`](../editing-hive-yaml.md#view-yaml-or-export-effe | `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:51` | | `GET` | `/api/config/triggers` | Verified owner only | Ordered Event triggers, opaque `version`/ETag, existing agents and managed repository values/labels; applies on next evaluation without restart | `pkg/dashboard/api_event_triggers.go` | | `PUT` | `/api/config/triggers` | Verified owner only | Compile-to-bool and durably compare-and-save `{rules:[{name,agent,expr,priority}],preset?:{index,kind,repo}}`; exact `If-Match` required (428 missing, 412 stale), validation 400, persistence failure 500 leaves live rules unchanged. No enabled field or source/webhook installation | `pkg/dashboard/api_event_triggers.go` | -| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:195` | -| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:196` | +| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:200` | +| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:201` | | `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:60` | | `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:61` | | `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:52` | -| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:244` | -| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:245` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:249` | +| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:250` | | `GET` | `/api/config/export` | Owner only | Redacted JSON export of the effective config, layer files, side files, and provenance | `pkg/dashboard/api_config_export.go` | | `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:55` | | `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:56` | @@ -27,111 +27,111 @@ JSON, see [Editing `hive.yaml`](../editing-hive-yaml.md#view-yaml-or-export-effe | `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:62` | | `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:63` | -| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:177` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:178` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:179` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:180` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:181` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:182` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:183` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:184` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:185` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:186` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:187` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:188` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:189` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:190` | +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:182` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:183` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:184` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:185` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:186` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:187` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:188` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:189` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:190` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:191` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:192` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:193` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:194` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:195` | | `GET` | `/api/config/agent/{name}/variables` | Dashboard auth/session | Per-agent Variables tab: the agent's own `${VAR}` definitions plus the hive-level ones it inherits (each flagged `overridden` when the agent redefines it) and the seed-only exec/http gate flags. Never returns values — only name, type, scope and a non-secret source hint | `pkg/dashboard/api_variables.go:298` | | `PUT` | `/api/config/agent/{name}/variables/{var}` | Owner only | Create or update one per-agent variable (`static`/`env` only; `script`/`http` are 403 and seed-only; scope `template` or `both`; secret-looking static values rejected). Persisted on the agent entry; overrides a same-named hive-level variable in this agent's kick prompt | `pkg/dashboard/api_variables.go:299` | | `DELETE` | `/api/config/agent/{name}/variables/{var}` | Owner only | Delete one per-agent variable (404 for inherited hive-level variables — delete those via `/api/config/variables/{name}`) | `pkg/dashboard/api_variables.go:300` | -| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:191` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:193` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:196` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:198` | | `PATCH` | `/api/config/governor` | Owner only | Update `merge_train_stall_warn_s`; omitted values stay unchanged, 0 disables warnings; returns the effective interval | `pkg/dashboard/api_governor_merge_train.go` | -| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:197` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:198` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:205` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:206` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:210` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:211` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:223` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:224` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:225` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:226` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:227` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:202` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:203` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:211` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:215` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:216` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:228` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:229` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:230` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:231` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:232` | | `GET` | `/api/config/governor/backup` | Owner only | Backup Key Status (presence + safe source label; never the key value) | `pkg/dashboard/backup_key.go` | | `PUT` | `/api/config/governor/backup` | Owner only | Backup Key Set (64-hex AES-256 key; stored 0600, path-only in `hive.yaml`) | `pkg/dashboard/backup_key.go` | | `DELETE` | `/api/config/governor/backup` | Owner only | Backup Key Clear (backups are refused again) | `pkg/dashboard/backup_key.go` | -| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:273` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:274` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:275` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:278` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:279` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:280` | -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:199` | -| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:200` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:277` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:278` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:281` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:282` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:283` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:284` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:285` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:291` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:292` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:293` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:297` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:298` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:301` | +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:204` | +| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:205` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:282` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:283` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:286` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:287` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:288` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:289` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:290` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:296` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:297` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:298` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:302` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:303` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:306` | | `GET` | `/api/config/github/webhooks` | Owner only | Config GitHub Webhooks (payload URL, events, secret source, receiver health, App hook permissions) | `pkg/dashboard/api_github_webhook_setup.go:88` | | `POST` | `/api/config/github/webhooks/secret` | Owner only | Config GitHub Webhooks Generate Secret (returned once) | `pkg/dashboard/api_github_webhook_setup.go:89` | | `POST` | `/api/config/github/webhooks/create` | Owner only | Config GitHub Webhooks Create Hook (through the App installation) | `pkg/dashboard/api_github_webhook_setup.go:90` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:360` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:361` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:362` | -| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:352` | -| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:353` | -| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:354` | -| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:355` | -| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:356` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:357` | -| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:358` | -| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:531` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:365` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:366` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:367` | +| `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:357` | +| `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:358` | +| `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:359` | +| `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:360` | +| `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:361` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:362` | +| `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:363` | +| `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:536` | -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:202` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:203` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:204` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:207` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:212` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:216` | -| `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:527` | -| `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:528` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:558` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:559` | -| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:564` | -| `GET` | `/api/config/repos/parent-autoclose` | Owner only | `repos..parent_autoclose` for every monitored repo: the effective value (`true`, `epics_too`, `trackers_too` or `false`), whether the repo carries its own, the default and the four options the Settings editor offers ([#19070](https://github.com/hivecommons/hive/issues/19070)) | `pkg/dashboard/api.go:561` | -| `PUT` | `/api/config/repos/parent-autoclose` | Owner only | Set one monitored repo's parent auto-close policy: `{"repo": "owner/name", "value": "true" \| "epics_too" \| "trackers_too" \| "false"}`. `true` is the default and clears the override. 400 for a missing repo or an invalid value, 404 for a repo that is not monitored, 500 when the file could not be written (previous value restored). Applies without a restart; audited as `config_repo_parent_autoclose`. Parents a person reopened and tracking issues are never auto-closed under any value | `pkg/dashboard/api.go:562` | -| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:573` | -| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:574` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:219` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:222` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:228` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:229` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:230` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:234` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:235` | +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:207` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:208` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:209` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:212` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:217` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:220` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:221` | +| `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:532` | +| `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:533` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:563` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:564` | +| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:569` | +| `GET` | `/api/config/repos/parent-autoclose` | Owner only | `repos..parent_autoclose` for every monitored repo: the effective value (`true`, `epics_too`, `trackers_too` or `false`), whether the repo carries its own, the default and the four options the Settings editor offers ([#19070](https://github.com/hivecommons/hive/issues/19070)) | `pkg/dashboard/api.go:566` | +| `PUT` | `/api/config/repos/parent-autoclose` | Owner only | Set one monitored repo's parent auto-close policy: `{"repo": "owner/name", "value": "true" \| "epics_too" \| "trackers_too" \| "false"}`. `true` is the default and clears the override. 400 for a missing repo or an invalid value, 404 for a repo that is not monitored, 500 when the file could not be written (previous value restored). Applies without a restart; audited as `config_repo_parent_autoclose`. Parents a person reopened and tracking issues are never auto-closed under any value | `pkg/dashboard/api.go:567` | +| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:578` | +| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:579` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:224` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:227` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:233` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:234` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:235` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:239` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:240` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | -| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:241` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:243` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:247` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:248` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:249` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:250` | -| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:260` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:261` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:262` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:263` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:264` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:279` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:280` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:246` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:248` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:252` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:253` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:254` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:255` | +| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:265` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:266` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:267` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:268` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:269` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:284` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:285` | | `PUT` | `/api/workflows/enabled` | Owner only | Turn model-based stage derivation (`workflow.enabled`, [#17620](https://github.com/hivecommons/hive/issues/17620)) on or off from the dashboard, for hosted hives with no `hive.yaml` access. Body `{enabled: bool}`; persists `hive.yaml`; the stage engine and tracker read the live flag so it applies on the next derivation pass without a restart. Turning on also provisions every bound repository's model labels now (`warnings[]` lists repositories that could not be provisioned; the next sweep retries). Returns `{enabled, changed, bindings[], warnings?[]}`. Audited `workflow_enabled` / `workflow_disabled`; `400` on a non-boolean body | `pkg/dashboard/api_workflows.go:29` | | `POST` | `/api/workflows/dispatch` | Owner only | Send a model-owned item to its agent profile: the stage tracker's **Send to *profile*** on a row whose bound model hands its current state to a profile ([cncf/techdocs#395](https://github.com/cncf/techdocs/issues/395): Accepted → `techdocs-drafter`, Drafting → `techdocs-verifier`). Body `{repo, number}`. Reads the item fresh, resolves the agent (`workflow.dispatch.profiles..agent`, then the default order ending at the hive's issue worker or reviewer, at every step only an agent whose mode lets it do what the profile needs, [#18749](https://github.com/hivecommons/hive/issues/18749); a profile disabled for automatic dispatch still resolves), takes the agent claim on an issue first, kicks the agent, and records the hand-off as pending once the kick lands so the automatic pass does not repeat it; a later pass marks it not started if the agent declines or ends its turn without the deliverable. Returns `{status: "sent", ref, model, state, profile, agent, result}`. Audited `workflow_dispatch`; `404` when the model does not hand the state to a profile, `409` when no agent fills it (the message gives the reason, for example that no agent on the hive may open pull requests in the repository, and names the Settings → Repos picker), someone else holds the claim, or the agent is busy | `pkg/dashboard/api_workflows.go:30` | | `PUT` | `/api/workflows/dispatch/profiles` | Owner only | Pick the hive agent a bound model's profile is handed to ([#18690](https://github.com/hivecommons/hive/issues/18690)): the agent picker on a repository's workflow row in Settings → Repos. Body `{profile, agent}`; an empty `agent` clears the pin so the profile resolves by default again. Persists `workflow.dispatch.profiles..agent` in `hive.yaml` (the profile's `prompt_template` and `disabled` are kept); the next scheduler pass reads the live config, so no restart is needed. `agent` must be an enabled agent that is not a replica (`400` otherwise). Returns `{changed, profile, agent, dispatch, agents}`, where `dispatch` lists every bound repository's profiles as `{repo, profile, agent, source, mode, needs, pinned, disabled, problem, states, candidates, not_started}` (`problem` is why nothing fills the profile, including a pin to an agent whose mode does not let it do the profile's work; `candidates` lists each pinnable agent as `{agent, mode, qualifies, reason}`; `not_started` lists the hand-offs an agent declined or did not act on while their item still waits, as `{ref, repo, number, profile, state, agent, reason, at, attempts, retrying, next, reason_at, reason_age, reason_session, stale}` (`reason_at`, `reason_age` and `reason_session` say when and in which hand-off session the reason was decided, and `stale` is true once a newer hand-off of the item exists, so the reason is history and not the item's state now, [#18916](https://github.com/hivecommons/hive/issues/18916)), [#18749](https://github.com/hivecommons/hive/issues/18749)) and `agents` the agents that can be picked; `GET /api/workflows` and `PUT /api/workflows/bindings` carry the same two fields. Audited `workflow_dispatch_agent` | `pkg/dashboard/api_workflows.go:31` | diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index ccd9e48f90..900a83be70 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -5,16 +5,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:88` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:143` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:144` | -| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485); every `estimated.by_model[]` row carries `canonical_model` (`modelfamily.Canonical` of its `name`, the id PRs-by-model and run stats group by), while spend stays one row per raw model because prices are per raw model (#18718) | `pkg/dashboard/api.go:145` | +| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:93` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:148` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:149` | +| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485); every `estimated.by_model[]` row carries `canonical_model` (`modelfamily.Canonical` of its `name`, the id PRs-by-model and run stats group by), while spend stays one row per raw model because prices are per raw model (#18718) | `pkg/dashboard/api.go:150` | | `GET` | `/api/repo-activity` | Dashboard auth/session | Per-repo audited activity | `pkg/dashboard/api.go` | | `GET` | `/api/repo-cost` | Dashboard auth/session | Per-repo estimated token cost (interval join, cached) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost` | Dashboard auth/session | Per-issue / PR / head-SHA estimated token cost from kick launch attribution (cached; `?ref=owner/repo#N` narrows) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost/history` | Dashboard auth/session | Daily per-ref rollup of launch attribution (`daily_rollup[]`: `day`, `by_ref[]` with `ref`, `kind`, `launches`, `share_usd`), kept ~2 years on the `/data` PVC so cost per PR can be measured past the `/api/launch-cost` window | `pkg/dashboard/api.go` | -| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:151` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:154` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:156` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:156` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:159` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:161` | | `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, and `plan_type` when a provider reports one), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:65` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:153` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:158` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 7f7266e273..000615ad07 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -54,7 +54,11 @@ review are settled. | 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:64` | -| `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:500` | +| `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:505` | +| `GET` | `/api/ask/status` | Dashboard auth/session | Ask AI help status for the signed-in person (`enabled`, `text_version`, `disclosure`, `consented`, `docs_url`, `ai_label`); `404` unless `ask.enabled` is on and configured. See [Ask AI help](../ask-ai-help.md) | `pkg/dashboard/api.go:82` | +| `PUT` | `/api/ask/consent` | Dashboard auth/session | Confirm the Ask disclosure (`{text_version}`); `409` on an older text; `204` | `pkg/dashboard/api.go:83` | +| `DELETE` | `/api/ask/consent` | Dashboard auth/session | Withdraw Ask consent; `204` | `pkg/dashboard/api.go:84` | +| `POST` | `/api/ask` | Dashboard auth/session | Ask a docs-help question (`{question, section?, conversation?}`); always `200` with an `outcome`; direct mode calls Kapa.ai, hub mode the hub relay | `pkg/dashboard/api.go:85` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:67` | | `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:70` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:68` | @@ -62,40 +66,40 @@ review are settled. | `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:74` | | `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:75` | | `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:76` | -| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:87` | -| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:89` | -| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:90` | -| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:91` | - - -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:246` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:452` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:455` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:456` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:458` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:459` | +| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:92` | +| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:94` | +| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:95` | +| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:96` | + + +| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:251` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:457` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:460` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:461` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:463` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:464` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:215` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:216` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:217` | -| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:289` | -| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:290` | - -| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:538` | -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:100` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:105` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:119` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:141` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:159` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:160` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:172` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_why` `{source: filed-for-help|decision-pending|level-gate|hive-hold|needs-approval|triage|author|needs-human, reason}` on every row a person must move (with `needs_human: true`; `filed_for_help` names the agent whose marker is in an unclaimed issue's body); `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:173` | -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:174` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:175` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:365` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:429` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:430` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:461` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:495` | +| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:294` | +| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:295` | + +| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:543` | +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:105` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:110` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:124` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:146` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:164` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:165` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:177` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_why` `{source: filed-for-help|decision-pending|level-gate|hive-hold|needs-approval|triage|author|needs-human, reason}` on every row a person must move (with `needs_human: true`; `filed_for_help` names the agent whose marker is in an unclaimed issue's body); `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:178` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:179` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:180` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:370` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:434` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:435` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:466` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:500` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:351` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:352` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:353` | @@ -113,7 +117,7 @@ review are settled. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:378` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:379` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:380` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1815` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1816` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 14ce8935bd..1080e9b257 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -25,17 +25,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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:47` | | `GET` | `/api/version/contains` | Dashboard auth/session | Does the running build contain a PR or commit ([#18915](https://github.com/hivecommons/hive/issues/18915)): `?q=` returns `{query, commit?, running?, channel?, contains, reason?}`. `contains` is `yes`, `no` or `unknown`, computed from the commit this hive reports running (`hash` on `/api/version`) and repository ancestry; `unknown` (with `reason`) when the commit cannot be resolved, the lookup failed or the hive has no GitHub access, never a guess. An unmerged PR is `no`. `400` when `q` is neither a PR number nor a SHA | `pkg/dashboard/api_version_contains.go:113` | | `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:71` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1788` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1789` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1790` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1796` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1801` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1802` | -| `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:1803` | -| `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:1804` | -| `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:1805` | -| `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:1806` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1807` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1789` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1790` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1791` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1797` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1802` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1803` | +| `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:1804` | +| `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:1805` | +| `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:1806` | +| `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:1807` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1808` | | `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` | @@ -45,11 +45,11 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/swarm/themes` | Owner only | Set a per-repo swarm theme (`event_name`, `call_to_arms`, `leaderboard_title`). | `pkg/dashboard/swarm.go:316` | | `PATCH` | `/api/swarm/objectives` | Owner only | Update the active swarm SDLC objective checklist completion state. | `pkg/dashboard/swarm.go:317` | | `GET` | `/api/leaderboard/swarm` | Public | Stable public JSON record of swarm history, leaderboard, top players, and achievements. | `pkg/dashboard/swarm.go:318` | -| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:92` | -| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:93` | -| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:94` | -| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:96` | -| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:97` | -| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:98` | -| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:99` | -| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:95` | +| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:97` | +| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:98` | +| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:99` | +| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:101` | +| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:102` | +| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:103` | +| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:104` | +| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:100` | diff --git a/src/docs/api-reference/hub-saas.md b/src/docs/api-reference/hub-saas.md index b32867a2c2..8b30aff010 100644 --- a/src/docs/api-reference/hub-saas.md +++ b/src/docs/api-reference/hub-saas.md @@ -118,3 +118,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/ask/stats` | Hub admin | Ask cost view: counts by outcome, today's total against the daily budget, breaker state, effective limits. No per-person data | `pkg/hub/ask.go:135` | | `GET` | `/ask-panel.js` | Hub handler-specific | Ask AI help panel script (`pkg/askai/web/ask-panel.js`), served only when Ask is on; `404` otherwise | `pkg/hub/ask.go:136` | | `GET` | `/ask-panel.css` | Hub handler-specific | Ask AI help panel stylesheet, served only when Ask is on; `404` otherwise | `pkg/hub/ask.go:137` | +| `POST` | `/api/hub/ask/relay` | Per-hive heartbeat bearer | Ask AI help relay for hosted hives ([#19183](https://github.com/hivecommons/hive/issues/19183)): bearer plus `X-Hive-ID`; body `{question, section?, conversation?}` (no person field); answers the same result shape as `POST /api/ask` with `relay_disabled` for a hive that is not hosted, is listed in `HIVE_ASK_RELAY_DISABLED_HIVES`, or when `HIVE_ASK_RELAY_HIVES=none`. Charged against the hive's hourly quota and the hub-wide limits; conversation handles are bound to the hive. Registered only when Ask is on at the hub | `pkg/hub/ask.go` | diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 4b71dc889b..847a64b977 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -35,29 +35,29 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/benchmarks/ingest` | Per-hive heartbeat bearer | Spoke push target for anonymized [benchmark records](../benchmarks.md): body `{hive_id, records[]}`; the hub recomputes the hive hash from the authenticated id, rejects records whose `source.hive_id` differs (`401` bad bearer, `403` unregistered hive, `400` malformed), merges accepted records by id into `/data/benchmarks//.json` and returns `202 {accepted, rejected, files}` | `pkg/hub/benchmarks.go` | | `GET` | `/api/hub/benchmarks` | Public | Benchmark publisher status: `last_ingest_at`, `last_publish_at`, `last_publish_files`, `last_error`, `pending_files`, `hive_count`, `record_count` and per-hive-hash `hives{}` counts; the hub commits pending month files hourly to `hivecommons/benchmarks` (`HIVE_BENCHMARKS_REPO`) via its App identity | `pkg/hub/benchmarks.go` | | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:511` | -| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1831` | -| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1832` | +| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1832` | +| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1833` | | `GET` | `/activity` | Signed-in user | Fleet activity page ([#16063](https://github.com/hivecommons/hive/issues/16063)): read-only, data-free shell that polls `/api/hub/activity` every 15 s with `If-None-Match`. No session → `307` to `/login`; blocked user → `403`. Own Content-Security-Policy (scripts and styles from `'self'` only, `script-src-attr`/`style-src-attr` `'none'`), `Cache-Control: no-cache` + content `ETag`. See [Hub Fleet activity page](../hub-fleet-activity.md) | `pkg/hub/activity_page.go` | | `GET` | `/activity/public` | Public | Public-safe Fleet activity page ([#15966](https://github.com/hivecommons/hive/issues/15966)): the same data-free shell as `/activity`, served without a session; on this path the page polls `/api/hub/activity/public` with `credentials: 'omit'`. Source of the `twitch.tv/hivecommonsfleet` broadcast. Same CSP and cache headers as `/activity`. See [Hub Fleet activity page](../hub-fleet-activity.md#public-safe-view) | `pkg/hub/activity_public.go` | | `GET` | `/activity/assets/{name}` | Public | The shared tracker assets the Fleet activity page loads, byte-identical: the row asset (`pkg/webassets/trackerrow`, [#16062](https://github.com/hivecommons/hive/issues/16062)) and the `am.*` URL-view and display-playlist helpers (`pkg/webassets/trackerview`, [#16064](https://github.com/hivecommons/hive/issues/16064)); only names in `trackerrow.Files` or `trackerview.Files`, else `404`. `Cache-Control: no-cache` + content `ETag` | `pkg/hub/activity_page.go` | -| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1750` | -| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1751` | -| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1752` | -| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat. A request carrying `X-Hive-Activity-Update` is an activity-only update ([#15963](https://github.com/hivecommons/hive/issues/15963)): body `{"activity_update":{"hive_id","activity"}}`, the same per-hive bearer, accepted only for a hive already in the registry (`404` otherwise); it replaces the in-memory activity digest and nothing else, and the signed response carries `ok`, `activity_etag` and `activity_events_ack` (the highest activity event sequence number the hub holds for the hive, [#15964](https://github.com/hivecommons/hive/issues/15964); full heartbeat responses carry it too) | `pkg/hub/server.go:1753` | -| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1754` | -| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1765` | -| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1766` | -| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1767` | -| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1768` | +| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1751` | +| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1752` | +| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1753` | +| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat. A request carrying `X-Hive-Activity-Update` is an activity-only update ([#15963](https://github.com/hivecommons/hive/issues/15963)): body `{"activity_update":{"hive_id","activity"}}`, the same per-hive bearer, accepted only for a hive already in the registry (`404` otherwise); it replaces the in-memory activity digest and nothing else, and the signed response carries `ok`, `activity_etag` and `activity_events_ack` (the highest activity event sequence number the hub holds for the hive, [#15964](https://github.com/hivecommons/hive/issues/15964); full heartbeat responses carry it too) | `pkg/hub/server.go:1754` | +| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1755` | +| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1766` | +| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1767` | +| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1768` | +| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1769` | | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | | `GET` | `/api/hub/activity` | Signed-in user | Read-only hub-wide activity view ([#15951](https://github.com/hivecommons/hive/issues/15951), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)) merged from each spoke's heartbeat `activity` digest, held in hub memory only. Authorization is per user and per hive before aggregation: hub admins see every registered hive; everyone else only hives they own or hold an unexpired grant for; anonymous → `401`. Returns `hives[]` (`hive_id`, `name`, `status` `ok`/`stale`/`not_reporting`/`missing`, `reporting`, `stale` once the block is older than two heartbeats, `last_heartbeat`, `received_at`, `generated_at`, `totals` — `items`, `by_stage`, `by_modifier`, counting private and truncated items too — `truncated` and `events_dropped`), `items[]` (`hive_id`, `repo`, `n`, `kind`, `title`, `author_kind`, `stage`, `stage_n`, `since`, `mods`, `private`) ordered needs-human/needs-decision, stalled, furthest stage, oldest, a response-level `truncated` (cap 2000), and `events[]` ([#15964](https://github.com/hivecommons/hive/issues/15964): `hive_id`, `received_at`, `seq`, `type` `opened`/`stage`/`merged`, `repo`, `n`, `kind`, `title`, `from`, `stage`, `at`, `private`), oldest first, from a fleet-wide in-memory ring of at most 1,000 events, none held longer than 24 hours (ageing out is not counted in `events_dropped`; when full, the oldest event of the hive holding the most events is dropped, counted in that hive's `events_dropped`, so one hive cannot evict the others' events). Events are filtered per user and per hive exactly like items, before aggregation, so an event for a hive the viewer cannot see is never delivered; `mod`/`author_kind` filters keep only events whose item is still on the hive's board. A spoke block carries at most 200 events; drops are disclosed per hive as `events_dropped`. New events change the `ETag`. Each digest carries at most 100 items by default and never more than the 250-item hub ceiling; private-repository items appear only when the spoke opts in. Filters: `hive`, `repo`, `stage`, `mod`, `author_kind`, `q` (title substring or `#`), each ≤ 200 characters (else `400`). `ETag` + `If-None-Match` → `304`; `Cache-Control: private, no-cache`, `Vary: Cookie, Authorization`. No actions | `pkg/hub/activity.go` | | `GET` | `/api/hub/activity/public` | Public | Public-safe activity view ([#15966](https://github.com/hivecommons/hive/issues/15966)): the `/api/hub/activity` shape for anyone, never reading a cookie, token or `Authorization` header (credentials do not change the response). Only hives the registry lists as public on github.com, and only items and events not marked `private`; `totals`, per-hive `truncated` and `events_dropped`, hive owners and per-user grants are omitted. Same filters (`400` on an invalid one). The body is built at most once per 2 s per parsed filter and shared by every anonymous caller, so rows, `generated_at` and the `ETag` change at most every 2 s; query strings that parse to the default view share one entry. Toggling a hive's visibility drops the cache at once. `ETag` + `If-None-Match` → `304`; `Cache-Control: no-cache` | `pkg/hub/activity_public.go` | -| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1776` | -| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1786` | -| `GET` | `/api/hub/selfservice/status` | Hub auth | Self-service registration status: `{enabled, max_per_user, count, expiry}`; always answers so the dashboard can decide whether **Register your own hive** opens the form or the self-hosting guide ([#18060](https://github.com/hivecommons/hive/issues/18060)) | `pkg/hub/server.go:1790` | -| `GET` | `/api/hub/selfservice/hives` | Hub auth | The caller's own self-service (`byo-`) hives: `{hives[]}` of `{id, owner, org, repos, dashboard_url, created_at, ownership_checked_at, last_accepted_heartbeat_at, online}`; never a key or a hash. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/server.go:1791` | -| `POST` | `/api/hub/selfservice/hives` | Hub auth | Register a self-hosted hive: body `{name, org, repos[], dashboard_url}`; the ID is `byo---` (the double hyphen keeps IDs unambiguous, since logins contain hyphens but never `--`). Proves `permissions.admin` on every `owner/name` repo with the caller's own stored GitHub token (`403` naming the refused repo, nothing stored); `400` invalid or reserved name, a login that contains `--` or starts or ends with `-`, bare-org or `.`/`..` repo, or non-`https`/private `dashboard_url`; `409` ID already registered; `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER` (enforced again under the store lock, so concurrent registrations cannot exceed it). `201 {hive, key, hub_url, snippets{docker_compose, podman, kubernetes}}`: the raw key appears here once and only its hash is stored. `404` while the flag is off | `pkg/hub/server.go:1792` | +| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1777` | +| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1787` | +| `GET` | `/api/hub/selfservice/status` | Hub auth | Self-service registration status: `{enabled, max_per_user, count, expiry}`; always answers so the dashboard can decide whether **Register your own hive** opens the form or the self-hosting guide ([#18060](https://github.com/hivecommons/hive/issues/18060)) | `pkg/hub/server.go:1791` | +| `GET` | `/api/hub/selfservice/hives` | Hub auth | The caller's own self-service (`byo-`) hives: `{hives[]}` of `{id, owner, org, repos, dashboard_url, created_at, ownership_checked_at, last_accepted_heartbeat_at, online}`; never a key or a hash. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/server.go:1792` | +| `POST` | `/api/hub/selfservice/hives` | Hub auth | Register a self-hosted hive: body `{name, org, repos[], dashboard_url}`; the ID is `byo---` (the double hyphen keeps IDs unambiguous, since logins contain hyphens but never `--`). Proves `permissions.admin` on every `owner/name` repo with the caller's own stored GitHub token (`403` naming the refused repo, nothing stored); `400` invalid or reserved name, a login that contains `--` or starts or ends with `-`, bare-org or `.`/`..` repo, or non-`https`/private `dashboard_url`; `409` ID already registered; `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER` (enforced again under the store lock, so concurrent registrations cannot exceed it). `201 {hive, key, hub_url, snippets{docker_compose, podman, kubernetes}}`: the raw key appears here once and only its hash is stored. `404` while the flag is off | `pkg/hub/server.go:1793` | | `GET` | `/api/hub/v1` | Public | Hub registration protocol v1 discovery ([#18642](https://github.com/hivecommons/hive/issues/18642)): `{protocol, version, base_path, operations[], patch_fields[], limits{max_repos, max_per_user, expiry, key_rotation_overlap}, proof_methods[]}`. Readable without signing in so a client learns the limits before it hits a `4xx`. `proof_methods` is `["hub-session-token"]`: ownership is proven with the GitHub token stored at hub sign-in. `max_repos` is `HIVE_HUB_SELFSERVICE_MAX_REPOS`. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_api.go` | | `POST` | `/api/hub/v1/registrations` | Hub auth | Register a self-hosted hive as a resource ([#18642](https://github.com/hivecommons/hive/issues/18642)): the same body, proof and refusals as `POST /api/hub/selfservice/hives` (including `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER`), except that a repo list over `HIVE_HUB_SELFSERVICE_MAX_REPOS` answers `413 {error, limit: "max_repos", max_repos}` instead of `400`. `201 {registration, key, hub_url, snippets}` with `Location` and a strong `ETag` header; `registration` is the legacy view plus `etag` and `repo_proofs[{repo, checked_at}]` (when the owner's admin permission on each repo was last proven). The raw key appears once. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_api.go` | | `GET` | `/api/hub/v1/registrations` | Hub auth | The caller's own registrations: `{registrations[]}`, each with its `etag` and `repo_proofs`; never a key or a hash | `pkg/hub/selfservice_v1_api.go` | @@ -65,26 +65,26 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PATCH` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner only, by hub session (a registration key is not accepted): change `repos` and/or `dashboard_url` in place with the heartbeat key kept valid ([#18642](https://github.com/hivecommons/hive/issues/18642)). Body: `repos` is a full list (replacement) or `{add[], remove[]}`; `dashboard_url` is an `https` URL or `""` to clear it. `If-Match` is required: `428` when absent, `412` carrying the current `ETag` when stale (checked before any GitHub call and again under the store lock). Only added repos are proven (`403` naming the first refused repo, nothing applied); kept repos keep their proof time and removed repos lose theirs. `org`, the owner, the ID and the keys are not editable: a body naming `org` or any other field is `400`, as is a list that would leave no repo. Over `HIVE_HUB_SELFSERVICE_MAX_REPOS` is `413 {error, limit: "max_repos", max_repos}`. Removing a repo the registration does not list is ignored; an edit that changes nothing answers `200` with the current `ETag` and does not bump the revision. `200 {registration}` with the new `ETag`; the key never appears. `404` for a missing hive, another user's hive and a hub admin who does not own it; `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_patch.go` | | `POST` | `/api/hub/v1/registrations/{id}/keys` | Hub auth | Owner only: rotate the heartbeat key; the previous key keeps authenticating for the 10 minute overlap. `201 {id, key, hub_url, overlap, snippets}` (the legacy rotate answers `200`) with the new `ETag`; the raw key appears once. Optional `If-Match` (`412` when stale). A body asking for a grace window is refused with `400`: caller-chosen grace is a later rollout step | `pkg/hub/selfservice_v1_api.go` | | `DELETE` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`. Optional `If-Match` (`412` when stale, carrying the current `ETag`) | `pkg/hub/selfservice_v1_api.go` | -| `POST` | `/api/hub/selfservice/hives/{id}/rotate` | Hub auth | Owner only: mint a new heartbeat key for `{id}`; the previous key keeps authenticating for `overlap` (10 minutes). `200 {id, key, hub_url, overlap, snippets}`, raw key once. Another user's hive, a missing hive and a hub admin who does not own it all get `404` | `pkg/hub/server.go:1793` | -| `DELETE` | `/api/hub/selfservice/hives/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`; another user's hive is `404` | `pkg/hub/server.go:1794` | -| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1798` | -| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1799` | -| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1800` | -| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1801` | +| `POST` | `/api/hub/selfservice/hives/{id}/rotate` | Hub auth | Owner only: mint a new heartbeat key for `{id}`; the previous key keeps authenticating for `overlap` (10 minutes). `200 {id, key, hub_url, overlap, snippets}`, raw key once. Another user's hive, a missing hive and a hub admin who does not own it all get `404` | `pkg/hub/server.go:1794` | +| `DELETE` | `/api/hub/selfservice/hives/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`; another user's hive is `404` | `pkg/hub/server.go:1795` | +| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1799` | +| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1800` | +| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1801` | +| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1802` | | `GET` | `/api/mail/hosts` | hive-mx bearer (`HIVE_HUB_MAIL_TOKEN`) | Hosts the mail receiver accepts `hive@` for ([#18395](https://github.com/hivecommons/hive/issues/18395)): `{hosts[]}`, sorted, lower-case: every hosted hive's subdomain host, vanity URL host and reported dashboard URL host. A host claimed by two hives is left out. `401` bad token, `404` while `HIVE_HUB_MAIL_TOKEN` is unset. `Cache-Control: no-store` | `pkg/hub/mail_relay.go` | | `POST` | `/api/mail/inbound` | hive-mx bearer (`HIVE_HUB_MAIL_TOKEN`) | One parsed mail delivery from hive-mx (`pkg/mailin/wire.Delivery`): JSON, or `multipart/form-data` for a large files delivery, routed by the `X-Hive-Mail-Delivery`, `X-Hive-Mail-Kind` and `X-Hive-Mail-Recipient` headers (at most 48 MiB, `HIVE_HUB_MAIL_MAX_BODY_BYTES`, this route only; without the headers, JSON of at most 8 MiB). The body is spooled to disk, never held whole in memory. The hub matches the recipient host to a hosted hive, signs the body byte for byte with that hive's relay key (`X-Hive-Relay-Timestamp`, `X-Hive-Relay-Signature-256` bound to `X-Hive-Relay-Delivery`) and forwards it to the spoke's `/api/meetings/invites`, `/api/inbox/email`, `/api/meetings/calendar-emails/proof` or `/api/inbox/email/report` (a refusal report, [#18699](https://github.com/hivecommons/hive/issues/18699)) by `kind`, behind the webhook relay's private-address guard and without following redirects. A files delivery that is multipart or larger than one piece (`HIVE_HUB_MAIL_CHUNK_BYTES`, 768 KiB) goes to `/api/inbox/email/chunk` in signed pieces instead ([#18564](https://github.com/hivecommons/hive/issues/18564)). Stores nothing once relayed; logs the delivery id only. `202` delivered; `400` invalid delivery; `404` no such hive; `413` too large; `422` the spoke refused it (permanent); `502`/`503` hive not reachable yet or unavailable (hive-mx asks the sender to retry) | `pkg/hub/mail_relay.go` | -| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1804` | -| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1805` | -| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1806` | -| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1809` | -| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1812` | -| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1813` | -| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1820` | -| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1821` | -| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1822` | -| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1839` | -| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1844` | -| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1846` | +| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1805` | +| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1806` | +| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1807` | +| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1810` | +| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1813` | +| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1814` | +| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1821` | +| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1822` | +| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1823` | +| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1840` | +| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1845` | +| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1847` | | `GET` | `/api/marketplace/workflows` | Public | Workflow-model marketplace index ([#17620](https://github.com/hivecommons/hive/issues/17620) phase 7): `{generatedAt, entries:[{name, version, hash, tier, description, source, states, columns, publishedAt, publishedBy, sourceSHA?, newerIngestAvailable, adoption:{}, ratings:{}, benchmarks:{}}]}`. Strong `ETag` (sha256 of the body) + `Cache-Control: no-cache`; `If-None-Match` → `304`. Tiers: `built-in`, `curated`, `ingested-unreviewed`, `local-published`. `404` when `HIVE_HUB_MARKETPLACE_DISABLED` is set | `pkg/hub/marketplace.go:36` | | `GET` | `/api/marketplace/workflows/{name}/{version}/bundle` | Public | One immutable signed bundle (`{apiVersion, model, profile, hash, createdAt, createdBy, tier}`), `Cache-Control: immutable`; `404` unknown, `400` malformed key | `pkg/hub/marketplace.go:37` | | `POST` | `/api/marketplace/workflows` | Spoke heartbeat bearer + `X-Hive-ID`, or Hub admin session | Publish a bundle. Body = bundle (≤ 4 MiB); the hub re-verifies the hash and recompiles the model before storing. Publisher may assert tier `local`/`local-published` (normalised to `local-published`) or `ingested-unreviewed`; `curated`/`built-in` require a hub admin session (`403` otherwise). `201 {published, created:true, entry}`; identical republish `200 created:false`; different content under an existing `name@version` `409`; verification failure `422`; unknown hive `403`; no hub secret `503` | `pkg/hub/marketplace.go:38` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 97d3005e48..1df4a164d7 100644 --- a/src/docs/api-reference/inception.md +++ b/src/docs/api-reference/inception.md @@ -7,17 +7,17 @@ The inception API was retired in favour of [Inception (spek) sessions](sessions. | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Dashboard auth/session | Retired (was: Inception Start): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:434` | -| `POST` | `/api/inception/scan` | Dashboard auth/session | Retired (was: Inception Scan): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:435` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Retired (was: Inception State): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:436` | -| `POST` | `/api/inception/questions` | Dashboard auth/session | Retired (was: Inception Set Questions): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:437` | -| `POST` | `/api/inception/answer` | Dashboard auth/session | Retired (was: Inception Answer): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:438` | -| `POST` | `/api/inception/facts` | Dashboard auth/session | Retired (was: Inception Record Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:439` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Retired (was: Inception Scaffold): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:440` | -| `POST` | `/api/inception/approve` | Dashboard auth/session | Retired (was: Inception Approve): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:441` | -| `POST` | `/api/inception/reset` | Dashboard auth/session | Retired (was: Inception Reset): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:442` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Retired (was: Inception Ideation Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:443` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Retired (was: Inception Download): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:444` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Retired (was: Inception Has Files): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:445` | -| `PUT` | `/api/inception/wiki-name` | Dashboard auth/session | Retired (was: Inception Rename Wiki): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:446` | -| `POST` | `/api/inception/import` | Dashboard auth/session | Retired (was: Inception Import): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:447` | +| `POST` | `/api/inception/start` | Dashboard auth/session | Retired (was: Inception Start): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:439` | +| `POST` | `/api/inception/scan` | Dashboard auth/session | Retired (was: Inception Scan): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:440` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Retired (was: Inception State): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:441` | +| `POST` | `/api/inception/questions` | Dashboard auth/session | Retired (was: Inception Set Questions): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:442` | +| `POST` | `/api/inception/answer` | Dashboard auth/session | Retired (was: Inception Answer): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:443` | +| `POST` | `/api/inception/facts` | Dashboard auth/session | Retired (was: Inception Record Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:444` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Retired (was: Inception Scaffold): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:445` | +| `POST` | `/api/inception/approve` | Dashboard auth/session | Retired (was: Inception Approve): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:446` | +| `POST` | `/api/inception/reset` | Dashboard auth/session | Retired (was: Inception Reset): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:447` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Retired (was: Inception Ideation Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:448` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Retired (was: Inception Download): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:449` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Retired (was: Inception Has Files): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:450` | +| `PUT` | `/api/inception/wiki-name` | Dashboard auth/session | Retired (was: Inception Rename Wiki): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:451` | +| `POST` | `/api/inception/import` | Dashboard auth/session | Retired (was: Inception Import): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:452` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index 2b22349dd2..e2c797074e 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -5,39 +5,39 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:367` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:368` | -| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | 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:378` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:369` | -| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:370` | -| `GET` | `/api/knowledge/advisor/summary` | Dashboard auth/session (read or higher) | Read-only knowledge-advisor rank-versus-holdout summary: `window` (`since`, `first_decision`, `last_decision`, `rank_mode_start`, `decisions`), `settings` (`enabled`, `mode`, `model`, `holdout_percent`, `max_calls_per_day`, `max_calls_per_agent_hour`, `candidates`, `on_error`; never the endpoint or key), `counts` (`by_mode`, `by_arm`, `by_outcome`), `arms` (per-arm closed-bead `beads` and mean fix attempts, CI failures and kicks from `Lane.AdvisorArmSummary()`) with `mixed` and `none` listed separately, `cost` (mean latency and tokens where records carry them), and a `small_n`/`caveat` pair. Counts and means only: no slugs, refs, agents or content. Query: `since` (RFC 3339) narrows the decision counts and cost, not the bead means ([docs](../retro-lane.md#reading-the-comparison-from-the-dashboard)) | `pkg/dashboard/api.go:371` | -| `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:372` | -| `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:373` | -| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:375` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:379` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:380` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:381` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:382` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:383` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:384` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:385` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:386` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:392` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:393` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:394` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:395` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:396` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:397` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:398` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:399` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:400` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:401` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:402` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:403` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:404` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:405` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:406` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:407` | +| `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:372` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:373` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | 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:383` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:374` | +| `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:375` | +| `GET` | `/api/knowledge/advisor/summary` | Dashboard auth/session (read or higher) | Read-only knowledge-advisor rank-versus-holdout summary: `window` (`since`, `first_decision`, `last_decision`, `rank_mode_start`, `decisions`), `settings` (`enabled`, `mode`, `model`, `holdout_percent`, `max_calls_per_day`, `max_calls_per_agent_hour`, `candidates`, `on_error`; never the endpoint or key), `counts` (`by_mode`, `by_arm`, `by_outcome`), `arms` (per-arm closed-bead `beads` and mean fix attempts, CI failures and kicks from `Lane.AdvisorArmSummary()`) with `mixed` and `none` listed separately, `cost` (mean latency and tokens where records carry them), and a `small_n`/`caveat` pair. Counts and means only: no slugs, refs, agents or content. Query: `since` (RFC 3339) narrows the decision counts and cost, not the bead means ([docs](../retro-lane.md#reading-the-comparison-from-the-dashboard)) | `pkg/dashboard/api.go:376` | +| `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:377` | +| `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:378` | +| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:380` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:384` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:385` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:386` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:387` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:388` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:389` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:390` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:391` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:397` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:398` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:399` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:400` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:401` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:402` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:403` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:404` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:405` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:406` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:407` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:408` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:409` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:410` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:411` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:412` | | `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, `running` and the live `progress` block (phase, items_done/items_total, current item, started_at; see [knowledge-connectors.md](../knowledge-connectors.md#api)), plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -47,19 +47,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/knowledge/agent-scopes` | Owner only | Replace `knowledge.agent_scopes` after validating layer and state names; persisted and audited as `config_knowledge_agent_scopes` | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/pipeline` | Owner only | Scalar bead synthesizer, curator, code map and primer settings and `knowledge.sidecar_advise`, plus the read-only engine, advisor flag, 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 and `sidecar_advise` apply 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:417` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:418` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:419` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:420` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:421` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:422` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:423` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:424` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:425` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:426` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:427` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:390` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:391` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:422` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:423` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:424` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:426` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:427` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:428` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:429` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:430` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:431` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:432` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:395` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:396` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses, each with a live `progress` block while a sync runs, and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](../knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:25` | | `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:26` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index b1cd9c0db0..d34a557ab8 100644 --- a/src/docs/api-reference/nous.md +++ b/src/docs/api-reference/nous.md @@ -5,28 +5,28 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:463` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:464` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:465` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:466` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:467` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:468` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:469` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:470` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:471` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:472` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:473` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:474` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:475` | -| `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:476` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:477` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:478` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:479` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:480` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:481` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:482` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:483` | -| `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:484` | -| `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:485` | -| `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:486` | -| `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:487` | +| `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:468` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:469` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:470` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:471` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:472` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:473` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:474` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:475` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:476` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:477` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:478` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:479` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:480` | +| `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:481` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:482` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:483` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:484` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:485` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:486` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:487` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:488` | +| `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:489` | +| `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:490` | +| `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:491` | +| `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:492` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index c0f895c894..8ac80e73f0 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -5,30 +5,30 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:311` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:312` | -| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:313` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:316` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:317` | +| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:318` | | `POST` | `/api/repos/rescan` | Dashboard auth/session | Re-enumerate watched repositories' open issues/PRs for the dashboard Projects cards. The scan is read-only with respect to agents/governor actions, collapses concurrent requests, and debounces repeated presses for 30 seconds (`repoRescanDebounce`) so the button cannot hammer GitHub | `pkg/dashboard/api.go`, `pkg/dashboard/api_repos_rescan.go` | | `POST` | `/api/repos/pause` | Owner | Quiet ONE repository without stopping the hive: agents stop writing to it and stop being handed work on it, while it keeps its dashboard card and ACMM eval. Body `{"repo": "...", "reason": "..."}` — the repo travels in the body because a `project.repos` entry may be an explicit cross-org `owner/name`. Records who/when/why; `changed: false` marks a no-op re-pause and leaves the original provenance intact; `persisted: false` means the pause is in force but could not be written to config. Rejects a repo outside `project.repos`. See [per-repo agent pause](../repo-pause.md) | `pkg/dashboard/api_repo_pause.go` | | `POST` | `/api/repos/resume` | Owner | Lift a repository's pause. Unlike pause, does not require the repo to be in `project.repos`, so a pause left behind by a removed repo can still be cleared | `pkg/dashboard/api_repo_pause.go` | | `GET` | `/api/repos/pauses` | Dashboard auth/session | Every repo pause with its provenance. Read-only — the same state is already on the repository cards | `pkg/dashboard/api_repo_pause.go` | -| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:328`, `pkg/dashboard/api_repo_hold.go` | +| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. 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:332`, `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"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:334`, `pkg/dashboard/api_repo_item_decision.go` | -| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_maintainer_notes.go` | -| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:339`, `pkg/dashboard/api_maintainer_notes.go` | -| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:340`, `pkg/dashboard/api_maintainer_notes.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 (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. 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:337`, `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"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:339`, `pkg/dashboard/api_repo_item_decision.go` | +| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:344`, `pkg/dashboard/api_maintainer_notes.go` | +| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_maintainer_notes.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085), and never decides a PR whose CI is running or whose review is incomplete on the current head — it answers `no-effect` (rule `mid-flight`, nothing written; fails closed, "review state not yet loaded", when the PR's review state cannot be read from the tracker; per PR in the `prs` fan-out, where the PR is skipped and counted as such), and the policy itself never releases (`default-release`, `small-low-risk`) a head whose checks are pending (rule `ci-pending`). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:344` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:345` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:556`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:348`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:349` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:350` | +| `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:561`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sha-waiver` | Owner or repo write/maintain/admin | Waive or restore the SHA-hold requirement on an issue from the activity monitor's row menu. Body `{"waived": true\|false}`. Waiving adds the persistent `sha-waived` label (created if missing), removes `needs-sha` at once and posts one App-authored comment with a `` marker; restoring removes `sha-waived`. A repeat is a no-op; pull requests are 404. Returns `{ok, repo, number, waived, added, removed, minStatusSeq, result}`. Audited as `repo_item_sha_waiver`. | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:335`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | -| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:347`, `pkg/dashboard/api_acmm_eval.go` | -| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:348` | -| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:349` | -| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:351`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:340`, `pkg/dashboard/api_repo_item_sentinel_confirm.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:352`, `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:353` | +| `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:354` | +| `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:356`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 880af5c538..b46cd31db8 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:48` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1878` | -| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:84` | -| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:85` | -| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:86` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1879` | +| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:89` | +| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:90` | +| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:91` | diff --git a/src/docs/ask-ai-help.md b/src/docs/ask-ai-help.md new file mode 100644 index 0000000000..6b88f0790d --- /dev/null +++ b/src/docs/ask-ai-help.md @@ -0,0 +1,98 @@ +# Ask AI help + +Ask AI help is an optional **Ask** panel that answers questions about using the +hub and hive dashboards ("where do I pause an agent?") from the Hive docs, with +the sources it used and an "AI generated, may be wrong" label. It is off by +default everywhere and inert until configured. The design, threat model and +isolation argument are in +[Dashboard Ask AI help](design/dashboard-ask-ai-help.md) (#19177). + +The browser only ever talks to its own dashboard. The dashboard's backend +calls the Kapa.ai Chat API server side: there is no third-party script on the +page and no Content-Security-Policy change, on or off. + +## What leaves, and what does not + +Per question, and only after the person has confirmed a short notice: + +- the question text (refused, not sent, when it looks like a password, token or + key); +- the label of the dashboard section the person is in, from a fixed list of + section names in `pkg/askai/sections.go` (turn it off with + `ask.send_section_label: false`); +- the Kapa.ai integration id and, for a follow-up, the vendor thread id, which + is kept on the server behind an opaque handle. + +Never sent: the person's login, email or role, page content, the URL, hive, +repo, agent or customer names, tokens or cookies. Hive keeps no question or +answer text; audit lines carry outcomes and counts only. Each person can +withdraw with **Stop sending my questions**; that cannot recall what Kapa.ai +already holds, and the notice says so. + +## Modes + +| Where | `ask.mode` | Who calls Kapa.ai | Key on this process | +|---|---|---|---| +| The hub | always `direct` | the hub | yes, from a Secret | +| A hosted hive | `hub` | the hub, through `POST /api/hub/ask/relay` | no | +| A self-hosted hive | `direct` | the hive | yes, from a Secret | + +A hosted hive in hub mode authenticates to the relay with the per-hive +heartbeat bearer it already has; no new secret is issued and the key never +leaves the hub. The hub applies a per-hive hourly quota and its own hub-wide +limits, and a hub operator can turn the relay off (`HIVE_ASK_RELAY_HIVES=none`) +or refuse single hives (`HIVE_ASK_RELAY_DISABLED_HIVES`). In this round the +relay serves hosted hives only; a self-hosted hive registered with a hub uses +direct mode with its own key, or stays off. + +## Turning it on for a hosted hive + +1. The hub operator turns Ask on at the hub ([Ask AI help on the + hub](hub-deployment.md#ask-ai-help)). +2. The hive owner opens **Settings, Features**, turns on **Ask AI help** and + sets **Ask mode** to `hub`, or sets in `hive.yaml`: + + ```yaml + ask: + enabled: true + mode: hub + ``` + + `HIVE_ASK_ENABLED` and `HIVE_ASK_MODE` override these. +3. If the hive is not hosted, or has no hub link, Settings says why Ask stays + off. + +## Configuration keys + +| Key | Env | Default | Meaning | +|---|---|---|---| +| `ask.enabled` | `HIVE_ASK_ENABLED` | off | The owner or operator switch. It makes the panel available; each person still consents. | +| `ask.mode` | `HIVE_ASK_MODE` | `off` | `off`, `direct` or `hub`. | +| `ask.kapa.project_id` | `HIVE_ASK_KAPA_PROJECT_ID` | unset | Direct mode only. Never logged or returned by an API; redacted in the config export. | +| `ask.kapa.integration_id` | `HIVE_ASK_KAPA_INTEGRATION_ID` | unset | Direct mode only. Same handling. | +| `ask.kapa.api_key_file` | `HIVE_ASK_KAPA_API_KEY_FILE` | unset | Direct mode only. A file under `/secrets` or `/data/secrets`, mounted from a Secret. | +| `ask.send_section_label` | `HIVE_ASK_SEND_SECTION_LABEL` | on | Send the closed-list section label with the question. | +| `ask.limits.person_per_minute`, `ask.limits.person_per_hour` | `HIVE_ASK_LIMIT_PERSON_PER_MINUTE`, `HIVE_ASK_LIMIT_PERSON_PER_HOUR` | 3, 20 | Per person, with one question in flight. | +| `ask.limits.global_per_minute`, `ask.limits.in_flight`, `ask.limits.daily` | `HIVE_ASK_LIMIT_GLOBAL_PER_MINUTE`, `HIVE_ASK_LIMIT_IN_FLIGHT`, `HIVE_ASK_LIMIT_DAILY` | 4, 2, 500 | Process-wide. The per-minute cap is a fifth of Kapa.ai's 20 per minute per-team limit and is never allowed above half of it. | +| `ask.limits.hive_per_hour` | `HIVE_ASK_LIMIT_HIVE_PER_HOUR` | 60 | Read by the hub: relayed questions per hive per hour. | + +If `ask.enabled` is on but a value is missing or the key file is unreadable, +Ask stays off, Settings shows the reason, and one warning line is logged that +names no value. + +## Failure and fallback + +Every state keeps a plain docs link: not consented, Kapa.ai or the hub +unreachable or busy (`429` backs callers off for its `Retry-After`), the circuit +breaker open after repeated failures, a refused question, or an answer with no +source on the allowlist (`docs.hivecommons.dev` and the docs path of +`hivecommons/hive` on GitHub), which is shown as "No cited answer found in the +docs" rather than as an answer. A hive whose relay is refused never falls back +to a key it does not hold. + +## API + +Hive dashboard: `GET /api/ask/status`, `PUT` and `DELETE /api/ask/consent`, +`POST /api/ask` (see `dashboard/openapi.json`); every route answers `404` while +Ask is off. Hub: the same routes plus `GET /api/ask/stats` and the relay, in +the [hub API reference](api-reference/hub-saas.md). diff --git a/src/docs/documentation-map.md b/src/docs/documentation-map.md index fb797fd5ab..f920acb49d 100644 --- a/src/docs/documentation-map.md +++ b/src/docs/documentation-map.md @@ -17,6 +17,7 @@ Documentation for the current Hive line (branch `v5`; the code and docs live und ### First installation - [Hosted Hive Hub onboarding](hosted-hub.md) — signing in at `https://hive.hivecommons.dev`, requesting a hosted hive, installing the GitHub App, configuring model gateways and Copilot login, reading `/fleet`, and fixing common setup problems. +- [Ask AI help](ask-ai-help.md) — the optional Ask panel on the hub and hive dashboards: what leaves, consent, hub relay and direct modes, configuration keys and the docs-link fallback (#19177). - [Hub Fleet activity page](hub-fleet-activity.md) — the read-only `/activity` board of open issues and PRs across the hives you can see: per-viewer scoping, hive chips, group-by-hive freshness headers, always-visible truncation and stale-source disclosures, 15-second ETag polling, and display mode (`?kiosk=1`, `?display=1`, `am.*` views and `hub-activity` playlists). - [Docker Compose quick start](quickstart-docker-compose.md) — default standalone installation, prerequisites, and verification. - [Podman quick start](quickstart-podman.md) — standalone Quadlet/systemd installation, with rootless/rootful prerequisites. diff --git a/src/docs/hub-deployment.md b/src/docs/hub-deployment.md index 0698e6606f..ed2b146f42 100644 --- a/src/docs/hub-deployment.md +++ b/src/docs/hub-deployment.md @@ -167,6 +167,16 @@ and is deleted with the user. Answers without an allowlisted source (`docs.hivecommons.dev` or the GitHub docs path under `hivecommons/hive`) are shown as "no cited answer" with a docs link. +Hosted hives ask through the hub: with Ask on, the hub also serves +`POST /api/hub/ask/relay`, authenticated with each hive's per-hive heartbeat +bearer, so the key stays on the hub. It serves hosted hives only in this round +(`HIVE_ASK_RELAY_HIVES`, default `hosted`; `none` turns the relay off; +`registered` is accepted and treated as `hosted` until self-hosted hives are +approved), refuses hives listed in `HIVE_ASK_RELAY_DISABLED_HIVES`, and charges +each hive at most 60 relayed questions an hour (`HIVE_ASK_LIMIT_HIVE_PER_HOUR`) +inside the hub-wide limits. See [Ask AI help](ask-ai-help.md) for the hive +side. + Limits (env overrides in [Environment variables](env-vars.md)): per person 3 a minute, 20 an hour and one in flight; hub-wide 4 a minute (a fifth of the vendor's 20 a minute per-team limit, and never more than half of it), 2 in diff --git a/src/docs/settings.md b/src/docs/settings.md index 3d6aa43d61..f3c0c1e4f9 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -84,6 +84,7 @@ Optional capabilities, each off or inert until you turn it on. Where a feature h - Trajectory review: [Trajectory-Review Lane](trajectory-review.md#configuration). - Linear agent: [Linear agent integration](linear-agent.md). - Upstream watch: [Upstream watch](upstream-watch.md#configuration). +- Ask AI help: [Ask AI help](ask-ai-help.md). The other features on this tab (OpenTelemetry export, external execution, auto-plan, issue claims, PR follow-up, long-running runs, provider rotation, merge recommendations, convergence rollout, stall replan, and question auto-close) are explained by their **?** tooltips, and their configuration keys are listed in the [Hive operator reference](operator-reference.md#configuration-blocks). diff --git a/src/docs/telemetry.md b/src/docs/telemetry.md index 50a66a459b..b20ae14c04 100644 --- a/src/docs/telemetry.md +++ b/src/docs/telemetry.md @@ -12,7 +12,7 @@ Hive sends a small number of operational signals outside the running hive only t | Build-containment lookup | A commit SHA (the hive's running commit and the commit being asked about) or a PR number, sent as part of a GitHub REST `compare` or `pulls` request. Only when an operator runs a lookup (`GET /api/saas/build-contains` on the hub, `GET /api/version/contains` on a hive). No hive identifier, org, repo name or user is in the request. | `api.github.com`, the public `hivecommons/hive` repository, using the hub's read-only GitHub identity or the hive's own configured GitHub client. The answer is shown to the caller only. | On demand only; no background polling. A hive with no GitHub client answers `unknown` and sends nothing. | None stored; compare answers are cached in memory, for the life of the process. | Do not run the lookup; there is no setting because nothing is sent otherwise. | `src/pkg/buildcontains/buildcontains.go`; `src/pkg/hub/build_contains.go`; `src/pkg/dashboard/api_version_contains.go`. | | NPS prompt | Score 1-4, optional free text, hive ID, and dashboard version. The signed-in username is used only locally for rate limiting and is not sent. | Hub `POST /api/nps/ingest`, or an explicitly configured NPS relay for standalone hives; only hub admins can read stored responses. | Hosted spokes default on; self-hosted/federated/standalone default off. Standalone relay requires explicit `hub.nps_enabled`/`HIVE_NPS_ENABLED` and `hub.nps_relay_url`/`HIVE_NPS_RELAY_URL`. | Hub store keeps at most 1,000 responses per hive and 10,000 total, oldest dropped first. | `hub.nps_enabled: false` or `HIVE_NPS_ENABLED=false`; leave relay URL unset. | `src/docs/nps.md`; `src/docs/env-vars.md`; `src/pkg/dashboard/nps.go`; `src/pkg/hub/nps.go`. | | Hosted hub web analytics | GA4 page/event data from hub-hosted pages, including custom hub events such as hive creation/deletion. Existing event code includes hive IDs and creation inputs such as org, primary repo, ACMM level, and cluster ID. | Google Analytics via `www.googletagmanager.com`, property `G-4707R797K3`. | Loaded by hosted hub static HTML pages. This is website analytics, not spoke software telemetry, but it still needs privacy review because custom events may include project identifiers. | Google Analytics retention is controlled in the GA property, not in this repository. | Browser tracking protections or removing the hosted hub GA script; there is no repository config flag. | `src/pkg/hub/assets/dashboard.html`; `src/pkg/hub/saas_pages.go`; `src/pkg/hub/static/*.html` pages such as `reading.html` and `cncf-reference-architecture.html`. | -| Ask AI help (optional) | The question a signed-in person typed, after a credential-shape check that refuses rather than sends; the label of the dashboard section they are in, from a closed list of our own ids; the Kapa.ai integration id; and, for a follow-up, the vendor thread id. No login, email, page content, URL, hive, repo or agent name. | Kapa.ai Chat API (`api.kapa.ai`), called server side by the hub; the project's Kapa administrators can read questions in Kapa analytics. | Off by default (`HIVE_ASK_ENABLED`); inert until a key file, project id and integration id are configured; each person confirms a disclosure before their first question and can withdraw. | Kapa keeps conversations for the duration of the service; Hive stores no question or answer text, only the per-person consent record. | Leave `HIVE_ASK_ENABLED` unset, or withdraw consent per person. | `src/pkg/askai/service.go`; `src/pkg/askai/kapa.go`; `src/pkg/hub/ask.go`; [design](design/dashboard-ask-ai-help.md). | +| Ask AI help (optional) | The question a signed-in person typed, after a credential-shape check that refuses rather than sends; the label of the dashboard section they are in, from a closed list of our own ids; the Kapa.ai integration id; and, for a follow-up, the vendor thread id. No login, email, page content, URL, hive, repo or agent name. | Kapa.ai Chat API (`api.kapa.ai`), called server side by the hub, or by a self-hosted hive in `ask.mode: direct`; a hosted hive in `ask.mode: hub` sends the same fields (without the integration id) to its hub relay over the per-hive heartbeat bearer. The project's Kapa administrators can read questions in Kapa analytics. | Off by default (`ask.enabled` / `HIVE_ASK_ENABLED`); inert until configured; each person confirms a disclosure before their first question and can withdraw. | Kapa keeps conversations for the duration of the service; Hive stores no question or answer text, only the per-person consent record. | Leave `HIVE_ASK_ENABLED` unset, or withdraw consent per person. | `src/pkg/askai/service.go`; `src/pkg/askai/kapa.go`; `src/pkg/askai/relay.go`; `src/pkg/hub/ask.go`; `src/pkg/dashboard/api_ask.go`; [guide](ask-ai-help.md), [design](design/dashboard-ask-ai-help.md). | | Crash/error reporting | No Sentry/PostHog/Segment/Plausible crash reporter was found in `src` during the onboarding audit. Errors are logged locally; selected log-safe health/error strings can appear in hub heartbeats as described above. | Local logs and, for selected operational state, the configured hub. | No third-party crash reporting by default. | Local log/PVC retention is deployment-specific. | N/A for third-party crash reporting; disable hub link for heartbeat-carried operational errors. | Audit search: `telemetry|analytics|metrics push|phone.?home|posthog|segment|plausible|gtag|googletagmanager|sentry` over Go/HTML/JS/Markdown. | ## Linux Foundation telemetry-policy status diff --git a/src/pkg/askai/consent.go b/src/pkg/askai/consent.go index ff4e1b4898..3402978dd8 100644 --- a/src/pkg/askai/consent.go +++ b/src/pkg/askai/consent.go @@ -1,11 +1,14 @@ package askai import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "os" "path/filepath" "regexp" + "strings" "sync" "time" ) @@ -30,6 +33,27 @@ const ( // consentStemPattern bounds a person key to a single safe path segment. var consentStemPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$`) +// personKeyHashPrefix marks a stem derived by hashing an identity that is not +// itself a safe file name (an email, say). +const ( + personKeyHashPrefix = "h-" + personKeyHashHexLen = 40 +) + +// PersonKey maps a dashboard identity to a consent stem: the identity itself +// when it is already a safe stem, else a hash of it. "" stays "". +func PersonKey(identity string) string { + identity = strings.TrimSpace(identity) + if identity == "" { + return "" + } + if consentStemPattern.MatchString(identity) { + return identity + } + sum := sha256.Sum256([]byte(identity)) + return personKeyHashPrefix + hex.EncodeToString(sum[:])[:personKeyHashHexLen] +} + // ErrInvalidPerson is returned for a person key that is not a safe stem. var ErrInvalidPerson = errors.New("ask: invalid person key") diff --git a/src/pkg/askai/limits.go b/src/pkg/askai/limits.go index 9f2c384c94..4489b5300d 100644 --- a/src/pkg/askai/limits.go +++ b/src/pkg/askai/limits.go @@ -77,7 +77,9 @@ func newLimiter(l Limits) *limiter { } // reserve takes one slot for person (and hive when non-empty). release must -// be called exactly once after an ok reservation. +// be called exactly once after an ok reservation. An empty person is a +// relayed request: the hive it came from has already applied its own +// per-person limits, so only the hive and process-wide caps apply here. func (l *limiter) reserve(now time.Time, person, hive string) limitDecision { l.mu.Lock() defer l.mu.Unlock() @@ -101,12 +103,13 @@ func (l *limiter) reserve(now time.Time, person, hive string) limitDecision { } hw.roll(now, hourWindow) } + perPerson := person != "" switch { - case p.inFlight >= personInFlight: + case perPerson && p.inFlight >= personInFlight: return limitDecision{retryAfter: time.Second} - case p.minute.count >= l.limits.PersonPerMinute: + case perPerson && p.minute.count >= l.limits.PersonPerMinute: return limitDecision{retryAfter: p.minute.retryAfter(now, minuteWindow)} - case p.hour.count >= l.limits.PersonPerHour: + case perPerson && p.hour.count >= l.limits.PersonPerHour: return limitDecision{retryAfter: p.hour.retryAfter(now, hourWindow)} case hw != nil && hw.count >= l.limits.HivePerHour: return limitDecision{retryAfter: hw.retryAfter(now, hourWindow)} @@ -117,10 +120,12 @@ func (l *limiter) reserve(now time.Time, person, hive string) limitDecision { case l.inFlight >= l.limits.InFlight: return limitDecision{retryAfter: time.Second} } - p.minute.count++ - p.hour.count++ - p.inFlight++ - l.persons[person] = p + if perPerson { + p.minute.count++ + p.hour.count++ + p.inFlight++ + l.persons[person] = p + } if hw != nil { hw.count++ l.hives[hive] = hw diff --git a/src/pkg/askai/relay.go b/src/pkg/askai/relay.go new file mode 100644 index 0000000000..4cb9d34dd6 --- /dev/null +++ b/src/pkg/askai/relay.go @@ -0,0 +1,213 @@ +package askai + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "strings" + "time" + "unicode/utf8" +) + +// Hub relay (phase 4, #19183). A hosted hive holds no Kapa key: it takes the +// person's consent, refuses credential-shaped input and applies its own +// per-person limits, then forwards only {question, section, conversation} to +// the hub, authenticated with the per-hive heartbeat bearer it already has. +// The hub applies the hive's quota and the process-wide caps, calls the vendor +// and returns a filtered Result. The hive filters it again before showing it. +const ( + // RelayPath is the hub route a hive posts to. + RelayPath = "/api/hub/ask/relay" + // RelayHiveIDHeader names the hive the bearer is bound to. + RelayHiveIDHeader = "X-Hive-ID" + // maxRelayResponseBytes caps what a hive reads back from the hub. + maxRelayResponseBytes = 64 << 10 +) + +// Asker is what a dashboard calls: a Service in direct mode, a RelayAsker in +// hub mode. +type Asker interface { + Ask(ctx context.Context, req Request) Result +} + +// knownOutcomes is the closed set a relayed Result may carry. +var knownOutcomes = map[Outcome]bool{ + OutcomeOK: true, OutcomeNoCitedAnswer: true, OutcomeRefusedSecretShape: true, OutcomeRateLimited: true, + OutcomeBreakerOpen: true, OutcomeUpstreamError: true, OutcomeNotConsented: true, OutcomeInvalidQuestion: true, + OutcomeRelayDisabled: true, +} + +// RelayOptions configure a RelayAsker. +type RelayOptions struct { + // HubURL is the hub base URL; HiveID the authenticated hive. + HubURL string + HiveID string + // Bearer returns the per-hive heartbeat bearer at call time. + Bearer func() string + Consent ConsentChecker + // Limits are this hive's own limits (HivePerHour is unused here). + Limits Limits + HTTP *http.Client + Logger *slog.Logger + // DocsURL is the fallback docs link; "" means DocsHomeURL. + DocsURL string + // Timeout bounds one hub call; 0 means DefaultUpstreamTimeout. + Timeout time.Duration + Now func() time.Time +} + +// RelayAsker answers through the hub relay. It never holds a vendor key and +// never falls back to one. +type RelayAsker struct { + url string + hiveID string + bearer func() string + consent ConsentChecker + limiter *limiter + convs *conversations + http *http.Client + logger *slog.Logger + docsURL string + timeout time.Duration + now func() time.Time +} + +// NewRelayAsker builds a relay client. It needs a hub URL, a hive id and a +// bearer source. +func NewRelayAsker(o RelayOptions) (*RelayAsker, error) { + base := strings.TrimRight(strings.TrimSpace(o.HubURL), "/") + if base == "" || strings.TrimSpace(o.HiveID) == "" || o.Bearer == nil { + return nil, errors.New("ask: hub relay is not configured") + } + if o.Timeout <= 0 { + o.Timeout = DefaultUpstreamTimeout + } + if o.HTTP == nil { + o.HTTP = &http.Client{Timeout: o.Timeout} + } + if o.Logger == nil { + o.Logger = slog.Default() + } + if o.DocsURL == "" { + o.DocsURL = DocsHomeURL + } + if o.Now == nil { + o.Now = time.Now + } + return &RelayAsker{ + url: base + RelayPath, hiveID: strings.TrimSpace(o.HiveID), bearer: o.Bearer, consent: o.Consent, + limiter: newLimiter(o.Limits), convs: newConversations(0), http: o.HTTP, logger: o.Logger, + docsURL: o.DocsURL, timeout: o.Timeout, now: o.Now, + }, nil +} + +func (a *RelayAsker) result(o Outcome, msg string) Result { + return Result{Outcome: o, Message: msg, AIGenerated: true, DocsURL: a.docsURL} +} + +// Ask validates locally, so nothing a person must not send ever reaches the +// hub, then forwards. +func (a *RelayAsker) Ask(ctx context.Context, req Request) Result { + start := a.now() + questionLen := utf8.RuneCountInString(strings.TrimSpace(req.Question)) + r := a.ask(ctx, req, start) + a.logger.Info("audit: ask request", "outcome", string(r.Outcome), "person", req.Person, "relay", true, + "question_len", questionLen, "sources_kept", len(r.Sources), "latency_ms", a.now().Sub(start).Milliseconds()) + return r +} + +func (a *RelayAsker) ask(ctx context.Context, req Request, start time.Time) Result { + question, outcome := ValidateQuestion(req.Question) + if outcome == OutcomeInvalidQuestion { + return a.result(OutcomeInvalidQuestion, msgInvalid) + } + if a.consent == nil || !a.consent.Has(req.Person) { + return a.result(OutcomeNotConsented, msgNotConsented) + } + if outcome == OutcomeRefusedSecretShape { + return a.result(OutcomeRefusedSecretShape, msgRefused) + } + decision := a.limiter.reserve(start, req.Person, "") + if !decision.ok { + r := a.result(OutcomeRateLimited, busyMessage(decision.retryAfter)) + r.RetryAfterSeconds = seconds(decision.retryAfter) + return r + } + defer a.limiter.release(req.Person) + + hubHandle := a.convs.thread(req.Conversation, req.Person, "", start) + section := "" + if _, ok := SectionLabel(req.Section); ok { + section = req.Section + } + body, err := json.Marshal(Request{Question: question, Section: section, Conversation: hubHandle}) + if err != nil { + return a.result(OutcomeUpstreamError, msgUnavailable) + } + callCtx, cancel := context.WithTimeout(ctx, a.timeout) + defer cancel() + httpReq, err := http.NewRequestWithContext(callCtx, http.MethodPost, a.url, bytes.NewReader(body)) + if err != nil { + return a.result(OutcomeUpstreamError, msgUnavailable) + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Accept", "application/json") + httpReq.Header.Set("Authorization", "Bearer "+a.bearer()) + httpReq.Header.Set(RelayHiveIDHeader, a.hiveID) + resp, err := a.http.Do(httpReq) + if err != nil { + return a.result(OutcomeUpstreamError, msgUnavailable) + } + defer resp.Body.Close() + switch { + case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden: + // Relay off on the hub, or this hive not served: never retry with a + // key the hive does not hold. + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxRelayResponseBytes)) + return a.result(OutcomeRelayDisabled, msgRelayDisabled) + case resp.StatusCode != http.StatusOK: + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxRelayResponseBytes)) + return a.result(OutcomeUpstreamError, msgUnavailable) + } + var got Result + if err := json.NewDecoder(io.LimitReader(resp.Body, maxRelayResponseBytes)).Decode(&got); err != nil || !knownOutcomes[got.Outcome] { + return a.result(OutcomeUpstreamError, msgUnavailable) + } + return a.reFilter(got, req, start) +} + +// reFilter applies the allowlist and text rules again on the hive, keeps the +// hub's conversation handle server side behind a local one, and never lets the +// hub decide the docs link or the AI label. +func (a *RelayAsker) reFilter(got Result, req Request, now time.Time) Result { + r := a.result(got.Outcome, cleanText(got.Message, MaxAnswerRunes, "")) + if r.Message == "" { + r.Message = msgUnavailable + } + r.RetryAfterSeconds = got.RetryAfterSeconds + if got.Outcome != OutcomeOK { + return r + } + in := make([]UpstreamSource, 0, len(got.Sources)) + for _, s := range got.Sources { + in = append(in, UpstreamSource{URL: s.URL, Title: s.Title}) + } + r.Message = "" + r.Sources = FilterSources(in) + r.Answer = SanitizeAnswer(got.Answer) + r.Uncertain = got.Uncertain + if handle := strings.TrimSpace(got.Conversation); handle != "" && len(handle) <= maxHandleLen { + r.Conversation = a.convs.remember(req.Conversation, req.Person, "", handle, now) + } + if len(r.Sources) == 0 || r.Answer == "" { + r.Outcome, r.Answer, r.Sources, r.Message, r.Uncertain = OutcomeNoCitedAnswer, "", nil, msgNoCitedAnswer, false + } + return r +} + +// maxHandleLen bounds a hub conversation handle the hive will keep. +const maxHandleLen = 2 * conversationHandleBytes diff --git a/src/pkg/askai/relay_test.go b/src/pkg/askai/relay_test.go new file mode 100644 index 0000000000..eee80030fc --- /dev/null +++ b/src/pkg/askai/relay_test.go @@ -0,0 +1,240 @@ +package askai + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// fakeHub is a hub relay endpoint that records what a hive sends. +type fakeHub struct { + mu sync.Mutex + bodies []map[string]any + headers []http.Header + status int + reply string + srv *httptest.Server +} + +func newFakeHub(t *testing.T) *fakeHub { + t.Helper() + h := &fakeHub{status: http.StatusOK} + h.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body map[string]any + _ = json.Unmarshal(raw, &body) + h.mu.Lock() + h.bodies = append(h.bodies, body) + h.headers = append(h.headers, r.Header.Clone()) + status, reply := h.status, h.reply + h.mu.Unlock() + if r.URL.Path != RelayPath { + http.NotFound(w, r) + return + } + w.WriteHeader(status) + _, _ = io.WriteString(w, reply) + })) + t.Cleanup(h.srv.Close) + return h +} + +func (h *fakeHub) set(status int, reply string) { + h.mu.Lock() + defer h.mu.Unlock() + h.status, h.reply = status, reply +} + +func (h *fakeHub) calls() int { + h.mu.Lock() + defer h.mu.Unlock() + return len(h.bodies) +} + +func (h *fakeHub) last() (map[string]any, http.Header) { + h.mu.Lock() + defer h.mu.Unlock() + return h.bodies[len(h.bodies)-1], h.headers[len(h.headers)-1] +} + +const hubOKReply = `{"outcome":"ok","answer":"Open Settings, then Features. See [this](https://evil.example/x).", + "sources":[{"title":"Settings","url":"https://docs.hivecommons.dev/settings/"},{"title":"Evil","url":"https://evil.example/"}], + "conversation":"0123456789abcdef0123456789abcdef","ai_generated":false,"docs_url":"https://evil.example/docs"}` + +type consentSet map[string]bool + +func (c consentSet) Has(p string) bool { return c[p] } + +func newTestRelay(t *testing.T, hub *fakeHub, consent ConsentChecker) *RelayAsker { + t.Helper() + a, err := NewRelayAsker(RelayOptions{ + HubURL: hub.srv.URL + "/", HiveID: "hosted-hive-1", Bearer: func() string { return "per-hive-bearer" }, + Consent: consent, Limits: generous, HTTP: hub.srv.Client(), + }) + if err != nil { + t.Fatal(err) + } + return a +} + +// TestRelaySendsOnlyTheQuestionAndRefiltersTheAnswer: the hive forwards +// question, section and the hub's own handle, authenticated as the hive, and +// never trusts the hub's links, label or docs URL. +func TestRelaySendsOnlyTheQuestionAndRefiltersTheAnswer(t *testing.T) { + hub := newFakeHub(t) + hub.set(http.StatusOK, hubOKReply) + a := newTestRelay(t, hub, consentSet{"alice-login": true, "bob": true}) + + r := a.Ask(context.Background(), Request{Person: "alice-login", HiveID: "ignored", Question: " Where is pause? ", Section: "agents-section"}) + if r.Outcome != OutcomeOK || len(r.Sources) != 1 || r.Sources[0].URL != "https://docs.hivecommons.dev/settings/" || + strings.Contains(r.Answer, "evil.example") || !r.AIGenerated || r.DocsURL != DocsHomeURL { + t.Fatalf("result %+v", r) + } + body, hdr := hub.last() + if len(body) != 2 || body["question"] != "Where is pause?" || body["section"] != "agents-section" { + t.Fatalf("relay body must be the question and section only, got %v", body) + } + if hdr.Get("Authorization") != "Bearer per-hive-bearer" || hdr.Get(RelayHiveIDHeader) != "hosted-hive-1" { + t.Fatalf("relay headers %v", hdr) + } + if r.Conversation == "" || r.Conversation == "0123456789abcdef0123456789abcdef" { + t.Fatalf("the hub's handle must stay on the hive behind a local one, got %q", r.Conversation) + } + + // Follow-up: alice's local handle maps to the hub handle; bob's use of it + // sends no conversation at all. + a.Ask(context.Background(), Request{Person: "alice-login", Question: "and then?", Conversation: r.Conversation}) + if body, _ := hub.last(); body["conversation"] != "0123456789abcdef0123456789abcdef" { + t.Fatalf("follow-up body %v", body) + } + a.Ask(context.Background(), Request{Person: "bob", Question: "and then?", Conversation: r.Conversation, Section: "acme/private-repo"}) + if body, _ := hub.last(); body["conversation"] != nil || body["section"] != nil { + t.Fatalf("bob used alice's handle or an unknown section was sent: %v", body) + } +} + +func TestRelayNothingLeavesWithoutConsentOrWithACredential(t *testing.T) { + hub := newFakeHub(t) + hub.set(http.StatusOK, hubOKReply) + a := newTestRelay(t, hub, consentSet{"alice": true}) + if r := a.Ask(context.Background(), Request{Person: "mallory", Question: "q?"}); r.Outcome != OutcomeNotConsented { + t.Fatalf("no consent: %+v", r) + } + if r := a.Ask(context.Background(), Request{Person: "alice", Question: "ghp_abcdefghijklmnopqrstuvwxyz0123 fails"}); r.Outcome != OutcomeRefusedSecretShape { + t.Fatalf("credential: %+v", r) + } + if r := a.Ask(context.Background(), Request{Person: "alice", Question: strings.Repeat("x", MaxQuestionRunes+1)}); r.Outcome != OutcomeInvalidQuestion { + t.Fatalf("too long: %+v", r) + } + if hub.calls() != 0 { + t.Fatalf("the hub was called %d times", hub.calls()) + } + nilConsent := newTestRelay(t, hub, nil) + if r := nilConsent.Ask(context.Background(), Request{Person: "alice", Question: "q?"}); r.Outcome != OutcomeNotConsented || hub.calls() != 0 { + t.Fatalf("nil checker: %+v", r) + } +} + +func TestRelayFailuresFallBackWithoutAKey(t *testing.T) { + hub := newFakeHub(t) + a := newTestRelay(t, hub, consentSet{"alice": true}) + ask := func() Outcome { return a.Ask(context.Background(), Request{Person: "alice", Question: "q?"}).Outcome } + for status, want := range map[int]Outcome{ + http.StatusNotFound: OutcomeRelayDisabled, + http.StatusUnauthorized: OutcomeRelayDisabled, + http.StatusForbidden: OutcomeRelayDisabled, + http.StatusBadGateway: OutcomeUpstreamError, + http.StatusInternalServerError: OutcomeUpstreamError, + } { + hub.set(status, `{}`) + if got := ask(); got != want { + t.Errorf("hub %d: %s, want %s", status, got, want) + } + } + hub.set(http.StatusOK, `{"outcome":"something_new"}`) + if got := ask(); got != OutcomeUpstreamError { + t.Fatalf("unknown outcome: %s", got) + } + hub.set(http.StatusOK, `{"outcome":"ok","answer":"text","sources":[{"url":"https://evil.example/"}]}`) + if got := ask(); got != OutcomeNoCitedAnswer { + t.Fatalf("uncited relayed answer: %s", got) + } + hub.set(http.StatusOK, `{"outcome":"rate_limited","message":"Busy, try again in 9 seconds.","retry_after_seconds":9}`) + if r := a.Ask(context.Background(), Request{Person: "alice", Question: "q?"}); r.Outcome != OutcomeRateLimited || r.RetryAfterSeconds != 9 { + t.Fatalf("relayed busy: %+v", r) + } + if _, err := NewRelayAsker(RelayOptions{HiveID: "h", Bearer: func() string { return "b" }}); err == nil { + t.Fatal("a relay without a hub URL must be refused") + } +} + +func TestRelayAppliesThisHivesPersonLimits(t *testing.T) { + hub := newFakeHub(t) + hub.set(http.StatusOK, hubOKReply) + a, err := NewRelayAsker(RelayOptions{ + HubURL: hub.srv.URL, HiveID: "h", Bearer: func() string { return "b" }, Consent: consentSet{"alice": true}, + Limits: Limits{PersonPerMinute: 1, PersonPerHour: 10, GlobalPerMinute: 10, InFlight: 10, Daily: 10}, + Now: func() time.Time { return time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) }, + }) + if err != nil { + t.Fatal(err) + } + a.Ask(context.Background(), Request{Person: "alice", Question: "q?"}) + if r := a.Ask(context.Background(), Request{Person: "alice", Question: "q?"}); r.Outcome != OutcomeRateLimited || hub.calls() != 1 { + t.Fatalf("per-person limit on the hive: %+v, calls %d", r, hub.calls()) + } +} + +// TestServiceRelayChargesTheHiveNotAPerson is the hub side: no consent check +// (the hive took it), the hive's hourly cap applies, and a conversation handle +// is bound to the hive that created it. +func TestServiceRelayChargesTheHiveNotAPerson(t *testing.T) { + up := &fakeUpstream{answer: citedAnswer} + limits := Limits{PersonPerMinute: 1, PersonPerHour: 1, HivePerHour: 2, GlobalPerMinute: 10, InFlight: 10, Daily: 10} + svc := newTestService(t, up, nil, limits, nil, nil) + first := svc.Relay(context.Background(), Request{HiveID: "hive-a", Question: "q?"}) + if first.Outcome != OutcomeOK || first.Conversation == "" { + t.Fatalf("relay without a consent checker: %+v", first) + } + // Per-person caps (1) do not bind relayed traffic; the hive cap (2) does. + if r := svc.Relay(context.Background(), Request{HiveID: "hive-a", Question: "q?", Conversation: first.Conversation}); r.Outcome != OutcomeOK { + t.Fatalf("second relay: %+v", r) + } + if r := svc.Relay(context.Background(), Request{HiveID: "hive-a", Question: "q?"}); r.Outcome != OutcomeRateLimited { + t.Fatalf("hive cap: %+v", r) + } + if r := svc.Relay(context.Background(), Request{HiveID: "hive-b", Question: "q?", Conversation: first.Conversation}); r.Outcome != OutcomeOK { + t.Fatalf("hive B: %+v", r) + } + want := []string{"", citedAnswer.ThreadID, ""} + for i, got := range up.threads { + if got != want[i] { + t.Fatalf("call %d thread %q, want %q (hive B must not continue hive A's thread)", i, got, want[i]) + } + } + if r := svc.Relay(context.Background(), Request{Question: "q?"}); r.Outcome != OutcomeRelayDisabled { + t.Fatalf("no hive: %+v", r) + } + if svc.RelayDisabledResult().Outcome != OutcomeRelayDisabled { + t.Fatal("disabled result") + } +} + +func TestPersonKey(t *testing.T) { + if PersonKey("alice") != "alice" || PersonKey(" ") != "" { + t.Fatal("a safe login is its own key") + } + k := PersonKey("alice@example.com") + if !strings.HasPrefix(k, personKeyHashPrefix) || strings.Contains(k, "@") || k != PersonKey("alice@example.com") || !consentStemPattern.MatchString(k) { + t.Fatalf("hashed key %q", k) + } + if PersonKey("../etc/passwd") == "../etc/passwd" { + t.Fatal("a path must never be a key") + } +} diff --git a/src/pkg/askai/service.go b/src/pkg/askai/service.go index c29c85f77d..5fb5ae77ea 100644 --- a/src/pkg/askai/service.go +++ b/src/pkg/askai/service.go @@ -160,6 +160,24 @@ func (s *Service) Ask(ctx context.Context, req Request) Result { return s.ask(ctx, req, true) } +// Relay answers a question relayed by a hive over the hub (phase 4, #19183). +// The hive took the person's consent and applied its own per-person limits +// before sending, so neither is checked again here; the hive's hourly cap and +// the process-wide caps are. req.HiveID must be the authenticated hive; the +// conversation handle is bound to it, so another hive cannot continue it. +func (s *Service) Relay(ctx context.Context, req Request) Result { + req.Person = "" + if req.HiveID == "" { + return s.result(OutcomeRelayDisabled, msgRelayDisabled) + } + return s.ask(ctx, req, false) +} + +// RelayDisabledResult is the answer for a hive the relay does not serve. +func (s *Service) RelayDisabledResult() Result { + return s.result(OutcomeRelayDisabled, msgRelayDisabled) +} + // ValidateQuestion trims the question and reports whether it is usable and // free of credential shapes. It is exported so a relaying hive can refuse // before anything leaves it. @@ -277,8 +295,11 @@ func (s *Service) finish(req Request, r Result, questionLen int, start time.Time } s.mu.Unlock() if !skip { - attrs := []any{"person", req.Person, "outcome", string(r.Outcome), "question_len", questionLen, + attrs := []any{"outcome", string(r.Outcome), "question_len", questionLen, "sources_kept", len(r.Sources), "latency_ms", s.now().Sub(start).Milliseconds()} + if req.Person != "" { + attrs = append(attrs, "person", req.Person) + } if req.HiveID != "" { attrs = append(attrs, "hive", req.HiveID) } diff --git a/src/pkg/config/ask.go b/src/pkg/config/ask.go index e643811bd2..0eee2fc597 100644 --- a/src/pkg/config/ask.go +++ b/src/pkg/config/ask.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "os" "regexp" "strconv" "strings" @@ -115,14 +116,17 @@ type AskConfig struct { SendSectionLabel *bool `yaml:"send_section_label,omitempty" json:"send_section_label,omitempty"` // Limits overrides the named defaults. Zero keeps the default. Limits AskLimitsConfig `yaml:"limits,omitempty" json:"limits,omitempty"` - // Relay is read by the hub only. - Relay AskRelayConfig `yaml:"relay,omitempty" json:"relay,omitempty"` + // Relay is read by the hub only, from env (HIVE_ASK_RELAY_*); the hub has + // no hive.yaml, so it is not a hive.yaml key. + Relay AskRelayConfig `yaml:"-" json:"-"` } // AskKapaConfig is ask.kapa. type AskKapaConfig struct { - ProjectID string `yaml:"project_id,omitempty" json:"project_id,omitempty"` - IntegrationID string `yaml:"integration_id,omitempty" json:"integration_id,omitempty"` + // ProjectID and IntegrationID are never serialised to JSON, so no API + // that encodes the config can return them. + ProjectID string `yaml:"project_id,omitempty" json:"-"` + IntegrationID string `yaml:"integration_id,omitempty" json:"-"` // APIKeyFile is a path under the allowed secret dirs, mounted from a // Secret. There is no inline key. APIKeyFile string `yaml:"api_key_file,omitempty" json:"api_key_file,omitempty"` @@ -178,6 +182,14 @@ type AskSettings struct { Problem string } +// AskSettings resolves the hive's ask block with the process env. +func (c *Config) AskSettings() AskSettings { + if c == nil { + return ResolveAsk(AskConfig{}, os.Getenv, false) + } + return ResolveAsk(c.Ask, os.Getenv, false) +} + // ResolveAsk applies env overrides (env wins over hive.yaml, as for the other // feature switches) and defaults. onHub forces direct mode: the hub always // calls the vendor itself. getenv is os.Getenv in production. diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 0c9656ad71..28c52ce29c 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -204,6 +204,10 @@ type Config struct { // Customers gates the Customers section and its people store (default // on). Nothing it stores leaves the hive. Customers CustomersConfig `yaml:"customers,omitempty" json:"customers,omitempty"` + // Ask is the optional Ask AI help panel (#19177): docs questions answered + // server side by Kapa.ai, directly or through the hub relay. Default off + // and inert when unconfigured. See src/docs/design/dashboard-ask-ai-help.md. + Ask AskConfig `yaml:"ask,omitempty" json:"ask,omitempty"` // DuplicateSweep gates the cross-PR duplicate suggestion pass // (hivecommons/hive#7469 capability B). Default off → zero behaviour // change and no GitHub traffic. diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 295a8ac3c0..53b360dd9e 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -78,6 +78,11 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // response to the hub over the spoke's authenticated hub link. See nps.go. s.mux.HandleFunc("GET /api/feedback/nps/status", s.handleNPSStatus) s.mux.HandleFunc("POST /api/feedback/nps", s.handleNPSSubmit) + // Ask AI help (#19183): 404 unless ask is on and configured. + s.mux.HandleFunc("GET /api/ask/status", s.handleAskStatus) + s.mux.HandleFunc("PUT /api/ask/consent", s.handleAskConsent) + s.mux.HandleFunc("DELETE /api/ask/consent", s.handleAskConsent) + s.mux.HandleFunc("POST /api/ask", s.handleAsk) s.mux.HandleFunc("GET /api/feedback/status", s.handleFeedbackStatus) s.mux.HandleFunc("POST /api/feedback/report", s.handleFeedbackReport) s.mux.HandleFunc("GET /api/feedback/mine", s.handleFeedbackMine) diff --git a/src/pkg/dashboard/api_ask.go b/src/pkg/dashboard/api_ask.go new file mode 100644 index 0000000000..4758c513fc --- /dev/null +++ b/src/pkg/dashboard/api_ask.go @@ -0,0 +1,320 @@ +package dashboard + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/askai" + "github.com/hivecommons/hive/pkg/config" + spoke "github.com/hivecommons/hive/pkg/hub/spoke" +) + +// Ask AI help on a hive dashboard (phase 4, #19183; design +// src/docs/design/dashboard-ask-ai-help.md). Off by default. With ask.enabled +// off, or on but not fully configured, every route answers 404 and nothing is +// read, stored or sent. Two modes: +// +// - direct: this hive calls Kapa.ai with its own key (a self-hosted hive). +// - hub: a hosted hive asks through the hub relay with its per-hive +// heartbeat bearer and holds no vendor key. +// +// The person's consent lives on this hive, one file per dashboard identity, +// and is checked before anything leaves. + +// askConsentDir is where per-person consent records live (tests override it). +var askConsentDir = "/data/ask-consents" + +// askKapaBaseURL overrides the vendor host in tests only. It is not +// configurable: the key must only ever go to the vendor. +var askKapaBaseURL = "" + +const ( + // maxAskRequestBody caps a question or consent body. + maxAskRequestBody = 8 << 10 + // askHiveAILabel is the label every answer carries. + askHiveAILabel = "AI generated, may be wrong. Answers by Kapa.ai from the Hive docs." + // askHostedOnlyProblem: the relay serves hosted hives only in this round. + // TODO(#19177): registered self-hosted hives on the hub relay. + askHostedOnlyProblem = "ask.mode hub serves hosted hives only; a self-hosted hive uses ask.mode direct with its own key" + askNoHubProblem = "ask.mode hub needs a hub link (hub.url) and a hive id" +) + +// askRuntime caches the built asker so limits and the breaker persist across +// requests; it is rebuilt when the effective settings change. +type askRuntime struct { + mu sync.Mutex + fingerprint string + asker askai.Asker +} + +// askEffective resolves ask for cfg and adds the hive-side gates: hub mode +// needs a hosted hive with a hub link. problem is "" when the feature is on. +func askEffective(cfg *config.Config) (config.AskSettings, string) { + st := cfg.AskSettings() + if !st.Requested { + return st, "" + } + if !st.Enabled { + return st, st.Problem + } + if st.Mode == config.AskModeHub { + if cfg == nil || cfg.Hub.HiveType != config.HiveTypeHosted { + return st, askHostedOnlyProblem + } + if strings.TrimSpace(cfg.Hub.URL) == "" || strings.TrimSpace(cfg.HiveID) == "" { + return st, askNoHubProblem + } + } + return st, "" +} + +func (s *Server) askConfig() *config.Config { + if s.deps == nil { + return nil + } + return s.deps.Config +} + +// askAsker returns the live asker, or nil when Ask is off for this hive. +func (s *Server) askAsker() askai.Asker { + cfg := s.askConfig() + st, problem := askEffective(cfg) + if !st.Enabled || problem != "" { + return nil + } + hubURL, hiveID := "", "" + if cfg != nil { + hubURL, hiveID = strings.TrimSpace(cfg.Hub.URL), strings.TrimSpace(cfg.HiveID) + } + fingerprint := fmt.Sprintf("%s|%s|%s|%s|%t|%+v|%s|%s", st.Mode, st.ProjectID, st.IntegrationID, st.APIKeyFile, + st.SendSectionLabel, st.Limits, hubURL, hiveID) + s.ask.mu.Lock() + defer s.ask.mu.Unlock() + if s.ask.asker != nil && s.ask.fingerprint == fingerprint { + return s.ask.asker + } + consent := &askai.ConsentStore{Dir: askConsentDir} + limits := askai.Limits{ + PersonPerMinute: st.Limits.PersonPerMinute, PersonPerHour: st.Limits.PersonPerHour, + HivePerHour: st.Limits.HivePerHour, GlobalPerMinute: st.Limits.GlobalPerMinute, + InFlight: st.Limits.InFlight, Daily: st.Limits.Daily, + } + var asker askai.Asker + switch st.Mode { + case config.AskModeDirect: + key, err := config.LoadAskAPIKey(st.APIKeyFile) + if err != nil { + s.logger.Warn("ask: requested but staying off", "reason", "api key file unreadable") + return nil + } + client, err := askai.NewKapaClient(askKapaBaseURL, st.ProjectID, st.IntegrationID, key, nil) + if err != nil { + s.logger.Warn("ask: requested but staying off", "reason", "vendor client not configured") + return nil + } + svc, err := askai.NewService(askai.Options{ + Upstream: client, Limits: limits, SendSectionLabel: st.SendSectionLabel, Consent: consent, Logger: s.logger, + }) + if err != nil { + return nil + } + asker = svc + case config.AskModeHub: + relay, err := askai.NewRelayAsker(askai.RelayOptions{ + HubURL: hubURL, HiveID: hiveID, Bearer: spoke.SpokeHeartbeatKey, Consent: consent, Limits: limits, Logger: s.logger, + }) + if err != nil { + return nil + } + asker = relay + default: + return nil + } + s.logger.Info("ask: enabled", "mode", st.Mode, "send_section_label", st.SendSectionLabel) + s.ask.asker, s.ask.fingerprint = asker, fingerprint + return asker +} + +// askPerson resolves the signed-in identity to its consent key, or writes the +// error. Anyone signed in may ask; nobody anonymous may. +func (s *Server) askPerson(w http.ResponseWriter, r *http.Request) (string, bool) { + user, _ := s.npsActor(r) + key := askai.PersonKey(user) + if key == "" { + jsonError(w, "sign in to use Ask", http.StatusUnauthorized) + return "", false + } + return key, true +} + +// askGate answers 404 when Ask is off, so an unconfigured hive has no route. +func (s *Server) askGate(w http.ResponseWriter, r *http.Request) (askai.Asker, string, bool) { + w.Header().Set("Cache-Control", "no-store") + asker := s.askAsker() + if asker == nil { + http.NotFound(w, r) + return nil, "", false + } + person, ok := s.askPerson(w, r) + if !ok { + return nil, "", false + } + return asker, person, true +} + +// hiveAskStatus mirrors the hub's status body. It never carries a vendor +// identifier or the key. +type hiveAskStatus struct { + Enabled bool `json:"enabled"` + TextVersion string `json:"text_version"` + Disclosure string `json:"disclosure"` + Consented bool `json:"consented"` + DocsURL string `json:"docs_url"` + AILabel string `json:"ai_label"` +} + +func (s *Server) handleAskStatus(w http.ResponseWriter, r *http.Request) { + _, person, ok := s.askGate(w, r) + if !ok { + return + } + store := &askai.ConsentStore{Dir: askConsentDir} + jsonResponse(w, hiveAskStatus{ + Enabled: true, TextVersion: askai.ConsentTextVersion, Disclosure: askai.ConsentText, + Consented: store.Has(person), DocsURL: askai.DocsHomeURL, AILabel: askHiveAILabel, + }) +} + +func (s *Server) handleAskConsent(w http.ResponseWriter, r *http.Request) { + _, person, ok := s.askGate(w, r) + if !ok { + return + } + store := &askai.ConsentStore{Dir: askConsentDir} + now := time.Now() + if r.Method == http.MethodDelete { + withdrawn, err := store.Withdraw(person, now) + if err != nil { + s.logger.Warn("ask consent store failed", "error", err) + jsonError(w, "could not access consent records", http.StatusInternalServerError) + return + } + if withdrawn { + s.logger.Info("audit: ask consent withdraw", "person", person, "text_version", askai.ConsentTextVersion) + } + w.WriteHeader(http.StatusNoContent) + return + } + var body struct { + TextVersion string `json:"text_version"` + } + if !decodeAskRequest(w, r, &body) { + return + } + if _, err := store.Grant(person, body.TextVersion, now); err != nil { + if errors.Is(err, askai.ErrStaleConsentVersion) { + jsonError(w, "disclosure version changed; reload and confirm again", http.StatusConflict) + return + } + s.logger.Warn("ask consent store failed", "error", err) + jsonError(w, "could not access consent records", http.StatusInternalServerError) + return + } + s.logger.Info("audit: ask consent grant", "person", person, "text_version", body.TextVersion) + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) handleAsk(w http.ResponseWriter, r *http.Request) { + asker, person, ok := s.askGate(w, r) + if !ok { + return + } + var req askai.Request + if !decodeAskRequest(w, r, &req) { + return + } + // The person comes from the authenticated request, never the body. + req.Person, req.HiveID = person, "" + jsonResponse(w, asker.Ask(r.Context(), req)) +} + +// decodeAskRequest reads exactly one JSON object with no unknown fields. +func decodeAskRequest(w http.ResponseWriter, r *http.Request, v any) bool { + defer closeHTTPBody(r.Body) + d := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxAskRequestBody)) + d.DisallowUnknownFields() + if d.Decode(v) != nil || d.Decode(new(json.RawMessage)) != io.EOF { + jsonError(w, "invalid JSON", http.StatusBadRequest) + return false + } + return true +} + +// featuresAskBody is the Ask part of the Settings, Features PUT. +type featuresAskBody struct { + AskEnabled *bool `json:"askEnabled"` + AskMode *string `json:"askMode"` + AskSendSectionLabel *bool `json:"askSendSectionLabel"` +} + +func (b featuresAskBody) prepare() (func(*config.Config), error) { + mode := "" + if b.AskMode != nil { + mode = strings.ToLower(strings.TrimSpace(*b.AskMode)) + switch mode { + case config.AskModeOff, config.AskModeDirect, config.AskModeHub: + default: + return nil, fmt.Errorf("ask mode must be one of %s, %s, %s", config.AskModeOff, config.AskModeDirect, config.AskModeHub) + } + } + return func(cfg *config.Config) { + if b.AskEnabled != nil { + on := *b.AskEnabled + cfg.Ask.Enabled = &on + } + if b.AskMode != nil { + cfg.Ask.Mode = mode + } + if b.AskSendSectionLabel != nil { + on := *b.AskSendSectionLabel + cfg.Ask.SendSectionLabel = &on + } + }, nil +} + +// featuresAskResponse is the GET side: the saved switch, the effective state +// and, when off although asked for, why (no values). Settings keys shown in +// the dialog: ask.enabled, ask.mode, ask.send_section_label; the Kapa values +// ask.kapa.project_id, ask.kapa.integration_id and ask.kapa.api_key_file, and +// the limits ask.limits.person_per_minute, ask.limits.person_per_hour, +// ask.limits.hive_per_hour, ask.limits.global_per_minute, +// ask.limits.in_flight and ask.limits.daily are set in hive.yaml or env. +func featuresAskResponse(cfg *config.Config) map[string]interface{} { + st, problem := askEffective(cfg) + saved := false + mode := config.AskModeOff + label := config.DefaultAskSendSectionLabel + if cfg != nil { + saved = cfg.Ask.Enabled != nil && *cfg.Ask.Enabled + if m := strings.TrimSpace(cfg.Ask.Mode); m != "" { + mode = m + } + if cfg.Ask.SendSectionLabel != nil { + label = *cfg.Ask.SendSectionLabel + } + } + return map[string]interface{}{ + "askEnabled": saved, + "askEffective": st.Enabled && problem == "", + "askMode": mode, + "askModeEffective": st.Mode, + "askSendSectionLabel": label, + "askProblem": problem, + } +} diff --git a/src/pkg/dashboard/api_ask_test.go b/src/pkg/dashboard/api_ask_test.go new file mode 100644 index 0000000000..53be15abeb --- /dev/null +++ b/src/pkg/dashboard/api_ask_test.go @@ -0,0 +1,324 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/askai" + "github.com/hivecommons/hive/pkg/config" + spoke "github.com/hivecommons/hive/pkg/hub/spoke" +) + +const ( + askTestKey = "kapa-hive-key-secret" + askTestProject = "proj-hive-1111" + askTestIntegration = "integ-hive-2222" + askTestBearer = "hive-heartbeat-bearer" +) + +// askFakeRemote stands in for Kapa (direct mode) or the hub relay (hub mode) +// and records every request body. +type askFakeRemote struct { + mu sync.Mutex + bodies []string + headers []http.Header + paths []string + srv *httptest.Server +} + +func newAskFakeRemote(t *testing.T, reply string) *askFakeRemote { + t.Helper() + f := &askFakeRemote{} + f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.bodies = append(f.bodies, string(b)) + f.headers = append(f.headers, r.Header.Clone()) + f.paths = append(f.paths, r.URL.Path) + f.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, reply) + })) + t.Cleanup(f.srv.Close) + return f +} + +func (f *askFakeRemote) seen() ([]string, []http.Header, []string) { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.bodies...), append([]http.Header(nil), f.headers...), append([]string(nil), f.paths...) +} + +const askKapaReply = `{"answer":"Open Settings, then Features.","thread_id":"t-1","question_answer_id":"qa","is_uncertain":false, + "relevant_sources":[{"source_url":"https://docs.hivecommons.dev/settings/","title":"Settings","contains_internal_data":false}]}` + +const askHubReply = `{"outcome":"ok","answer":"Open Settings, then Features.","sources":[{"title":"Settings","url":"https://docs.hivecommons.dev/settings/"}],"conversation":"00112233445566778899aabbccddeeff","ai_generated":true,"docs_url":"https://docs.hivecommons.dev/"}` + +// askTestServer builds a dashboard server with the given ask block. It +// isolates the consent dir, the secret roots, the vendor host and env. +func askTestServer(t *testing.T, ask config.AskConfig, hub config.HubConfig, kapaURL string) (*Server, *bytes.Buffer) { + t.Helper() + for _, k := range []string{config.EnvAskEnabled, config.EnvAskMode, config.EnvAskKapaProjectID, config.EnvAskKapaIntegrationID, + config.EnvAskKapaAPIKeyFile, config.EnvAskSendSectionLabel} { + t.Setenv(k, "") + } + t.Setenv(spoke.EnvHeartbeatKey, askTestBearer) + oldDir, oldBase := askConsentDir, askKapaBaseURL + askConsentDir, askKapaBaseURL = filepath.Join(t.TempDir(), "ask-consents"), kapaURL + t.Cleanup(func() { askConsentDir, askKapaBaseURL = oldDir, oldBase }) + secrets := t.TempDir() + t.Cleanup(config.SetSecretFileRootsForTest(secrets)) + keyPath := filepath.Join(secrets, "kapa-api-key") + if err := os.WriteFile(keyPath, []byte(askTestKey), 0o600); err != nil { + t.Fatal(err) + } + if ask.Kapa.APIKeyFile == "key" { + ask.Kapa.APIKeyFile = keyPath + } + s := NewServer(0, dismissLogger()) + logs := &bytes.Buffer{} + s.logger = slog.New(slog.NewTextHandler(logs, nil)) + s.deps = &Dependencies{Config: &config.Config{HiveID: "acme-secret-hive", Hub: hub, Ask: ask}} + return s, logs +} + +func askCall(s *Server, method, path, body, user string) *httptest.ResponseRecorder { + var rd io.Reader + if body != "" { + rd = strings.NewReader(body) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("Content-Type", "application/json") + if user != "" { + req.Header.Set("X-Hive-User", user) + req.Header.Set("X-Hive-Role", "write") + } + rec := httptest.NewRecorder() + switch { + case path == "/api/ask/status": + s.handleAskStatus(rec, req) + case path == "/api/ask/consent": + s.handleAskConsent(rec, req) + default: + s.handleAsk(rec, req) + } + return rec +} + +func askResult(t *testing.T, rec *httptest.ResponseRecorder) askai.Result { + t.Helper() + var r askai.Result + if err := json.Unmarshal(rec.Body.Bytes(), &r); err != nil { + t.Fatalf("decode %d %s: %v", rec.Code, rec.Body, err) + } + return r +} + +func askOn() *bool { v := true; return &v } + +var askDirect = config.AskConfig{Enabled: askOn(), Mode: config.AskModeDirect, + Kapa: config.AskKapaConfig{ProjectID: askTestProject, IntegrationID: askTestIntegration, APIKeyFile: "key"}} + +// TestHiveAskOffIsInert: no ask block, or a half-configured one, answers 404 +// on every route, writes no consent and sends nothing. +func TestHiveAskOffIsInert(t *testing.T) { + kapa := newAskFakeRemote(t, askKapaReply) + half := askDirect + half.Kapa.IntegrationID = "" + for name, ask := range map[string]config.AskConfig{"unset": {}, "switched off": {Mode: config.AskModeDirect}, "half-configured": half} { + s, logs := askTestServer(t, ask, config.HubConfig{}, kapa.srv.URL) + for _, c := range []struct{ method, path, body string }{ + {"GET", "/api/ask/status", ""}, {"PUT", "/api/ask/consent", `{"text_version":"1"}`}, {"POST", "/api/ask", `{"question":"q?"}`}, + } { + if rec := askCall(s, c.method, c.path, c.body, "alice"); rec.Code != http.StatusNotFound { + t.Errorf("%s: %s %s = %d", name, c.method, c.path, rec.Code) + } + } + if _, err := os.Stat(askConsentDir); !os.IsNotExist(err) { + t.Errorf("%s: a consent dir was created", name) + } + if strings.Contains(logs.String(), askTestProject) || strings.Contains(logs.String(), askTestIntegration) { + t.Errorf("%s: logs name a vendor id", name) + } + } + if b, _, _ := kapa.seen(); len(b) != 0 { + t.Fatalf("the vendor saw %d requests with Ask off", len(b)) + } +} + +// TestHiveAskCSPIsUnchangedWhenOn is the CSP tripwire: switching Ask on must +// not change a single byte of the security headers. +func TestHiveAskCSPIsUnchangedWhenOn(t *testing.T) { + headers := func(ask config.AskConfig) http.Header { + s, _ := askTestServer(t, ask, config.HubConfig{}, "") + h := s.securityHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + return rec.Header() + } + off, onH := headers(config.AskConfig{}), headers(askDirect) + for _, k := range []string{"Content-Security-Policy", "X-Frame-Options", "Referrer-Policy", "Permissions-Policy"} { + if off.Get(k) != onH.Get(k) { + t.Errorf("%s changed with Ask on:\n%q\n%q", k, off.Get(k), onH.Get(k)) + } + } + if off.Get("Content-Security-Policy") == "" { + t.Fatal("expected a CSP to compare") + } +} + +// TestHiveAskDirectModeFlow covers consent, the exact vendor payload, refusal +// of credential-shaped input and that the person comes from the request. +func TestHiveAskDirectModeFlow(t *testing.T) { + kapa := newAskFakeRemote(t, askKapaReply) + s, logs := askTestServer(t, askDirect, config.HubConfig{}, kapa.srv.URL) + + if rec := askCall(s, "POST", "/api/ask", `{"question":"q?"}`, ""); rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous: %d", rec.Code) + } + if r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"Where do I pause an agent?"}`, "alice-login")); r.Outcome != askai.OutcomeNotConsented { + t.Fatalf("before consent: %+v", r) + } + var st hiveAskStatus + if err := json.Unmarshal(askCall(s, "GET", "/api/ask/status", "", "alice-login").Body.Bytes(), &st); err != nil || !st.Enabled || st.Consented { + t.Fatalf("status %+v %v", st, err) + } + if rec := askCall(s, "PUT", "/api/ask/consent", `{"text_version":"0"}`, "alice-login"); rec.Code != http.StatusConflict { + t.Fatalf("stale disclosure: %d", rec.Code) + } + if rec := askCall(s, "PUT", "/api/ask/consent", `{"text_version":"`+askai.ConsentTextVersion+`"}`, "alice-login"); rec.Code != http.StatusNoContent { + t.Fatalf("grant: %d %s", rec.Code, rec.Body) + } + if rec := askCall(s, "POST", "/api/ask", `{"question":"q?","person":"bob"}`, "alice-login"); rec.Code != http.StatusBadRequest { + t.Fatalf("person in body: %d", rec.Code) + } + r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"Where do I pause an agent?","section":"agents-section"}`, "alice-login")) + if r.Outcome != askai.OutcomeOK || len(r.Sources) != 1 || !r.AIGenerated { + t.Fatalf("answer %+v", r) + } + if r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"token ghp_abcdefghijklmnopqrstuvwxyz0123"}`, "alice-login")); r.Outcome != askai.OutcomeRefusedSecretShape { + t.Fatalf("credential: %+v", r) + } + if r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"q?"}`, "bob")); r.Outcome != askai.OutcomeNotConsented { + t.Fatalf("bob covered by alice: %+v", r) + } + + bodies, headers, paths := kapa.seen() + if len(bodies) != 1 || paths[0] != "/query/v1/projects/"+askTestProject+"/chat/" || headers[0].Get("X-API-KEY") != askTestKey { + t.Fatalf("vendor saw %q %q", bodies, paths) + } + var payload map[string]any + if err := json.Unmarshal([]byte(bodies[0]), &payload); err != nil { + t.Fatal(err) + } + if len(payload) != 2 || payload["query"] != "Dashboard section: Agents.\n\nWhere do I pause an agent?" || payload["integration_id"] != askTestIntegration { + t.Fatalf("payload %v", payload) + } + for _, seeded := range []string{"alice-login", "acme-secret-hive", "ghp_"} { + if strings.Contains(bodies[0], seeded) { + t.Fatalf("payload leaks %q", seeded) + } + } + if rec := askCall(s, "DELETE", "/api/ask/consent", "", "alice-login"); rec.Code != http.StatusNoContent { + t.Fatalf("withdraw: %d", rec.Code) + } + if r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"q?"}`, "alice-login")); r.Outcome != askai.OutcomeNotConsented { + t.Fatalf("after withdrawal: %+v", r) + } + all := logs.String() + for _, v := range []string{askTestKey, askTestProject, askTestIntegration, "pause an agent"} { + if strings.Contains(all, v) { + t.Fatalf("logs carry %q:\n%s", v, all) + } + } + if !strings.Contains(all, "audit: ask consent grant") || !strings.Contains(all, "audit: ask consent withdraw") { + t.Fatalf("missing consent audit:\n%s", all) + } +} + +// TestHiveAskHubModeUsesTheRelay: a hosted hive in hub mode holds no key and +// posts to the hub relay with its heartbeat bearer; a self-hosted hive in hub +// mode stays off. +func TestHiveAskHubModeUsesTheRelay(t *testing.T) { + hubSrv := newAskFakeRemote(t, askHubReply) + hubMode := config.AskConfig{Enabled: askOn(), Mode: config.AskModeHub} + s, _ := askTestServer(t, hubMode, config.HubConfig{Enabled: true, URL: hubSrv.srv.URL, HiveType: config.HiveTypeHosted}, "") + askCall(s, "PUT", "/api/ask/consent", `{"text_version":"`+askai.ConsentTextVersion+`"}`, "alice") + r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"Where is pause?","section":"agents-section"}`, "alice")) + if r.Outcome != askai.OutcomeOK || r.Conversation == "" || r.Conversation == "00112233445566778899aabbccddeeff" { + t.Fatalf("relayed answer %+v", r) + } + bodies, headers, paths := hubSrv.seen() + if len(bodies) != 1 || paths[0] != askai.RelayPath || headers[0].Get("Authorization") != "Bearer "+askTestBearer || + headers[0].Get(askai.RelayHiveIDHeader) != "acme-secret-hive" || strings.Contains(bodies[0], "alice") { + t.Fatalf("relay call %q %q %v", bodies, paths, headers) + } + if headers[0].Get("X-API-KEY") != "" { + t.Fatal("a hive in hub mode must never send a vendor key") + } + + selfHosted, _ := askTestServer(t, hubMode, config.HubConfig{Enabled: true, URL: hubSrv.srv.URL}, "") + if rec := askCall(selfHosted, "GET", "/api/ask/status", "", "alice"); rec.Code != http.StatusNotFound { + t.Fatalf("self-hosted hive in hub mode: %d", rec.Code) + } + if _, problem := askEffective(selfHosted.deps.Config); problem != askHostedOnlyProblem { + t.Fatalf("problem %q", problem) + } + noHub, _ := askTestServer(t, hubMode, config.HubConfig{HiveType: config.HiveTypeHosted}, "") + if _, problem := askEffective(noHub.deps.Config); problem != askNoHubProblem { + t.Fatalf("no hub link: %q", problem) + } +} + +func TestHiveAskSettingsFeaturesAndExport(t *testing.T) { + s, _ := askTestServer(t, askDirect, config.HubConfig{}, "") + got := featuresAskResponse(s.deps.Config) + if got["askEnabled"] != true || got["askEffective"] != true || got["askMode"] != config.AskModeDirect || got["askProblem"] != "" { + t.Fatalf("features GET %v", got) + } + for _, v := range got { + if str, ok := v.(string); ok && (strings.Contains(str, askTestProject) || strings.Contains(str, askTestIntegration)) { + t.Fatalf("features GET exposes a vendor id: %v", got) + } + } + if _, err := (featuresAskBody{AskMode: strPtr("sideways")}).prepare(); err == nil { + t.Fatal("an unknown mode must be rejected") + } + off := false + apply, err := (featuresAskBody{AskEnabled: &off, AskMode: strPtr(" HUB "), AskSendSectionLabel: &off}).prepare() + if err != nil { + t.Fatal(err) + } + cfg := s.deps.Config + apply(cfg) + if *cfg.Ask.Enabled || cfg.Ask.Mode != config.AskModeHub || *cfg.Ask.SendSectionLabel { + t.Fatalf("features PUT applied %+v", cfg.Ask) + } + if r := featuresAskResponse(cfg); r["askEffective"] != false || r["askSendSectionLabel"] != false { + t.Fatalf("after switching off %v", r) + } + + // The config export redacts every ask.kapa value, and JSON never carries + // the vendor ids at all. + exported := redactConfigValue(map[string]any{"ask": map[string]any{"kapa": map[string]any{ + "project_id": askTestProject, "integration_id": askTestIntegration, "api_key_file": "/secrets/kapa/api-key"}}}, "") + raw, _ := json.Marshal(exported) + for _, v := range []string{askTestProject, askTestIntegration, "/secrets/kapa/api-key"} { + if strings.Contains(string(raw), v) { + t.Fatalf("export leaks %q: %s", v, raw) + } + } + js, _ := json.Marshal(cfg.Ask) + if strings.Contains(string(js), askTestProject) || strings.Contains(string(js), askTestIntegration) { + t.Fatalf("config JSON carries vendor ids: %s", js) + } +} diff --git a/src/pkg/dashboard/api_config_export.go b/src/pkg/dashboard/api_config_export.go index e8b4606d8e..f209f84458 100644 --- a/src/pkg/dashboard/api_config_export.go +++ b/src/pkg/dashboard/api_config_export.go @@ -89,6 +89,12 @@ type configRedactionMarker struct { } var configExportSecretKeyRE = regexp.MustCompile(`(?i)(token|secret|password|authorization|api[_-]?key|apikey|backup.*key|webhook.*secret|oauth.*secret|bob.*key)`) + +// configExportSecretParents name blocks whose every configured value is +// treated as a credential in the export: ask.kapa holds the vendor project and +// integration ids and the key file path (#19183). +var configExportSecretParents = map[string]bool{"kapa": true} + var configEnvSecretKeyRE = regexp.MustCompile(`(?i)(TOKEN|KEY|SECRET|PASSWORD)`) func (s *Server) handleConfigExport(w http.ResponseWriter, r *http.Request) { @@ -259,6 +265,10 @@ func redactConfigValue(v any, key string) any { case map[string]any: out := make(map[string]any, len(x)) for k, val := range x { + if configExportSecretParents[key] && hasConfiguredValue(val) { + out[k] = redactMarker(fmt.Sprint(val)) + continue + } out[k] = redactConfigValue(val, k) } return out diff --git a/src/pkg/dashboard/api_governor_features.go b/src/pkg/dashboard/api_governor_features.go index 3cb39df9ef..a94ab9231b 100644 --- a/src/pkg/dashboard/api_governor_features.go +++ b/src/pkg/dashboard/api_governor_features.go @@ -165,6 +165,7 @@ func (s *Server) handleGovernorFeatures(w http.ResponseWriter, r *http.Request) featuresOpsBody featuresPlatformBody featuresRunsBody + featuresAskBody } if err := decodeBody(r, &body); err != nil { jsonError(w, "invalid body", http.StatusBadRequest) @@ -293,11 +294,17 @@ func (s *Server) handleGovernorFeatures(w http.ResponseWriter, r *http.Request) jsonError(w, err.Error(), http.StatusBadRequest) return } + applyAsk, err := body.featuresAskBody.prepare() + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } // --- apply --- cfg := s.deps.Config applyOps(cfg) applyPlatform(cfg) + applyAsk(cfg) applyRuns(cfg) if body.IoscanEnabled != nil { v := *body.IoscanEnabled @@ -637,6 +644,9 @@ func featuresSectionResponse(cfg *config.Config) map[string]interface{} { for k, v := range featuresRunsResponse(cfg) { out[k] = v } + for k, v := range featuresAskResponse(cfg) { + out[k] = v + } return out } diff --git a/src/pkg/dashboard/openapi_schema_parity_test.go b/src/pkg/dashboard/openapi_schema_parity_test.go index 3fd468a386..88136fdb33 100644 --- a/src/pkg/dashboard/openapi_schema_parity_test.go +++ b/src/pkg/dashboard/openapi_schema_parity_test.go @@ -63,6 +63,11 @@ func TestOpenAPISchemaFieldsExistOnGoTypes(t *testing.T) { "before the first status build completes, instead of a StatusPayload.", }, }, + { + name: "GET /api/ask/status", + path: "/api/ask/status", + goType: reflect.TypeOf(hiveAskStatus{}), + }, { name: "GET /api/tokens", path: "/api/tokens", diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index a04953cc94..76655c84af 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -110,6 +110,7 @@ const staleDropStarvationThreshold = 5 type Server struct { nativeQueueTracker nativeQueueTrackerRuntime + ask askRuntime // Ask AI help asker, built on first use (#19183) integration integrationRuntime webhookNoSecretOnce sync.Once // warn once per process about a missing webhook secret (#13666) prGateOnce sync.Once // builds the PR gate on first use (#19038) diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 7586a67611..404c76e59f 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -900,6 +900,19 @@ ${f.customersSearchEffective !== f.customersSearch ? `

HIVE_CUSTOMERS_MENTION_SEARCH_ENABLED (or turning Customers off) overrides this setting: the search is currently ${f.customersSearchEffective ? 'on' : 'off'}.

` : ''} +
+
+
+ Ask AI help ${yamlHint('ask.enabled')} ${settingHelpMark('settings', 'features', 'Ask AI help', `OFF by default. Shows an Ask panel that answers questions about using this dashboard from the Hive docs. What is sent: the question a person types, and the label of the dashboard section they are in (from a fixed list, never anything on screen), to Kapa.ai, an AI service; the project's Kapa administrators can read questions in their analytics. Nothing else leaves: no login, email, page content, URL, repo, hive or agent name. Each person confirms a notice before their first question and can withdraw. Questions that look like a password, token or key are refused and not sent. Answers show their sources and an "AI generated, may be wrong" label. Needs a mode: hub (hosted hives, through the hub relay; no key on this hive) or direct (this hive calls Kapa.ai with its own key, set as ask.kapa.project_id, ask.kapa.integration_id and ask.kapa.api_key_file in hive.yaml or HIVE_ASK_* env). Limits: ask.limits.person_per_minute, ask.limits.person_per_hour, ask.limits.hive_per_hour, ask.limits.global_per_minute, ask.limits.in_flight, ask.limits.daily. HIVE_ASK_ENABLED overrides the switch. See src/docs/design/dashboard-ask-ai-help.md.`)} +
+ ${f.askEnabled && !f.askEffective ? `

Ask stays off: ${esc(f.askProblem || 'HIVE_ASK_ENABLED overrides this setting')}.

` : ''} + ${!f.askEnabled && f.askEffective ? `

HIVE_ASK_ENABLED overrides this setting: Ask is currently on.

` : ''} +
+
+
+ Send the section label with questions ${yamlHint('ask.send_section_label')} ${settingHelpMark('settings', 'features', 'Ask section label', `ON by default. Adds the name of the dashboard section the person is in, taken from a fixed list of section names, so "where is this button" finds the right page. Off sends the question alone. HIVE_ASK_SEND_SECTION_LABEL overrides it.`)} +
+
diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 7334f6e6e3..12f7023d13 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -79627,6 +79627,19 @@

${esc(s.title)}

${f.customersSearchEffective !== f.customersSearch ? `

HIVE_CUSTOMERS_MENTION_SEARCH_ENABLED (or turning Customers off) overrides this setting: the search is currently ${f.customersSearchEffective ? 'on' : 'off'}.

` : ''}
+
+
+
+ Ask AI help ${yamlHint('ask.enabled')} ${settingHelpMark('settings', 'features', 'Ask AI help', `OFF by default. Shows an Ask panel that answers questions about using this dashboard from the Hive docs. What is sent: the question a person types, and the label of the dashboard section they are in (from a fixed list, never anything on screen), to Kapa.ai, an AI service; the project's Kapa administrators can read questions in their analytics. Nothing else leaves: no login, email, page content, URL, repo, hive or agent name. Each person confirms a notice before their first question and can withdraw. Questions that look like a password, token or key are refused and not sent. Answers show their sources and an "AI generated, may be wrong" label. Needs a mode: hub (hosted hives, through the hub relay; no key on this hive) or direct (this hive calls Kapa.ai with its own key, set as ask.kapa.project_id, ask.kapa.integration_id and ask.kapa.api_key_file in hive.yaml or HIVE_ASK_* env). Limits: ask.limits.person_per_minute, ask.limits.person_per_hour, ask.limits.hive_per_hour, ask.limits.global_per_minute, ask.limits.in_flight, ask.limits.daily. HIVE_ASK_ENABLED overrides the switch. See src/docs/design/dashboard-ask-ai-help.md.`)} +
+ ${f.askEnabled && !f.askEffective ? `

Ask stays off: ${esc(f.askProblem || 'HIVE_ASK_ENABLED overrides this setting')}.

` : ''} + ${!f.askEnabled && f.askEffective ? `

HIVE_ASK_ENABLED overrides this setting: Ask is currently on.

` : ''} +
+
+
+ Send the section label with questions ${yamlHint('ask.send_section_label')} ${settingHelpMark('settings', 'features', 'Ask section label', `ON by default. Adds the name of the dashboard section the person is in, taken from a fixed list of section names, so "where is this button" finds the right page. Off sends the question alone. HIVE_ASK_SEND_SECTION_LABEL overrides it.`)} +
+
diff --git a/src/pkg/hub/ask.go b/src/pkg/hub/ask.go index 93d23e48cc..7eb3e6a925 100644 --- a/src/pkg/hub/ask.go +++ b/src/pkg/hub/ask.go @@ -135,6 +135,9 @@ func (s *HubServer) registerAskRoutes() { s.mux.HandleFunc("GET "+askStatsPath, s.requireAdmin(s.handleAskStats)) s.mux.HandleFunc("GET "+askPanelJSPath, serveAskAsset("text/javascript; charset=utf-8", askai.PanelJS)) s.mux.HandleFunc("GET "+askPanelCSSPath, serveAskAsset("text/css; charset=utf-8", askai.PanelCSS)) + // Hub relay for hosted hives (#19183): per-hive heartbeat bearer, no + // session. + s.mux.HandleFunc("POST "+askai.RelayPath, s.handleAskRelay) } // askPanelTags are the only additions the panel makes to the dashboard diff --git a/src/pkg/hub/ask_relay.go b/src/pkg/hub/ask_relay.go new file mode 100644 index 0000000000..d6c82e6fde --- /dev/null +++ b/src/pkg/hub/ask_relay.go @@ -0,0 +1,80 @@ +package hub + +import ( + "net/http" + "strings" + "sync" + + "github.com/hivecommons/hive/pkg/askai" + "github.com/hivecommons/hive/pkg/config" +) + +// Ask hub relay (phase 4, #19183). Hosted hives ask through the hub so the +// Kapa key never leaves it. A hive authenticates with the per-hive heartbeat +// bearer it already holds; no new secret is issued. The route exists only when +// Ask is on at the hub. + +// registeredRelayWarnOnce says once that ask.relay.hives=registered is not +// served in this round. +var registeredRelayWarnOnce sync.Once + +// relayAllowsHive reports whether the relay serves hiveID: hosted hives only +// in this round, minus any hive the operator disabled. +// +// TODO(#19177): serving self-hosted hives registered with this hub +// (AskRelayRegistered) waits for an operator decision; until then it behaves +// as AskRelayHosted. +func (s *HubServer) relayAllowsHive(hiveID string) bool { + if s.ask == nil { + return false + } + settings := s.ask.settings + if settings.DisabledHives[hiveID] { + return false + } + switch settings.RelayHives { + case config.AskRelayNone: + return false + case config.AskRelayRegistered: + registeredRelayWarnOnce.Do(func() { + s.logger.Warn("ask: relay for registered self-hosted hives is not served yet; serving hosted hives only") + }) + } + return askHiveIsHosted(hiveID) +} + +// askHiveIsHosted: a hive this hub provisioned and runs, never a self-service +// (byo-) registration. +func askHiveIsHosted(hiveID string) bool { + if strings.HasPrefix(hiveID, SelfServiceHiveIDPrefix) { + return false + } + return loadSaaSHive(hiveID) != nil +} + +// handleAskRelay answers POST /api/hub/ask/relay for a hive. +func (s *HubServer) handleAskRelay(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + auth := r.Header.Get("Authorization") + hiveID := r.Header.Get(askai.RelayHiveIDHeader) + if !strings.HasPrefix(auth, "Bearer ") || hiveID == "" || hiveID != sanitizeHeartbeatField(hiveID) || !isValidName(hiveID) { + writeJSONError(w, http.StatusUnauthorized, "unauthorized") + return + } + if s.hubSecret == "" || !s.verifyHeartbeatBearer(strings.TrimPrefix(auth, "Bearer "), hiveID) { + writeJSONError(w, http.StatusUnauthorized, "unauthorized") + return + } + var req askai.Request + if !decodeAskBody(w, r, &req) { + return + } + if !s.relayAllowsHive(hiveID) { + s.logger.Info("audit: ask request", "hive", hiveID, "outcome", string(askai.OutcomeRelayDisabled)) + writeAskJSON(w, http.StatusOK, s.ask.svc.RelayDisabledResult()) + return + } + // The hive is the bearer's hive; the person is never sent. + req.Person, req.HiveID = "", hiveID + writeAskJSON(w, http.StatusOK, s.ask.svc.Relay(r.Context(), req)) +} diff --git a/src/pkg/hub/ask_relay_test.go b/src/pkg/hub/ask_relay_test.go new file mode 100644 index 0000000000..503cf84bf4 --- /dev/null +++ b/src/pkg/hub/ask_relay_test.go @@ -0,0 +1,165 @@ +package hub + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/askai" + "github.com/hivecommons/hive/pkg/config" +) + +// relayFakeUpstream records the vendor thread each relayed call used. +type relayFakeUpstream struct { + mu sync.Mutex + queries []string + threads []string +} + +func (f *relayFakeUpstream) Chat(_ context.Context, thread, query string) (askai.UpstreamAnswer, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.queries = append(f.queries, query) + f.threads = append(f.threads, thread) + return askai.UpstreamAnswer{ + Answer: "Settings, Features.", + ThreadID: "vendor-thread-" + string(rune('a'+len(f.threads)-1)), + Sources: []askai.UpstreamSource{{URL: "https://docs.hivecommons.dev/settings/", Title: "Settings"}}, + }, nil +} + +func (f *relayFakeUpstream) snapshot() ([]string, []string) { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.queries...), append([]string(nil), f.threads...) +} + +func relayDo(s *HubServer, bearerHive, headerHive, body string) (*httptest.ResponseRecorder, askai.Result) { + r := httptest.NewRequest(http.MethodPost, askai.RelayPath, strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + if bearerHive != "" { + r.Header.Set("Authorization", heartbeatBearer(testHubSecret, bearerHive)) + } + r.Header.Set(askai.RelayHiveIDHeader, headerHive) + w := httptest.NewRecorder() + s.mux.ServeHTTP(w, r) + var res askai.Result + if w.Code == http.StatusOK { + _ = json.Unmarshal(w.Body.Bytes(), &res) + } + return w, res +} + +func mkHostedHive(t *testing.T, id string) { + t.Helper() + if err := saveSaaSHive(&SaaSHive{ID: id, Owner: "alice"}); err != nil { + t.Fatal(err) + } +} + +func TestHubAskRelayIsAbsentWhenOff(t *testing.T) { + s, _ := newAskTestHub(t, false, nil) + mkHostedHive(t, "hosted-a") + if w, _ := relayDo(s, "hosted-a", "hosted-a", `{"question":"q?"}`); w.Code != http.StatusNotFound { + t.Fatalf("relay with Ask off answered %d", w.Code) + } +} + +func TestHubAskRelayAuthenticatesTheHiveAndServesHostedOnly(t *testing.T) { + t.Setenv(config.EnvAskRelayDisabledHives, "hosted-off") + t.Setenv(config.EnvAskLimitHivePerHour, "2") + up := &relayFakeUpstream{} + s, logs := newAskTestHub(t, true, up) + for _, id := range []string{"hosted-a", "hosted-b", "hosted-off"} { + mkHostedHive(t, id) + } + const q = `{"question":"Where is pause?","section":"agents-section"}` + + if w, _ := relayDo(s, "", "hosted-a", q); w.Code != http.StatusUnauthorized { + t.Fatalf("no bearer: %d", w.Code) + } + if w, _ := relayDo(s, "hosted-b", "hosted-a", q); w.Code != http.StatusUnauthorized { + t.Fatalf("hive B's bearer for hive A: %d", w.Code) + } + if w, _ := relayDo(s, "hosted-a", "hosted-a", `{"question":"q?","person":"alice"}`); w.Code != http.StatusBadRequest { + t.Fatalf("a person field must be rejected: %d", w.Code) + } + for _, id := range []string{"hosted-off", "not-provisioned"} { + if w, r := relayDo(s, id, id, q); w.Code != http.StatusOK || r.Outcome != askai.OutcomeRelayDisabled { + t.Fatalf("%s: %d %+v", id, w.Code, r) + } + } + // A self-service (byo-) hive never authenticates with hub-derived + // material, and is never served by the relay even if it did. + if w, r := relayDo(s, "byo-alice--home", "byo-alice--home", q); w.Code != http.StatusUnauthorized && r.Outcome != askai.OutcomeRelayDisabled { + t.Fatalf("byo hive: %d %+v", w.Code, r) + } + if askHiveIsHosted("byo-alice--home") { + t.Fatal("a byo- hive is never hosted") + } + if q, _ := up.snapshot(); len(q) != 0 { + t.Fatalf("refused hives reached the vendor: %q", q) + } + + _, a1 := relayDo(s, "hosted-a", "hosted-a", q) + if a1.Outcome != askai.OutcomeOK || a1.Conversation == "" || len(a1.Sources) != 1 { + t.Fatalf("hosted hive: %+v", a1) + } + // Hive B presenting hive A's handle starts a fresh vendor thread. + _, b1 := relayDo(s, "hosted-b", "hosted-b", `{"question":"and?","conversation":"`+a1.Conversation+`"}`) + _, a2 := relayDo(s, "hosted-a", "hosted-a", `{"question":"and?","conversation":"`+a1.Conversation+`"}`) + if b1.Outcome != askai.OutcomeOK || a2.Outcome != askai.OutcomeOK { + t.Fatalf("follow-ups: %+v %+v", b1, a2) + } + queries, threads := up.snapshot() + if want := []string{"", "", "vendor-thread-a"}; strings.Join(threads, ",") != strings.Join(want, ",") { + t.Fatalf("threads %q, want %q", threads, want) + } + if queries[0] != "Dashboard section: Agents.\n\nWhere is pause?" { + t.Fatalf("vendor query %q", queries[0]) + } + // Hive A has spent its hourly quota of 2; hive B has not. + if _, r := relayDo(s, "hosted-a", "hosted-a", q); r.Outcome != askai.OutcomeRateLimited { + t.Fatalf("hive A quota: %+v", r) + } + if _, r := relayDo(s, "hosted-b", "hosted-b", q); r.Outcome != askai.OutcomeOK { + t.Fatalf("hive B charged for hive A: %+v", r) + } + if !strings.Contains(logs.String(), "hive=hosted-a") || strings.Contains(logs.String(), "Where is pause") { + t.Fatalf("relay audit lines:\n%s", logs) + } +} + +func TestHubAskRelayNoneTurnsTheRelayOff(t *testing.T) { + t.Setenv(config.EnvAskRelayHives, config.AskRelayNone) + up := &relayFakeUpstream{} + s, _ := newAskTestHub(t, true, up) + mkHostedHive(t, "hosted-a") + if _, r := relayDo(s, "hosted-a", "hosted-a", `{"question":"q?"}`); r.Outcome != askai.OutcomeRelayDisabled { + t.Fatalf("relay none: %+v", r) + } + t.Setenv(config.EnvAskRelayHives, config.AskRelayRegistered) + s2, logs := newAskTestHub(t, true, up) + mkHostedHive(t, "hosted-a") + if _, r := relayDo(s2, "hosted-a", "hosted-a", `{"question":"q?"}`); r.Outcome != askai.OutcomeOK { + t.Fatalf("registered behaves as hosted: %+v", r) + } + if w, r := relayDo(s2, "byo-bob--x", "byo-bob--x", `{"question":"q?"}`); w.Code != http.StatusUnauthorized && r.Outcome != askai.OutcomeRelayDisabled { + t.Fatalf("self-hosted on registered: %d %+v", w.Code, r) + } + if !strings.Contains(logs.String(), "relay for registered self-hosted hives is not served yet") && !registeredWarned() { + t.Fatalf("no registered-mode warning:\n%s", logs) + } +} + +// registeredWarned reports whether the once-only warning already fired in an +// earlier test of this process. +func registeredWarned() bool { + fired := true + registeredRelayWarnOnce.Do(func() { fired = false }) + return fired +} diff --git a/src/pkg/prosefilter/outbound_sites_test.go b/src/pkg/prosefilter/outbound_sites_test.go index 55843aff84..7610ec4e42 100644 --- a/src/pkg/prosefilter/outbound_sites_test.go +++ b/src/pkg/prosefilter/outbound_sites_test.go @@ -118,6 +118,7 @@ var outboundSites = map[string]outboundSite{ "agent.(*sharedSessionPoolClient).request": machine(reasonInternalAPI), "api.(*Client).request": machine(reasonInternalAPI), "askai.(*KapaClient).Chat": machine(reasonModelPrompt), + "askai.(*RelayAsker).ask": machine(reasonSpokeToHub), "auth.(*Provider).fetchIDToken": machine(reasonAuth), "callback.(*Client).do": machine(reasonInternalAPI), "client.(*Client).doJSON": machine(reasonInternalAPI), From 2d345c8d0912ecf6f2b2fd1a04130372b0e4ec2b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:23:03 -0500 Subject: [PATCH 06/11] =?UTF-8?q?=E2=9C=A8=20ask:=20hive=20panel=20and=20r?= =?UTF-8?q?ollout=20verification=20for=20optional=20Ask=20AI=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hive dashboard loads the shared Ask panel component from 'self' only when /api/config reports ask_enabled; the section in view or the open Settings tab labels the question from the closed vocabulary, and the docs link follows it. /ask-panel.js and /ask-panel.css on the hive answer 404 while Ask is off. Adds a vocabulary parity test against the dashboard's section registry, a node test of the panel view model, the self-hosted direct-mode guide and a rollout verification checklist. Fixes #19184 Signed-off-by: Andy Anderson --- changelog.d/added-19184-ask-hive-panel.md | 1 + src/docs/api-reference/agents-and-controls.md | 72 +++--- src/docs/api-reference/auth.md | 22 +- src/docs/api-reference/beads.md | 10 +- src/docs/api-reference/configuration.md | 214 +++++++++--------- .../api-reference/cost-tokens-telemetry.md | 18 +- src/docs/api-reference/dashboard-misc.md | 90 ++++---- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/inception.md | 28 +-- src/docs/api-reference/knowledge.md | 92 ++++---- src/docs/api-reference/nous.md | 50 ++-- src/docs/api-reference/packs-and-acmm.md | 36 +-- src/docs/api-reference/snapshots-and-style.md | 8 +- src/docs/ask-ai-help.md | 86 +++++++ src/pkg/askai/sections_parity_test.go | 31 +++ src/pkg/dashboard/api.go | 3 + src/pkg/dashboard/api_ask.go | 20 ++ src/pkg/dashboard/api_ask_panel_test.go | 71 ++++++ src/pkg/dashboard/api_config.go | 3 + src/pkg/dashboard/ask_panel.test.js | 41 ++++ .../dashboard/openapi_route_parity_test.go | 10 + src/pkg/dashboard/static-src/html/topbar.html | 2 + src/pkg/dashboard/static-src/js/ask.js | 61 +++++ .../dashboard/static-src/js/sse-bootstrap.js | 2 + src/pkg/dashboard/static-src/manifest.txt | 1 + src/pkg/dashboard/static/index.html | 65 ++++++ 26 files changed, 729 insertions(+), 330 deletions(-) create mode 100644 changelog.d/added-19184-ask-hive-panel.md create mode 100644 src/pkg/askai/sections_parity_test.go create mode 100644 src/pkg/dashboard/api_ask_panel_test.go create mode 100644 src/pkg/dashboard/ask_panel.test.js create mode 100644 src/pkg/dashboard/static-src/js/ask.js diff --git a/changelog.d/added-19184-ask-hive-panel.md b/changelog.d/added-19184-ask-hive-panel.md new file mode 100644 index 0000000000..19c8268b9f --- /dev/null +++ b/changelog.d/added-19184-ask-hive-panel.md @@ -0,0 +1 @@ +- Hive dashboards show the optional **Ask** panel when Ask AI help is on, reusing the hub's panel: the section in view (or the open Settings tab) labels the question from a fixed list, the docs link follows the section, and with Ask off the page loads nothing for it. The Ask AI help guide covers self-hosted direct mode and a rollout verification checklist ([#19184](https://github.com/hivecommons/hive/issues/19184)). diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index c3f51795fe..fd4a7b297c 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -6,49 +6,49 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:126` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:130` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:129` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:133` | | `GET` | `/api/kick-outcomes` | Dashboard auth/session; detail for owner and read-write | What each kick of an agent came to ([#18916](https://github.com/hivecommons/hive/issues/18916)). Without `?agent=`, every agent's latest kick as `{kind, summary, at}` under `agents`. With `?agent=`, that agent's last ten kicks under `kicks`, newest first, each with `trigger_kind` (`dashboard`, `governor`, `workflow_dispatch`, `other`), `trigger_actor`, `started_at`, `ended_at`, `pr_url`/`pr_number`, `branch`/`sha`, `refusal_code` (a [kick-refusals](../kick-refusals.md) reason) and `quote`; a read-only session gets only the latest one-line summary. `kind` is one of `opened_pr`, `pushed_commit`, `commented`, `stood_down`, `refused`, `still_running`, `ended_no_visible_action`, derived from real signals only. `quote` is untrusted agent text (redacted, capped): escape it. Not reachable by agents. `503` without the store | `pkg/dashboard/api_kick_outcomes.go:49` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:131` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:132` | -| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:133` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:134` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:135` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:136` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:137` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:138` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:139` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:140` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:141` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:145` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:162` | -| `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, Wilson 95% `*_ci` intervals on the rates (omitted when the denominator is 0), a `coverage` block (closed-PR lookback and run-log partiality, as on `/api/contribute/effective-models`), `earliest_pr_created_at`, the top 10 most-reworked PRs, and per-bucket `hive_cost` (`usd`, `launches`, `prs_with_cost`, `usd_per_merged_pr`: the hive's estimated review/fix spend on that model's PRs from the cached `/api/launch-cost` snapshot; `usd` is `null`, not `0`, when nothing was attributed; omitted while the snapshot is not ready) with a top-level `hive_cost_coverage` (`ready`, `window_hours`, `unattributed_usd`, `backend_unsupported_usd`, `disclaimer`). Optional `model=` (matched after `modelfamily.Canonical`, so raw spellings such as `anthropic/claude-opus-5-5` work) adds `prs[]`: every PR in the window in that model's bucket, with the `most_reworked` fields plus `outcome` (`merged` / `closed_unmerged` / `open`), `agent`, `created_at`, `merged_at` and `first_pass`, sorted by review rounds + fix attempts then newest, capped at 200 with `prs_truncated: true` past that. An unknown model returns `prs: []`; without `model` the response is unchanged | `pkg/dashboard/api.go:163` | -| `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:226` | -| `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:510` | -| `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:513` | -| `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:514` | -| `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:518` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:134` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:135` | +| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:136` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:137` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:138` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:139` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:140` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:141` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:142` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:143` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:144` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:148` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:165` | +| `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, Wilson 95% `*_ci` intervals on the rates (omitted when the denominator is 0), a `coverage` block (closed-PR lookback and run-log partiality, as on `/api/contribute/effective-models`), `earliest_pr_created_at`, the top 10 most-reworked PRs, and per-bucket `hive_cost` (`usd`, `launches`, `prs_with_cost`, `usd_per_merged_pr`: the hive's estimated review/fix spend on that model's PRs from the cached `/api/launch-cost` snapshot; `usd` is `null`, not `0`, when nothing was attributed; omitted while the snapshot is not ready) with a top-level `hive_cost_coverage` (`ready`, `window_hours`, `unattributed_usd`, `backend_unsupported_usd`, `disclaimer`). Optional `model=` (matched after `modelfamily.Canonical`, so raw spellings such as `anthropic/claude-opus-5-5` work) adds `prs[]`: every PR in the window in that model's bucket, with the `most_reworked` fields plus `outcome` (`merged` / `closed_unmerged` / `open`), `agent`, `created_at`, `merged_at` and `first_pass`, sorted by review rounds + fix attempts then newest, capped at 200 with `prs_truncated: true` past that. An unknown model returns `prs: []`; without `model` the response is unchanged | `pkg/dashboard/api.go:166` | +| `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:229` | +| `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:513` | +| `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:516` | +| `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:517` | +| `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:521` | | `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:15` | -| `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:522` | -| `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:523` | -| `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:525` | -| `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), `outcomes_by_author_family` and `outcomes_by_author_model` (the same outcome fields keyed by the author's model family and by canonical author model, `human` / `unknown` when no model was recorded; [#18720](https://github.com/hivecommons/hive/issues/18720)), `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:528` | -| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:529` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:311` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:312` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:313` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:314` | +| `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:525` | +| `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:526` | +| `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:528` | +| `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), `outcomes_by_author_family` and `outcomes_by_author_model` (the same outcome fields keyed by the author's model family and by canonical author model, `human` / `unknown` when no model was recorded; [#18720](https://github.com/hivecommons/hive/issues/18720)), `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:531` | +| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:532` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:314` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:315` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:316` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:317` | | `GET` | `/api/agents/discovered` | Dashboard auth/session | Agents declared under `.hive/agents/*.yaml` in allowlisted managed repos, with `status` `pending` / `invalid` / `approved` / `rejected` / `orphaned`; `enabled: false` when discovery is not running ([agent configuration](../agent-configuration.md#agents-declared-in-a-managed-repo-hiveagents)) | `pkg/dashboard/api_repo_agents.go:23` | | `POST` | `/api/agents/discovered/approve` | Owner only | Register a pending discovered agent: body `{id, name?, backend?, model?, mode?}`; sets `definition_source` (marked `discovered`) and, with a sibling `.md`, `prompt_source`; backend, model and mode come from the request, never the file | `pkg/dashboard/api_repo_agents.go:24` | | `POST` | `/api/agents/discovered/reject` | Owner only | Decline a pending discovered agent (body `{id}`); stays declined until the file is removed | `pkg/dashboard/api_repo_agents.go:25` | | `POST` | `/api/agents/discovered/refresh` | Owner only | Rescan every managed repo's `.hive/agents/` now and return the list | `pkg/dashboard/api_repo_agents.go:26` | -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:113` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:117` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:120` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:121` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:122` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:144` | +| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:116` | +| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:120` | +| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:123` | +| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:124` | +| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:125` | +| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:147` | ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 0492562941..0ea4065aa8 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -5,13 +5,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:167` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:168` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:169` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:170` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:171` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:172` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:173` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:170` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:171` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:172` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:173` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:174` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:175` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:176` | | `GET` | `/api/claude-auth/status` | Dashboard auth/session | Claude Auth Status | `pkg/dashboard/claude_auth.go:54` | | `POST` | `/api/claude-auth/start` | Dashboard auth/session | Claude Auth Start | `pkg/dashboard/claude_auth.go:55` | | `POST` | `/api/claude-auth/exchange` | Dashboard auth/session | Claude Auth Exchange | `pkg/dashboard/claude_auth.go:56` | @@ -27,7 +27,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1809` | | `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1810` | | `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1811` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:572` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:573` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:574` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:575` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:575` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:576` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:577` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:578` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index d18b555e02..5caebab49f 100644 --- a/src/docs/api-reference/beads.md +++ b/src/docs/api-reference/beads.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:494` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:495` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:496` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:497` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:498` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:497` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:498` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:499` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:500` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:501` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 4df93e74be..5e88863cae 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -8,130 +8,130 @@ JSON, see [Editing `hive.yaml`](../editing-hive-yaml.md#view-yaml-or-export-effe | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:49` | -| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:50` | -| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:51` | +| `GET` | `/api/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:50` | +| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:51` | +| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:52` | | `GET` | `/api/config/triggers` | Verified owner only | Ordered Event triggers, opaque `version`/ETag, existing agents and managed repository values/labels; applies on next evaluation without restart | `pkg/dashboard/api_event_triggers.go` | | `PUT` | `/api/config/triggers` | Verified owner only | Compile-to-bool and durably compare-and-save `{rules:[{name,agent,expr,priority}],preset?:{index,kind,repo}}`; exact `If-Match` required (428 missing, 412 stale), validation 400, persistence failure 500 leaves live rules unchanged. No enabled field or source/webhook installation | `pkg/dashboard/api_event_triggers.go` | -| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:200` | -| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:201` | -| `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:60` | -| `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:61` | -| `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:52` | -| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:249` | -| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:250` | +| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:203` | +| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:204` | +| `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:61` | +| `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:62` | +| `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:53` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:252` | +| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:253` | | `GET` | `/api/config/export` | Owner only | Redacted JSON export of the effective config, layer files, side files, and provenance | `pkg/dashboard/api_config_export.go` | -| `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:55` | -| `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:56` | -| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:59` | -| `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:62` | -| `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:63` | +| `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:56` | +| `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:57` | +| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:60` | +| `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:63` | +| `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:64` | -| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:182` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:183` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:184` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:185` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:186` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:187` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:188` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:189` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:190` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:191` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:192` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:193` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:194` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:195` | +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:185` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:186` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:187` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:188` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:189` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:190` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:191` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:192` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:193` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:194` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:195` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:196` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:197` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:198` | | `GET` | `/api/config/agent/{name}/variables` | Dashboard auth/session | Per-agent Variables tab: the agent's own `${VAR}` definitions plus the hive-level ones it inherits (each flagged `overridden` when the agent redefines it) and the seed-only exec/http gate flags. Never returns values — only name, type, scope and a non-secret source hint | `pkg/dashboard/api_variables.go:298` | | `PUT` | `/api/config/agent/{name}/variables/{var}` | Owner only | Create or update one per-agent variable (`static`/`env` only; `script`/`http` are 403 and seed-only; scope `template` or `both`; secret-looking static values rejected). Persisted on the agent entry; overrides a same-named hive-level variable in this agent's kick prompt | `pkg/dashboard/api_variables.go:299` | | `DELETE` | `/api/config/agent/{name}/variables/{var}` | Owner only | Delete one per-agent variable (404 for inherited hive-level variables — delete those via `/api/config/variables/{name}`) | `pkg/dashboard/api_variables.go:300` | -| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:196` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:198` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:199` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:201` | | `PATCH` | `/api/config/governor` | Owner only | Update `merge_train_stall_warn_s`; omitted values stay unchanged, 0 disables warnings; returns the effective interval | `pkg/dashboard/api_governor_merge_train.go` | -| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:202` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:203` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:210` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:211` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:216` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:228` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:229` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:230` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:231` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:232` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:205` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:206` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:213` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:214` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:218` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:219` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:231` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:232` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:233` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:234` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:235` | | `GET` | `/api/config/governor/backup` | Owner only | Backup Key Status (presence + safe source label; never the key value) | `pkg/dashboard/backup_key.go` | | `PUT` | `/api/config/governor/backup` | Owner only | Backup Key Set (64-hex AES-256 key; stored 0600, path-only in `hive.yaml`) | `pkg/dashboard/backup_key.go` | | `DELETE` | `/api/config/governor/backup` | Owner only | Backup Key Clear (backups are refused again) | `pkg/dashboard/backup_key.go` | -| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:278` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:279` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:280` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:281` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:282` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:283` | -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:204` | -| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:205` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:282` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:283` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:286` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:287` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:288` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:289` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:290` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:296` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:297` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:298` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:302` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:303` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:306` | +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:207` | +| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:208` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:285` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:286` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:289` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:290` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:291` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:292` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:293` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:299` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:300` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:301` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:305` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:306` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:309` | | `GET` | `/api/config/github/webhooks` | Owner only | Config GitHub Webhooks (payload URL, events, secret source, receiver health, App hook permissions) | `pkg/dashboard/api_github_webhook_setup.go:88` | | `POST` | `/api/config/github/webhooks/secret` | Owner only | Config GitHub Webhooks Generate Secret (returned once) | `pkg/dashboard/api_github_webhook_setup.go:89` | | `POST` | `/api/config/github/webhooks/create` | Owner only | Config GitHub Webhooks Create Hook (through the App installation) | `pkg/dashboard/api_github_webhook_setup.go:90` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:365` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:366` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:367` | -| `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:357` | -| `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:358` | -| `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:359` | -| `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:360` | -| `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:361` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:362` | -| `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:363` | -| `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:536` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:368` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:369` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:370` | +| `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:360` | +| `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:361` | +| `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:362` | +| `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:363` | +| `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:364` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:365` | +| `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:366` | +| `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:539` | -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:207` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:208` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:209` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:212` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:217` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:220` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:221` | -| `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:532` | -| `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:533` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:563` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:564` | -| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:569` | -| `GET` | `/api/config/repos/parent-autoclose` | Owner only | `repos..parent_autoclose` for every monitored repo: the effective value (`true`, `epics_too`, `trackers_too` or `false`), whether the repo carries its own, the default and the four options the Settings editor offers ([#19070](https://github.com/hivecommons/hive/issues/19070)) | `pkg/dashboard/api.go:566` | -| `PUT` | `/api/config/repos/parent-autoclose` | Owner only | Set one monitored repo's parent auto-close policy: `{"repo": "owner/name", "value": "true" \| "epics_too" \| "trackers_too" \| "false"}`. `true` is the default and clears the override. 400 for a missing repo or an invalid value, 404 for a repo that is not monitored, 500 when the file could not be written (previous value restored). Applies without a restart; audited as `config_repo_parent_autoclose`. Parents a person reopened and tracking issues are never auto-closed under any value | `pkg/dashboard/api.go:567` | -| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:578` | -| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:579` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:224` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:227` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:233` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:234` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:235` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:239` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:240` | +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:211` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:212` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:215` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:220` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:223` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:224` | +| `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:535` | +| `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:536` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:566` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:567` | +| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:572` | +| `GET` | `/api/config/repos/parent-autoclose` | Owner only | `repos..parent_autoclose` for every monitored repo: the effective value (`true`, `epics_too`, `trackers_too` or `false`), whether the repo carries its own, the default and the four options the Settings editor offers ([#19070](https://github.com/hivecommons/hive/issues/19070)) | `pkg/dashboard/api.go:569` | +| `PUT` | `/api/config/repos/parent-autoclose` | Owner only | Set one monitored repo's parent auto-close policy: `{"repo": "owner/name", "value": "true" \| "epics_too" \| "trackers_too" \| "false"}`. `true` is the default and clears the override. 400 for a missing repo or an invalid value, 404 for a repo that is not monitored, 500 when the file could not be written (previous value restored). Applies without a restart; audited as `config_repo_parent_autoclose`. Parents a person reopened and tracking issues are never auto-closed under any value | `pkg/dashboard/api.go:570` | +| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:581` | +| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:582` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:227` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:230` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:236` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:237` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:238` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:242` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:243` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | -| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:246` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:248` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:252` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:253` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:254` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:255` | -| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:265` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:266` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:267` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:269` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:284` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:285` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:249` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:251` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:255` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:256` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:257` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:258` | +| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:268` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:270` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:271` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:272` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:287` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:288` | | `PUT` | `/api/workflows/enabled` | Owner only | Turn model-based stage derivation (`workflow.enabled`, [#17620](https://github.com/hivecommons/hive/issues/17620)) on or off from the dashboard, for hosted hives with no `hive.yaml` access. Body `{enabled: bool}`; persists `hive.yaml`; the stage engine and tracker read the live flag so it applies on the next derivation pass without a restart. Turning on also provisions every bound repository's model labels now (`warnings[]` lists repositories that could not be provisioned; the next sweep retries). Returns `{enabled, changed, bindings[], warnings?[]}`. Audited `workflow_enabled` / `workflow_disabled`; `400` on a non-boolean body | `pkg/dashboard/api_workflows.go:29` | | `POST` | `/api/workflows/dispatch` | Owner only | Send a model-owned item to its agent profile: the stage tracker's **Send to *profile*** on a row whose bound model hands its current state to a profile ([cncf/techdocs#395](https://github.com/cncf/techdocs/issues/395): Accepted → `techdocs-drafter`, Drafting → `techdocs-verifier`). Body `{repo, number}`. Reads the item fresh, resolves the agent (`workflow.dispatch.profiles..agent`, then the default order ending at the hive's issue worker or reviewer, at every step only an agent whose mode lets it do what the profile needs, [#18749](https://github.com/hivecommons/hive/issues/18749); a profile disabled for automatic dispatch still resolves), takes the agent claim on an issue first, kicks the agent, and records the hand-off as pending once the kick lands so the automatic pass does not repeat it; a later pass marks it not started if the agent declines or ends its turn without the deliverable. Returns `{status: "sent", ref, model, state, profile, agent, result}`. Audited `workflow_dispatch`; `404` when the model does not hand the state to a profile, `409` when no agent fills it (the message gives the reason, for example that no agent on the hive may open pull requests in the repository, and names the Settings → Repos picker), someone else holds the claim, or the agent is busy | `pkg/dashboard/api_workflows.go:30` | | `PUT` | `/api/workflows/dispatch/profiles` | Owner only | Pick the hive agent a bound model's profile is handed to ([#18690](https://github.com/hivecommons/hive/issues/18690)): the agent picker on a repository's workflow row in Settings → Repos. Body `{profile, agent}`; an empty `agent` clears the pin so the profile resolves by default again. Persists `workflow.dispatch.profiles..agent` in `hive.yaml` (the profile's `prompt_template` and `disabled` are kept); the next scheduler pass reads the live config, so no restart is needed. `agent` must be an enabled agent that is not a replica (`400` otherwise). Returns `{changed, profile, agent, dispatch, agents}`, where `dispatch` lists every bound repository's profiles as `{repo, profile, agent, source, mode, needs, pinned, disabled, problem, states, candidates, not_started}` (`problem` is why nothing fills the profile, including a pin to an agent whose mode does not let it do the profile's work; `candidates` lists each pinnable agent as `{agent, mode, qualifies, reason}`; `not_started` lists the hand-offs an agent declined or did not act on while their item still waits, as `{ref, repo, number, profile, state, agent, reason, at, attempts, retrying, next, reason_at, reason_age, reason_session, stale}` (`reason_at`, `reason_age` and `reason_session` say when and in which hand-off session the reason was decided, and `stale` is true once a newer hand-off of the item exists, so the reason is history and not the item's state now, [#18916](https://github.com/hivecommons/hive/issues/18916)), [#18749](https://github.com/hivecommons/hive/issues/18749)) and `agents` the agents that can be picked; `GET /api/workflows` and `PUT /api/workflows/bindings` carry the same two fields. Audited `workflow_dispatch_agent` | `pkg/dashboard/api_workflows.go:31` | diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index 900a83be70..ed647695be 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -5,16 +5,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:93` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:148` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:149` | -| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485); every `estimated.by_model[]` row carries `canonical_model` (`modelfamily.Canonical` of its `name`, the id PRs-by-model and run stats group by), while spend stays one row per raw model because prices are per raw model (#18718) | `pkg/dashboard/api.go:150` | +| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:96` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:151` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:152` | +| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485); every `estimated.by_model[]` row carries `canonical_model` (`modelfamily.Canonical` of its `name`, the id PRs-by-model and run stats group by), while spend stays one row per raw model because prices are per raw model (#18718) | `pkg/dashboard/api.go:153` | | `GET` | `/api/repo-activity` | Dashboard auth/session | Per-repo audited activity | `pkg/dashboard/api.go` | | `GET` | `/api/repo-cost` | Dashboard auth/session | Per-repo estimated token cost (interval join, cached) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost` | Dashboard auth/session | Per-issue / PR / head-SHA estimated token cost from kick launch attribution (cached; `?ref=owner/repo#N` narrows) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost/history` | Dashboard auth/session | Daily per-ref rollup of launch attribution (`daily_rollup[]`: `day`, `by_ref[]` with `ref`, `kind`, `launches`, `share_usd`), kept ~2 years on the `/data` PVC so cost per PR can be measured past the `/api/launch-cost` window | `pkg/dashboard/api.go` | -| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:156` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:159` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:161` | -| `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, and `plan_type` when a provider reports one), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:65` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:158` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:159` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:162` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:164` | +| `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, and `plan_type` when a provider reports one), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:66` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:161` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 000615ad07..9dcd0b8579 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -53,53 +53,55 @@ review are settled. | 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:64` | -| `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:505` | -| `GET` | `/api/ask/status` | Dashboard auth/session | Ask AI help status for the signed-in person (`enabled`, `text_version`, `disclosure`, `consented`, `docs_url`, `ai_label`); `404` unless `ask.enabled` is on and configured. See [Ask AI help](../ask-ai-help.md) | `pkg/dashboard/api.go:82` | -| `PUT` | `/api/ask/consent` | Dashboard auth/session | Confirm the Ask disclosure (`{text_version}`); `409` on an older text; `204` | `pkg/dashboard/api.go:83` | -| `DELETE` | `/api/ask/consent` | Dashboard auth/session | Withdraw Ask consent; `204` | `pkg/dashboard/api.go:84` | -| `POST` | `/api/ask` | Dashboard auth/session | Ask a docs-help question (`{question, section?, conversation?}`); always `200` with an `outcome`; direct mode calls Kapa.ai, hub mode the hub relay | `pkg/dashboard/api.go:85` | -| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:67` | -| `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:70` | -| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:68` | -| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:69` | -| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:74` | -| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:75` | -| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:76` | -| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:92` | -| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:94` | -| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:95` | -| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:96` | - - -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:251` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:457` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:460` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:461` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:463` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:464` | +| `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:65` | +| `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:508` | +| `GET` | `/api/ask/status` | Dashboard auth/session | Ask AI help status for the signed-in person (`enabled`, `text_version`, `disclosure`, `consented`, `docs_url`, `ai_label`); `404` unless `ask.enabled` is on and configured. See [Ask AI help](../ask-ai-help.md) | `pkg/dashboard/api.go:83` | +| `PUT` | `/api/ask/consent` | Dashboard auth/session | Confirm the Ask disclosure (`{text_version}`); `409` on an older text; `204` | `pkg/dashboard/api.go:84` | +| `DELETE` | `/api/ask/consent` | Dashboard auth/session | Withdraw Ask consent; `204` | `pkg/dashboard/api.go:85` | +| `POST` | `/api/ask` | Dashboard auth/session | Ask a docs-help question (`{question, section?, conversation?}`); always `200` with an `outcome`; direct mode calls Kapa.ai, hub mode the hub relay | `pkg/dashboard/api.go:86` | +| `GET` | `/ask-panel.js` | Dashboard auth/session | Ask AI help panel script, the shared component in `pkg/askai/web`; `404` while Ask is off | `pkg/dashboard/api.go:87` | +| `GET` | `/ask-panel.css` | Dashboard auth/session | Ask AI help panel stylesheet; `404` while Ask is off | `pkg/dashboard/api.go:88` | +| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:68` | +| `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:71` | +| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:69` | +| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:70` | +| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:75` | +| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:76` | +| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:77` | +| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:95` | +| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:97` | +| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:98` | +| `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:99` | + + +| `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:460` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:463` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:464` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:466` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:467` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:215` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:216` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:217` | -| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:294` | -| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:295` | - -| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:543` | -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:105` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:110` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:124` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:146` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:164` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:165` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:177` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_why` `{source: filed-for-help|decision-pending|level-gate|hive-hold|needs-approval|triage|author|needs-human, reason}` on every row a person must move (with `needs_human: true`; `filed_for_help` names the agent whose marker is in an unclaimed issue's body); `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:178` | -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:179` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:180` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:370` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:434` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:435` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:466` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:500` | +| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:297` | +| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:298` | + +| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:546` | +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:108` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:113` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:127` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:149` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:167` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:168` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:180` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_why` `{source: filed-for-help|decision-pending|level-gate|hive-hold|needs-approval|triage|author|needs-human, reason}` on every row a person must move (with `needs_human: true`; `filed_for_help` names the agent whose marker is in an unclaimed issue's body); `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:181` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:182` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:183` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:373` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:437` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:438` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:469` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:503` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:351` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:352` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:353` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 1080e9b257..169788cd47 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -21,10 +21,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:46` | -| `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:47` | +| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:47` | +| `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:48` | | `GET` | `/api/version/contains` | Dashboard auth/session | Does the running build contain a PR or commit ([#18915](https://github.com/hivecommons/hive/issues/18915)): `?q=` returns `{query, commit?, running?, channel?, contains, reason?}`. `contains` is `yes`, `no` or `unknown`, computed from the commit this hive reports running (`hash` on `/api/version`) and repository ancestry; `unknown` (with `reason`) when the commit cannot be resolved, the lookup failed or the hive has no GitHub access, never a guess. An unmerged PR is `no`. `400` when `q` is neither a PR number nor a SHA | `pkg/dashboard/api_version_contains.go:113` | -| `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:71` | +| `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:72` | | `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1789` | | `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1790` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1791` | @@ -45,11 +45,11 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/swarm/themes` | Owner only | Set a per-repo swarm theme (`event_name`, `call_to_arms`, `leaderboard_title`). | `pkg/dashboard/swarm.go:316` | | `PATCH` | `/api/swarm/objectives` | Owner only | Update the active swarm SDLC objective checklist completion state. | `pkg/dashboard/swarm.go:317` | | `GET` | `/api/leaderboard/swarm` | Public | Stable public JSON record of swarm history, leaderboard, top players, and achievements. | `pkg/dashboard/swarm.go:318` | -| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:97` | -| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:98` | -| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:99` | -| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:101` | -| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:102` | -| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:103` | -| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:104` | -| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:100` | +| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:100` | +| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:101` | +| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:102` | +| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:104` | +| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:105` | +| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:106` | +| `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:107` | +| `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:103` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 1df4a164d7..b7709e832a 100644 --- a/src/docs/api-reference/inception.md +++ b/src/docs/api-reference/inception.md @@ -7,17 +7,17 @@ The inception API was retired in favour of [Inception (spek) sessions](sessions. | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Dashboard auth/session | Retired (was: Inception Start): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:439` | -| `POST` | `/api/inception/scan` | Dashboard auth/session | Retired (was: Inception Scan): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:440` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Retired (was: Inception State): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:441` | -| `POST` | `/api/inception/questions` | Dashboard auth/session | Retired (was: Inception Set Questions): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:442` | -| `POST` | `/api/inception/answer` | Dashboard auth/session | Retired (was: Inception Answer): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:443` | -| `POST` | `/api/inception/facts` | Dashboard auth/session | Retired (was: Inception Record Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:444` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Retired (was: Inception Scaffold): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:445` | -| `POST` | `/api/inception/approve` | Dashboard auth/session | Retired (was: Inception Approve): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:446` | -| `POST` | `/api/inception/reset` | Dashboard auth/session | Retired (was: Inception Reset): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:447` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Retired (was: Inception Ideation Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:448` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Retired (was: Inception Download): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:449` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Retired (was: Inception Has Files): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:450` | -| `PUT` | `/api/inception/wiki-name` | Dashboard auth/session | Retired (was: Inception Rename Wiki): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:451` | -| `POST` | `/api/inception/import` | Dashboard auth/session | Retired (was: Inception Import): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:452` | +| `POST` | `/api/inception/start` | Dashboard auth/session | Retired (was: Inception Start): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:442` | +| `POST` | `/api/inception/scan` | Dashboard auth/session | Retired (was: Inception Scan): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:443` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Retired (was: Inception State): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:444` | +| `POST` | `/api/inception/questions` | Dashboard auth/session | Retired (was: Inception Set Questions): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:445` | +| `POST` | `/api/inception/answer` | Dashboard auth/session | Retired (was: Inception Answer): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:446` | +| `POST` | `/api/inception/facts` | Dashboard auth/session | Retired (was: Inception Record Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:447` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Retired (was: Inception Scaffold): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:448` | +| `POST` | `/api/inception/approve` | Dashboard auth/session | Retired (was: Inception Approve): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:449` | +| `POST` | `/api/inception/reset` | Dashboard auth/session | Retired (was: Inception Reset): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:450` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Retired (was: Inception Ideation Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:451` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Retired (was: Inception Download): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:452` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Retired (was: Inception Has Files): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:453` | +| `PUT` | `/api/inception/wiki-name` | Dashboard auth/session | Retired (was: Inception Rename Wiki): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:454` | +| `POST` | `/api/inception/import` | Dashboard auth/session | Retired (was: Inception Import): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:455` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index e2c797074e..f3c9d9f169 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -5,39 +5,39 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:372` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:373` | -| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | 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:383` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:374` | -| `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:375` | -| `GET` | `/api/knowledge/advisor/summary` | Dashboard auth/session (read or higher) | Read-only knowledge-advisor rank-versus-holdout summary: `window` (`since`, `first_decision`, `last_decision`, `rank_mode_start`, `decisions`), `settings` (`enabled`, `mode`, `model`, `holdout_percent`, `max_calls_per_day`, `max_calls_per_agent_hour`, `candidates`, `on_error`; never the endpoint or key), `counts` (`by_mode`, `by_arm`, `by_outcome`), `arms` (per-arm closed-bead `beads` and mean fix attempts, CI failures and kicks from `Lane.AdvisorArmSummary()`) with `mixed` and `none` listed separately, `cost` (mean latency and tokens where records carry them), and a `small_n`/`caveat` pair. Counts and means only: no slugs, refs, agents or content. Query: `since` (RFC 3339) narrows the decision counts and cost, not the bead means ([docs](../retro-lane.md#reading-the-comparison-from-the-dashboard)) | `pkg/dashboard/api.go:376` | -| `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:377` | -| `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:378` | -| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:380` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:384` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:385` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:386` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:387` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:388` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:389` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:390` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:391` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:397` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:398` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:399` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:400` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:401` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:402` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:403` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:404` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:405` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:406` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:407` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:408` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:409` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:410` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:411` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:412` | +| `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:375` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:376` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | 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:386` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:377` | +| `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:378` | +| `GET` | `/api/knowledge/advisor/summary` | Dashboard auth/session (read or higher) | Read-only knowledge-advisor rank-versus-holdout summary: `window` (`since`, `first_decision`, `last_decision`, `rank_mode_start`, `decisions`), `settings` (`enabled`, `mode`, `model`, `holdout_percent`, `max_calls_per_day`, `max_calls_per_agent_hour`, `candidates`, `on_error`; never the endpoint or key), `counts` (`by_mode`, `by_arm`, `by_outcome`), `arms` (per-arm closed-bead `beads` and mean fix attempts, CI failures and kicks from `Lane.AdvisorArmSummary()`) with `mixed` and `none` listed separately, `cost` (mean latency and tokens where records carry them), and a `small_n`/`caveat` pair. Counts and means only: no slugs, refs, agents or content. Query: `since` (RFC 3339) narrows the decision counts and cost, not the bead means ([docs](../retro-lane.md#reading-the-comparison-from-the-dashboard)) | `pkg/dashboard/api.go:379` | +| `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:380` | +| `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:381` | +| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:383` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:387` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:388` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:389` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:390` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:391` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:392` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:393` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:394` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:400` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:401` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:402` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:403` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:404` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:405` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:406` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:407` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:408` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:409` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:410` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:411` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:412` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:413` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:415` | | `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, `running` and the live `progress` block (phase, items_done/items_total, current item, started_at; see [knowledge-connectors.md](../knowledge-connectors.md#api)), plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -47,19 +47,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/knowledge/agent-scopes` | Owner only | Replace `knowledge.agent_scopes` after validating layer and state names; persisted and audited as `config_knowledge_agent_scopes` | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/pipeline` | Owner only | Scalar bead synthesizer, curator, code map and primer settings and `knowledge.sidecar_advise`, plus the read-only engine, advisor flag, 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 and `sidecar_advise` apply 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:422` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:423` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:424` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:425` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:426` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:427` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:428` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:429` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:430` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:431` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:432` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:395` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:396` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:425` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:426` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:427` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:428` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:429` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:430` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:431` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:432` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:433` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:434` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:435` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:398` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:399` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses, each with a live `progress` block while a sync runs, and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](../knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:25` | | `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:26` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index d34a557ab8..70dc9a23f0 100644 --- a/src/docs/api-reference/nous.md +++ b/src/docs/api-reference/nous.md @@ -5,28 +5,28 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:468` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:469` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:470` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:471` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:472` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:473` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:474` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:475` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:476` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:477` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:478` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:479` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:480` | -| `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:481` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:482` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:483` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:484` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:485` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:486` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:487` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:488` | -| `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:489` | -| `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:490` | -| `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:491` | -| `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:492` | +| `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:471` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:472` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:473` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:474` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:475` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:477` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:478` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:479` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:480` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:481` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:482` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:483` | +| `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:484` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:485` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:486` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:487` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:488` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:489` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:490` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:491` | +| `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:492` | +| `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:493` | +| `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:494` | +| `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:495` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 8ac80e73f0..60c9407487 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -5,30 +5,30 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:316` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:317` | -| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:318` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:319` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:320` | +| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:321` | | `POST` | `/api/repos/rescan` | Dashboard auth/session | Re-enumerate watched repositories' open issues/PRs for the dashboard Projects cards. The scan is read-only with respect to agents/governor actions, collapses concurrent requests, and debounces repeated presses for 30 seconds (`repoRescanDebounce`) so the button cannot hammer GitHub | `pkg/dashboard/api.go`, `pkg/dashboard/api_repos_rescan.go` | | `POST` | `/api/repos/pause` | Owner | Quiet ONE repository without stopping the hive: agents stop writing to it and stop being handed work on it, while it keeps its dashboard card and ACMM eval. Body `{"repo": "...", "reason": "..."}` — the repo travels in the body because a `project.repos` entry may be an explicit cross-org `owner/name`. Records who/when/why; `changed: false` marks a no-op re-pause and leaves the original provenance intact; `persisted: false` means the pause is in force but could not be written to config. Rejects a repo outside `project.repos`. See [per-repo agent pause](../repo-pause.md) | `pkg/dashboard/api_repo_pause.go` | | `POST` | `/api/repos/resume` | Owner | Lift a repository's pause. Unlike pause, does not require the repo to be in `project.repos`, so a pause left behind by a removed repo can still be cleared | `pkg/dashboard/api_repo_pause.go` | | `GET` | `/api/repos/pauses` | Dashboard auth/session | Every repo pause with its provenance. Read-only — the same state is already on the repository cards | `pkg/dashboard/api_repo_pause.go` | -| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_hold.go` | +| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:336`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. 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:337`, `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"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:339`, `pkg/dashboard/api_repo_item_decision.go` | -| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_maintainer_notes.go` | -| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:344`, `pkg/dashboard/api_maintainer_notes.go` | -| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_maintainer_notes.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 (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. 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:340`, `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"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:342`, `pkg/dashboard/api_repo_item_decision.go` | +| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:346`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:347`, `pkg/dashboard/api_maintainer_notes.go` | +| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:348`, `pkg/dashboard/api_maintainer_notes.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085), and never decides a PR whose CI is running or whose review is incomplete on the current head — it answers `no-effect` (rule `mid-flight`, nothing written; fails closed, "review state not yet loaded", when the PR's review state cannot be read from the tracker; per PR in the `prs` fan-out, where the PR is skipped and counted as such), and the policy itself never releases (`default-release`, `small-low-risk`) a head whose checks are pending (rule `ci-pending`). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:348`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:349` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:350` | -| `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:561`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:351`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:352` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:353` | +| `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:564`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sha-waiver` | Owner or repo write/maintain/admin | Waive or restore the SHA-hold requirement on an issue from the activity monitor's row menu. Body `{"waived": true\|false}`. Waiving adds the persistent `sha-waived` label (created if missing), removes `needs-sha` at once and posts one App-authored comment with a `` marker; restoring removes `sha-waived`. A repeat is a no-op; pull requests are 404. Returns `{ok, repo, number, waived, added, removed, minStatusSeq, result}`. Audited as `repo_item_sha_waiver`. | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:340`, `pkg/dashboard/api_repo_item_sentinel_confirm.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:352`, `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:353` | -| `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:354` | -| `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:356`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_repo_item_sentinel_confirm.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:355`, `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:356` | +| `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:357` | +| `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:359`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index b46cd31db8..a75b0b0f6f 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:48` | +| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:49` | | `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1879` | -| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:89` | -| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:90` | -| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:91` | +| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:92` | +| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:93` | +| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:94` | diff --git a/src/docs/ask-ai-help.md b/src/docs/ask-ai-help.md index 6b88f0790d..7c8e0f067d 100644 --- a/src/docs/ask-ai-help.md +++ b/src/docs/ask-ai-help.md @@ -62,6 +62,54 @@ direct mode with its own key, or stays off. 3. If the hive is not hosted, or has no hub link, Settings says why Ask stays off. +## Turning it on for a self-hosted hive + +A self-hosted hive (no hub, or registered with a hub, which the relay does not +serve in this round) calls Kapa.ai itself with its own key: + +1. In the Kapa project, create an HTTP API integration and an API key. +2. Put the key in a file under `/secrets` or `/data/secrets`, from a Secret + (Kubernetes) or a read-only bind mount (Docker Compose, Podman). For + Kubernetes: + + ```sh + kubectl -n create secret generic hive-ask-kapa \ + --from-file=api-key= + ``` + + and mount it at `/secrets/kapa` in the hive container. +3. Set in `hive.yaml` (or the matching `HIVE_ASK_*` env): + + ```yaml + ask: + enabled: true + mode: direct + kapa: + project_id: + integration_id: + api_key_file: /secrets/kapa/api-key + ``` + + The project id and integration id are configuration, never committed to a + repository; the config export redacts them. +4. Settings, Features shows **Ask AI help** on, or the reason it stays off. + +The hive applies the same limits as the hub to its own traffic; a busy shared +vendor quota shows "Busy, try again in N seconds" and the docs link. + +## Using the panel + +With Ask on, the dashboard header shows an **Ask** button. It opens a panel +docked to the side (a bottom sheet on a phone). The first time, it shows the +notice and **I understand, continue**; after that the person types a question +(Enter sends, Shift+Enter adds a line) and gets a plain-text answer with a +**Sources** list and the "AI generated, may be wrong" label. The label of the +section in view, or of the open Settings tab, goes with the question. Every +state has a docs link for the section in view. Escape closes the panel and +returns focus to the button; answers and errors are announced to screen +readers. With Ask off the button is not shown and the page loads nothing for +it. + ## Configuration keys | Key | Env | Default | Meaning | @@ -96,3 +144,41 @@ Hive dashboard: `GET /api/ask/status`, `PUT` and `DELETE /api/ask/consent`, `POST /api/ask` (see `dashboard/openapi.json`); every route answers `404` while Ask is off. Hub: the same routes plus `GET /api/ask/stats` and the relay, in the [hub API reference](api-reference/hub-saas.md). + +## Verifying a rollout + +Run these after the Kapa key exists and Ask is switched on, first on the hub, +then on one hosted hive, then on one self-hosted hive. Use a test account that +has consented; nothing here needs a production change beyond the switch. + +1. **Hub, off first.** With `HIVE_ASK_ENABLED` unset, `GET /api/ask/status` and + `GET /ask-panel.js` on the hub answer `404`, the dashboard has no **Ask** + button, and `kubectl logs` for the hub shows no `ask:` line. +2. **Hub, on.** Set the env and the Secret ([hub + steps](hub-deployment.md#ask-ai-help)), restart, and check the log for + `ask: enabled` (and no `ask: requested but staying off`). Open My Hives, click + **Ask**, confirm the notice, and ask "Where do I add a hosted hive?". Expect an + answer with at least one source on `docs.hivecommons.dev` and the AI label. +3. **Refusal.** Ask a question containing a fake token such as + `ghp_` followed by 30 letters. Expect "This looks like it contains a password, + token or key" and, in the Kapa analytics, no new question. +4. **Withdraw.** Click **Stop sending my questions**, ask again, and expect the + notice instead of an answer. +5. **Hosted hive.** On a hosted hive, Settings, Features: turn on **Ask AI help** + and set **Ask mode** to `hub`. Open **Ask**, confirm, and ask "Where do I pause + an agent?". Expect an answer linking to the dashboard sections or agents + docs. The hub log shows `audit: ask request` with `hive=`; the hive + log shows `audit: ask request` with `relay=true`. Neither line carries the + question. +6. **Self-hosted hive.** Configure direct mode as above, restart, and ask the + same question. The hive log shows `ask: enabled mode=direct`. +7. **Fallback.** On the self-hosted hive point `ask.kapa.api_key_file` at an + empty file and restart: Settings shows why Ask stays off and the button is + gone. Restore it. +8. **Off again.** Turn Ask off on the hosted hive and on the hub. The button + disappears on the next reload, the routes answer `404`, and the hub's + `GET /api/ask/stats` (while on) showed the counts by outcome for the test. +9. **What left.** In Kapa analytics, the test questions appear with the section + label prefix (`Dashboard section: ...`) and nothing else: no login, URL or + hive name. + diff --git a/src/pkg/askai/sections_parity_test.go b/src/pkg/askai/sections_parity_test.go new file mode 100644 index 0000000000..23bf6f4e4b --- /dev/null +++ b/src/pkg/askai/sections_parity_test.go @@ -0,0 +1,31 @@ +package askai + +import ( + "os" + "regexp" + "testing" +) + +// TestSectionVocabularyCoversTheHiveDashboard keeps the closed vocabulary in +// step with the hive dashboard's own section registry: every section that has +// a "?" help mark can be named in a question, and nothing else can. +func TestSectionVocabularyCoversTheHiveDashboard(t *testing.T) { + data, err := os.ReadFile("../dashboard/static-src/js/sections.js") + if err != nil { + t.Fatal(err) + } + ids := regexp.MustCompile(`'([a-z0-9-]+-section)': \{ heading: '([^']*)'`).FindAllStringSubmatch(string(data), -1) + if len(ids) == 0 { + t.Fatal("no DASHBOARD_SECTION_HELP entries found") + } + for _, m := range ids { + label, ok := SectionLabel(m[1]) + if !ok { + t.Errorf("dashboard section %q is missing from the Ask vocabulary", m[1]) + continue + } + if label != m[2] { + t.Errorf("section %q label %q, dashboard heading %q", m[1], label, m[2]) + } + } +} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 53b360dd9e..cc5fb8327e 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -17,6 +17,7 @@ import ( "time" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/askai" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/github" spoke "github.com/hivecommons/hive/pkg/hub/spoke" @@ -83,6 +84,8 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("PUT /api/ask/consent", s.handleAskConsent) s.mux.HandleFunc("DELETE /api/ask/consent", s.handleAskConsent) s.mux.HandleFunc("POST /api/ask", s.handleAsk) + s.mux.HandleFunc("GET /ask-panel.js", s.handleAskPanelAsset("text/javascript; charset=utf-8", askai.PanelJS)) + s.mux.HandleFunc("GET /ask-panel.css", s.handleAskPanelAsset("text/css; charset=utf-8", askai.PanelCSS)) s.mux.HandleFunc("GET /api/feedback/status", s.handleFeedbackStatus) s.mux.HandleFunc("POST /api/feedback/report", s.handleFeedbackReport) s.mux.HandleFunc("GET /api/feedback/mine", s.handleFeedbackMine) diff --git a/src/pkg/dashboard/api_ask.go b/src/pkg/dashboard/api_ask.go index 4758c513fc..c03b43ea53 100644 --- a/src/pkg/dashboard/api_ask.go +++ b/src/pkg/dashboard/api_ask.go @@ -74,6 +74,26 @@ func askEffective(cfg *config.Config) (config.AskSettings, string) { return st, "" } +// askOn reports whether Ask is on and fully configured for cfg. +func askOn(cfg *config.Config) bool { + st, problem := askEffective(cfg) + return st.Enabled && problem == "" +} + +// handleAskPanelAsset serves the shared panel component (#19184) from 'self' +// only while Ask is on; otherwise 404, like every other Ask route. +func (s *Server) handleAskPanelAsset(contentType string, data []byte) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !askOn(s.askConfig()) { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", contentType) + w.Header().Set("Cache-Control", "no-cache") + _, _ = w.Write(data) + } +} + func (s *Server) askConfig() *config.Config { if s.deps == nil { return nil diff --git a/src/pkg/dashboard/api_ask_panel_test.go b/src/pkg/dashboard/api_ask_panel_test.go new file mode 100644 index 0000000000..7f45fb5051 --- /dev/null +++ b/src/pkg/dashboard/api_ask_panel_test.go @@ -0,0 +1,71 @@ +package dashboard + +import ( + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/askai" + "github.com/hivecommons/hive/pkg/config" +) + +// TestHiveAskPanelAssetsOnlyWhenOn: the panel component is served from +// 'self' only while ask is on, and /api/config tells the page whether to load +// it at all. +func TestHiveAskPanelAssetsOnlyWhenOn(t *testing.T) { + get := func(s *Server, path string, data []byte, ct string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + s.handleAskPanelAsset(ct, data)(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec + } + off, _ := askTestServer(t, config.AskConfig{}, config.HubConfig{}, "") + if rec := get(off, "/ask-panel.js", askai.PanelJS, "text/javascript"); rec.Code != http.StatusNotFound || askOn(off.deps.Config) { + t.Fatalf("off: %d", rec.Code) + } + on, _ := askTestServer(t, askDirect, config.HubConfig{}, "") + js := get(on, "/ask-panel.js", askai.PanelJS, "text/javascript; charset=utf-8") + css := get(on, "/ask-panel.css", askai.PanelCSS, "text/css; charset=utf-8") + if js.Code != http.StatusOK || !strings.Contains(js.Body.String(), "HiveAsk") || !strings.HasPrefix(js.Header().Get("Content-Type"), "text/javascript") { + t.Fatalf("js %d", js.Code) + } + if css.Code != http.StatusOK || !strings.Contains(css.Body.String(), ".hive-ask-panel") || !askOn(on.deps.Config) { + t.Fatalf("css %d", css.Code) + } + src, err := os.ReadFile("api_config.go") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(src), `"ask_enabled": askOn(cfg)`) { + t.Fatal("/api/config must report ask_enabled from the effective settings") + } +} + +// TestHiveAskPanelLoaderIsGatedAndSameOrigin pins the page side: one opener +// slot, the loader only runs on cfg.ask_enabled === true, it loads the +// component from this origin, and it adds no third-party host. +func TestHiveAskPanelLoaderIsGatedAndSameOrigin(t *testing.T) { + loader, err := os.ReadFile("static-src/js/ask.js") + if err != nil { + t.Fatal(err) + } + js := string(loader) + for _, want := range []string{"cfg.ask_enabled !== true", "'/ask-panel.js'", "'/ask-panel.css'", "window.HiveAsk.mount(", "DASHBOARD_SECTION_HELP", "dashboardDocsHref("} { + if !strings.Contains(js, want) { + t.Errorf("loader lacks %q", want) + } + } + for _, banned := range []string{"http://", "https://", "kapa", "innerHTML"} { + if strings.Contains(js, banned) { + t.Errorf("loader carries %q", banned) + } + } + index, err := os.ReadFile("static/index.html") + if err != nil { + t.Fatal(err) + } + if strings.Count(string(index), `id="hive-ask-slot"`) != 1 || !strings.Contains(string(index), "loadAskPanel(cfg)") { + t.Fatal("the dashboard must hold one Ask slot and call the gated loader from the config bootstrap") + } +} diff --git a/src/pkg/dashboard/api_config.go b/src/pkg/dashboard/api_config.go index 2c90f31b98..a12b38d254 100644 --- a/src/pkg/dashboard/api_config.go +++ b/src/pkg/dashboard/api_config.go @@ -51,6 +51,9 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { "dashboard_issue_bands": cfg.Dashboard.IssueBands, "writing_guide": cfg.Project.WritingGuide, "my_hives_url": myHivesURL(cfg), // hub My Hives page for the user menu (#9696); "" when standalone + // ask_enabled tells the page to load the Ask AI help panel (#19184). + // With Ask off the page loads nothing and asks nothing. + "ask_enabled": askOn(cfg), } // The active project.issue_filter, read-only: which issues agents may // initiate work on, by label. Omitted entirely when no filter is diff --git a/src/pkg/dashboard/ask_panel.test.js b/src/pkg/dashboard/ask_panel.test.js new file mode 100644 index 0000000000..293b3c50c6 --- /dev/null +++ b/src/pkg/dashboard/ask_panel.test.js @@ -0,0 +1,41 @@ +// Ask AI help panel view model (#19184). The shared component in +// pkg/askai/web renders only what askViewModel returns, with textContent, so +// this pins what reaches the page: answers need an https source, everything +// else becomes a notice with the docs link. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); + +const { askViewModel } = require(path.join(__dirname, '..', 'askai', 'web', 'ask-panel.js')); + +test('an answer keeps only https sources and names their host', () => { + const v = askViewModel({ + outcome: 'ok', answer: 'Open Settings.', uncertain: true, conversation: 'h1', docs_url: 'https://docs.hivecommons.dev/', + sources: [{ title: 'Settings', url: 'https://docs.hivecommons.dev/settings/' }, { title: 'x', url: 'javascript:alert(1)' }, { url: 'http://insecure.example/' }], + }); + assert.equal(v.kind, 'answer'); + assert.equal(v.text, 'Open Settings.'); + assert.equal(v.uncertain, true); + assert.equal(v.conversation, 'h1'); + assert.deepEqual(v.sources, [{ label: 'Settings', host: 'docs.hivecommons.dev', href: 'https://docs.hivecommons.dev/settings/' }]); +}); + +test('an answer with no usable source is shown as no cited answer', () => { + const v = askViewModel({ outcome: 'ok', answer: 'Trust me.', sources: [{ url: 'ftp://x' }] }); + assert.equal(v.kind, 'notice'); + assert.match(v.text, /No cited answer/); + assert.equal(v.uncertain, false); + assert.deepEqual(v.sources, []); +}); + +test('every other outcome is a notice carrying the backend message', () => { + for (const outcome of ['rate_limited', 'breaker_open', 'upstream_error', 'refused_secret_shape', 'not_consented', 'relay_disabled']) { + const v = askViewModel({ outcome, message: 'msg ' + outcome, retry_after_seconds: 7, answer: 'ignored' }); + assert.equal(v.kind, 'notice'); + assert.equal(v.text, 'msg ' + outcome); + assert.deepEqual(v.sources, []); + } + assert.equal(askViewModel({ outcome: 'rate_limited', retry_after_seconds: 7 }).retryAfter, 7); + assert.equal(askViewModel(null).kind, 'notice'); + assert.match(askViewModel(undefined).text, /unavailable/); +}); diff --git a/src/pkg/dashboard/openapi_route_parity_test.go b/src/pkg/dashboard/openapi_route_parity_test.go index 252c127dc8..c6a6ac23e8 100644 --- a/src/pkg/dashboard/openapi_route_parity_test.go +++ b/src/pkg/dashboard/openapi_route_parity_test.go @@ -45,6 +45,16 @@ type routeParityException struct { // not listed here must appear in the spec (with a matching method) or the // test fails. var routeParityExceptions = []routeParityException{ + { + method: "GET", path: "/ask-panel.js", + reason: "Ask AI help panel script (#19184): a static same-origin asset " + + "served only while ask is on, not a JSON data operation.", + }, + { + method: "GET", path: "/ask-panel.css", + reason: "Ask AI help panel stylesheet (#19184): a static same-origin " + + "asset served only while ask is on, not a JSON data operation.", + }, { method: "GET", path: "/api/health", reason: "Kubernetes readiness probe. Returns a bare {\"status\":...} " + diff --git a/src/pkg/dashboard/static-src/html/topbar.html b/src/pkg/dashboard/static-src/html/topbar.html index 934f45b8ed..76d4cc5e4a 100644 --- a/src/pkg/dashboard/static-src/html/topbar.html +++ b/src/pkg/dashboard/static-src/html/topbar.html @@ -23,6 +23,8 @@
+ + diff --git a/src/pkg/dashboard/static-src/js/ask.js b/src/pkg/dashboard/static-src/js/ask.js new file mode 100644 index 0000000000..4b721b7949 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/ask.js @@ -0,0 +1,61 @@ + // ── Ask AI help (#19184) ───────────────────────────────────────── + // Loads the shared panel component (pkg/askai/web, served from 'self' + // at /ask-panel.js) only when /api/config says ask is on. With ask off + // the page adds nothing and requests nothing. The panel sends only the + // question and an id from the closed section vocabulary to this hive's + // own /api/ask; the backend decides what, if anything, leaves. + const ASK_PANEL_SCRIPT = '/ask-panel.js'; + const ASK_PANEL_STYLE = '/ask-panel.css'; + const ASK_SLOT_ID = 'hive-ask-slot'; + // A section counts as "current" once its top is above this fraction of + // the viewport height. + const ASK_SECTION_VIEWPORT_FRACTION = 3; + let askPanelRequested = false; + + // askCurrentSection names where the person is, from our own ids only: + // the Settings tab when the dialog is open, else the dashboard section + // nearest the top of the viewport. + function askCurrentSection() { + const overlay = document.getElementById('config-overlay'); + if (overlay && !overlay.classList.contains('hidden')) { + return (typeof _configState !== 'undefined' && _configState && _configState.tab === 'features') ? 'settings-features' : 'settings'; + } + let best = ''; + let bestTop = -Infinity; + const limit = window.innerHeight / ASK_SECTION_VIEWPORT_FRACTION; + Object.keys(DASHBOARD_SECTION_HELP).forEach(id => { + const el = document.getElementById(id); + if (!el || !el.offsetParent) return; + const top = el.getBoundingClientRect().top; + if (top <= limit && top > bestTop) { best = id; bestTop = top; } + }); + return best; + } + + // askCurrentDocsHref is the docs-link fallback for where the person is, + // built by the same function as every "?" help mark. + function askCurrentDocsHref() { + const section = askCurrentSection(); + if (section === 'settings-features') return dashboardDocsHref('settings', 'features'); + if (section === 'settings') return dashboardDocsHref('settings', ''); + const entry = DASHBOARD_SECTION_HELP[section]; + return dashboardDocsHref(DASHBOARD_HELP_PAGE, entry ? dashboardSectionHelpAnchor(entry.heading) : ''); + } + + function loadAskPanel(cfg) { + if (!cfg || cfg.ask_enabled !== true || askPanelRequested) return; + if (!document.getElementById(ASK_SLOT_ID)) return; + askPanelRequested = true; + const style = document.createElement('link'); + style.rel = 'stylesheet'; + style.href = ASK_PANEL_STYLE; + document.head.appendChild(style); + const script = document.createElement('script'); + script.src = ASK_PANEL_SCRIPT; + script.addEventListener('load', () => { + if (window.HiveAsk && typeof window.HiveAsk.mount === 'function') { + window.HiveAsk.mount({ slot: ASK_SLOT_ID, base: '/api/ask', section: askCurrentSection, docsHref: askCurrentDocsHref }); + } + }); + document.head.appendChild(script); + } diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 5fdd0936c8..895783a947 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -207,6 +207,8 @@ // standalone hive, which keeps the entry hidden. window._myHivesURL = cfg.my_hives_url || ''; renderMyHivesMenuItem(); + // Ask AI help (#19184): load the panel only when this hive has it on. + if (typeof loadAskPanel === 'function') loadAskPanel(cfg); const repoDisplay = cfg.org && cfg.primaryRepo && !cfg.primaryRepo.includes('/') ? cfg.org + '/' + cfg.primaryRepo : (cfg.primaryRepo || ''); diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 1eb9156157..d788b11402 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -167,6 +167,7 @@ js/plan-agent-controls.js js/acmm.js js/version.js js/sse-bootstrap.js +js/ask.js js/config-state.js js/settings-search.js js/config-dialog.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 12f7023d13..1d8cb66e3d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -9387,6 +9387,8 @@

🐝 Getting Started

+ + @@ -64679,6 +64681,8 @@

Configure LiteLLM

// standalone hive, which keeps the entry hidden. window._myHivesURL = cfg.my_hives_url || ''; renderMyHivesMenuItem(); + // Ask AI help (#19184): load the panel only when this hive has it on. + if (typeof loadAskPanel === 'function') loadAskPanel(cfg); const repoDisplay = cfg.org && cfg.primaryRepo && !cfg.primaryRepo.includes('/') ? cfg.org + '/' + cfg.primaryRepo : (cfg.primaryRepo || ''); @@ -64750,6 +64754,67 @@

Configure LiteLLM

return fetch('/api/timeline').then(r => r.json()).then(d => { window._timelineData = d; }).catch(() => {}); } const TIMELINE_REFRESH_MS = 60000; + // ── Ask AI help (#19184) ───────────────────────────────────────── + // Loads the shared panel component (pkg/askai/web, served from 'self' + // at /ask-panel.js) only when /api/config says ask is on. With ask off + // the page adds nothing and requests nothing. The panel sends only the + // question and an id from the closed section vocabulary to this hive's + // own /api/ask; the backend decides what, if anything, leaves. + const ASK_PANEL_SCRIPT = '/ask-panel.js'; + const ASK_PANEL_STYLE = '/ask-panel.css'; + const ASK_SLOT_ID = 'hive-ask-slot'; + // A section counts as "current" once its top is above this fraction of + // the viewport height. + const ASK_SECTION_VIEWPORT_FRACTION = 3; + let askPanelRequested = false; + + // askCurrentSection names where the person is, from our own ids only: + // the Settings tab when the dialog is open, else the dashboard section + // nearest the top of the viewport. + function askCurrentSection() { + const overlay = document.getElementById('config-overlay'); + if (overlay && !overlay.classList.contains('hidden')) { + return (typeof _configState !== 'undefined' && _configState && _configState.tab === 'features') ? 'settings-features' : 'settings'; + } + let best = ''; + let bestTop = -Infinity; + const limit = window.innerHeight / ASK_SECTION_VIEWPORT_FRACTION; + Object.keys(DASHBOARD_SECTION_HELP).forEach(id => { + const el = document.getElementById(id); + if (!el || !el.offsetParent) return; + const top = el.getBoundingClientRect().top; + if (top <= limit && top > bestTop) { best = id; bestTop = top; } + }); + return best; + } + + // askCurrentDocsHref is the docs-link fallback for where the person is, + // built by the same function as every "?" help mark. + function askCurrentDocsHref() { + const section = askCurrentSection(); + if (section === 'settings-features') return dashboardDocsHref('settings', 'features'); + if (section === 'settings') return dashboardDocsHref('settings', ''); + const entry = DASHBOARD_SECTION_HELP[section]; + return dashboardDocsHref(DASHBOARD_HELP_PAGE, entry ? dashboardSectionHelpAnchor(entry.heading) : ''); + } + + function loadAskPanel(cfg) { + if (!cfg || cfg.ask_enabled !== true || askPanelRequested) return; + if (!document.getElementById(ASK_SLOT_ID)) return; + askPanelRequested = true; + const style = document.createElement('link'); + style.rel = 'stylesheet'; + style.href = ASK_PANEL_STYLE; + document.head.appendChild(style); + const script = document.createElement('script'); + script.src = ASK_PANEL_SCRIPT; + script.addEventListener('load', () => { + if (window.HiveAsk && typeof window.HiveAsk.mount === 'function') { + window.HiveAsk.mount({ slot: ASK_SLOT_ID, base: '/api/ask', section: askCurrentSection, docsHref: askCurrentDocsHref }); + } + }); + document.head.appendChild(script); + } // ── Configuration Dialog ────────────────────────────────────────── let _configState = { type: null, agent: null, tab: null, data: {}, dirty: {} }; const _configTabMemory = {}; From c0ad209a71ef6972de0ebda98bf2cd34c7adb271 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:26:16 -0500 Subject: [PATCH 07/11] =?UTF-8?q?=F0=9F=93=96=20ask:=20resync=20hub=20API?= =?UTF-8?q?=20reference=20citations=20after=20the=20rebase=20onto=20v5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/docs/api-reference/hub-server.md | 68 ++++++++++++++-------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 4b71dc889b..847a64b977 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -35,29 +35,29 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/benchmarks/ingest` | Per-hive heartbeat bearer | Spoke push target for anonymized [benchmark records](../benchmarks.md): body `{hive_id, records[]}`; the hub recomputes the hive hash from the authenticated id, rejects records whose `source.hive_id` differs (`401` bad bearer, `403` unregistered hive, `400` malformed), merges accepted records by id into `/data/benchmarks//.json` and returns `202 {accepted, rejected, files}` | `pkg/hub/benchmarks.go` | | `GET` | `/api/hub/benchmarks` | Public | Benchmark publisher status: `last_ingest_at`, `last_publish_at`, `last_publish_files`, `last_error`, `pending_files`, `hive_count`, `record_count` and per-hive-hash `hives{}` counts; the hub commits pending month files hourly to `hivecommons/benchmarks` (`HIVE_BENCHMARKS_REPO`) via its App identity | `pkg/hub/benchmarks.go` | | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:511` | -| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1831` | -| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1832` | +| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1832` | +| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1833` | | `GET` | `/activity` | Signed-in user | Fleet activity page ([#16063](https://github.com/hivecommons/hive/issues/16063)): read-only, data-free shell that polls `/api/hub/activity` every 15 s with `If-None-Match`. No session → `307` to `/login`; blocked user → `403`. Own Content-Security-Policy (scripts and styles from `'self'` only, `script-src-attr`/`style-src-attr` `'none'`), `Cache-Control: no-cache` + content `ETag`. See [Hub Fleet activity page](../hub-fleet-activity.md) | `pkg/hub/activity_page.go` | | `GET` | `/activity/public` | Public | Public-safe Fleet activity page ([#15966](https://github.com/hivecommons/hive/issues/15966)): the same data-free shell as `/activity`, served without a session; on this path the page polls `/api/hub/activity/public` with `credentials: 'omit'`. Source of the `twitch.tv/hivecommonsfleet` broadcast. Same CSP and cache headers as `/activity`. See [Hub Fleet activity page](../hub-fleet-activity.md#public-safe-view) | `pkg/hub/activity_public.go` | | `GET` | `/activity/assets/{name}` | Public | The shared tracker assets the Fleet activity page loads, byte-identical: the row asset (`pkg/webassets/trackerrow`, [#16062](https://github.com/hivecommons/hive/issues/16062)) and the `am.*` URL-view and display-playlist helpers (`pkg/webassets/trackerview`, [#16064](https://github.com/hivecommons/hive/issues/16064)); only names in `trackerrow.Files` or `trackerview.Files`, else `404`. `Cache-Control: no-cache` + content `ETag` | `pkg/hub/activity_page.go` | -| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1750` | -| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1751` | -| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1752` | -| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat. A request carrying `X-Hive-Activity-Update` is an activity-only update ([#15963](https://github.com/hivecommons/hive/issues/15963)): body `{"activity_update":{"hive_id","activity"}}`, the same per-hive bearer, accepted only for a hive already in the registry (`404` otherwise); it replaces the in-memory activity digest and nothing else, and the signed response carries `ok`, `activity_etag` and `activity_events_ack` (the highest activity event sequence number the hub holds for the hive, [#15964](https://github.com/hivecommons/hive/issues/15964); full heartbeat responses carry it too) | `pkg/hub/server.go:1753` | -| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1754` | -| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1765` | -| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1766` | -| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1767` | -| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1768` | +| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1751` | +| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1752` | +| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1753` | +| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat. A request carrying `X-Hive-Activity-Update` is an activity-only update ([#15963](https://github.com/hivecommons/hive/issues/15963)): body `{"activity_update":{"hive_id","activity"}}`, the same per-hive bearer, accepted only for a hive already in the registry (`404` otherwise); it replaces the in-memory activity digest and nothing else, and the signed response carries `ok`, `activity_etag` and `activity_events_ack` (the highest activity event sequence number the hub holds for the hive, [#15964](https://github.com/hivecommons/hive/issues/15964); full heartbeat responses carry it too) | `pkg/hub/server.go:1754` | +| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1755` | +| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1766` | +| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1767` | +| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1768` | +| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1769` | | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | | `GET` | `/api/hub/activity` | Signed-in user | Read-only hub-wide activity view ([#15951](https://github.com/hivecommons/hive/issues/15951), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)) merged from each spoke's heartbeat `activity` digest, held in hub memory only. Authorization is per user and per hive before aggregation: hub admins see every registered hive; everyone else only hives they own or hold an unexpired grant for; anonymous → `401`. Returns `hives[]` (`hive_id`, `name`, `status` `ok`/`stale`/`not_reporting`/`missing`, `reporting`, `stale` once the block is older than two heartbeats, `last_heartbeat`, `received_at`, `generated_at`, `totals` — `items`, `by_stage`, `by_modifier`, counting private and truncated items too — `truncated` and `events_dropped`), `items[]` (`hive_id`, `repo`, `n`, `kind`, `title`, `author_kind`, `stage`, `stage_n`, `since`, `mods`, `private`) ordered needs-human/needs-decision, stalled, furthest stage, oldest, a response-level `truncated` (cap 2000), and `events[]` ([#15964](https://github.com/hivecommons/hive/issues/15964): `hive_id`, `received_at`, `seq`, `type` `opened`/`stage`/`merged`, `repo`, `n`, `kind`, `title`, `from`, `stage`, `at`, `private`), oldest first, from a fleet-wide in-memory ring of at most 1,000 events, none held longer than 24 hours (ageing out is not counted in `events_dropped`; when full, the oldest event of the hive holding the most events is dropped, counted in that hive's `events_dropped`, so one hive cannot evict the others' events). Events are filtered per user and per hive exactly like items, before aggregation, so an event for a hive the viewer cannot see is never delivered; `mod`/`author_kind` filters keep only events whose item is still on the hive's board. A spoke block carries at most 200 events; drops are disclosed per hive as `events_dropped`. New events change the `ETag`. Each digest carries at most 100 items by default and never more than the 250-item hub ceiling; private-repository items appear only when the spoke opts in. Filters: `hive`, `repo`, `stage`, `mod`, `author_kind`, `q` (title substring or `#`), each ≤ 200 characters (else `400`). `ETag` + `If-None-Match` → `304`; `Cache-Control: private, no-cache`, `Vary: Cookie, Authorization`. No actions | `pkg/hub/activity.go` | | `GET` | `/api/hub/activity/public` | Public | Public-safe activity view ([#15966](https://github.com/hivecommons/hive/issues/15966)): the `/api/hub/activity` shape for anyone, never reading a cookie, token or `Authorization` header (credentials do not change the response). Only hives the registry lists as public on github.com, and only items and events not marked `private`; `totals`, per-hive `truncated` and `events_dropped`, hive owners and per-user grants are omitted. Same filters (`400` on an invalid one). The body is built at most once per 2 s per parsed filter and shared by every anonymous caller, so rows, `generated_at` and the `ETag` change at most every 2 s; query strings that parse to the default view share one entry. Toggling a hive's visibility drops the cache at once. `ETag` + `If-None-Match` → `304`; `Cache-Control: no-cache` | `pkg/hub/activity_public.go` | -| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1776` | -| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1786` | -| `GET` | `/api/hub/selfservice/status` | Hub auth | Self-service registration status: `{enabled, max_per_user, count, expiry}`; always answers so the dashboard can decide whether **Register your own hive** opens the form or the self-hosting guide ([#18060](https://github.com/hivecommons/hive/issues/18060)) | `pkg/hub/server.go:1790` | -| `GET` | `/api/hub/selfservice/hives` | Hub auth | The caller's own self-service (`byo-`) hives: `{hives[]}` of `{id, owner, org, repos, dashboard_url, created_at, ownership_checked_at, last_accepted_heartbeat_at, online}`; never a key or a hash. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/server.go:1791` | -| `POST` | `/api/hub/selfservice/hives` | Hub auth | Register a self-hosted hive: body `{name, org, repos[], dashboard_url}`; the ID is `byo---` (the double hyphen keeps IDs unambiguous, since logins contain hyphens but never `--`). Proves `permissions.admin` on every `owner/name` repo with the caller's own stored GitHub token (`403` naming the refused repo, nothing stored); `400` invalid or reserved name, a login that contains `--` or starts or ends with `-`, bare-org or `.`/`..` repo, or non-`https`/private `dashboard_url`; `409` ID already registered; `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER` (enforced again under the store lock, so concurrent registrations cannot exceed it). `201 {hive, key, hub_url, snippets{docker_compose, podman, kubernetes}}`: the raw key appears here once and only its hash is stored. `404` while the flag is off | `pkg/hub/server.go:1792` | +| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1777` | +| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1787` | +| `GET` | `/api/hub/selfservice/status` | Hub auth | Self-service registration status: `{enabled, max_per_user, count, expiry}`; always answers so the dashboard can decide whether **Register your own hive** opens the form or the self-hosting guide ([#18060](https://github.com/hivecommons/hive/issues/18060)) | `pkg/hub/server.go:1791` | +| `GET` | `/api/hub/selfservice/hives` | Hub auth | The caller's own self-service (`byo-`) hives: `{hives[]}` of `{id, owner, org, repos, dashboard_url, created_at, ownership_checked_at, last_accepted_heartbeat_at, online}`; never a key or a hash. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/server.go:1792` | +| `POST` | `/api/hub/selfservice/hives` | Hub auth | Register a self-hosted hive: body `{name, org, repos[], dashboard_url}`; the ID is `byo---` (the double hyphen keeps IDs unambiguous, since logins contain hyphens but never `--`). Proves `permissions.admin` on every `owner/name` repo with the caller's own stored GitHub token (`403` naming the refused repo, nothing stored); `400` invalid or reserved name, a login that contains `--` or starts or ends with `-`, bare-org or `.`/`..` repo, or non-`https`/private `dashboard_url`; `409` ID already registered; `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER` (enforced again under the store lock, so concurrent registrations cannot exceed it). `201 {hive, key, hub_url, snippets{docker_compose, podman, kubernetes}}`: the raw key appears here once and only its hash is stored. `404` while the flag is off | `pkg/hub/server.go:1793` | | `GET` | `/api/hub/v1` | Public | Hub registration protocol v1 discovery ([#18642](https://github.com/hivecommons/hive/issues/18642)): `{protocol, version, base_path, operations[], patch_fields[], limits{max_repos, max_per_user, expiry, key_rotation_overlap}, proof_methods[]}`. Readable without signing in so a client learns the limits before it hits a `4xx`. `proof_methods` is `["hub-session-token"]`: ownership is proven with the GitHub token stored at hub sign-in. `max_repos` is `HIVE_HUB_SELFSERVICE_MAX_REPOS`. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_api.go` | | `POST` | `/api/hub/v1/registrations` | Hub auth | Register a self-hosted hive as a resource ([#18642](https://github.com/hivecommons/hive/issues/18642)): the same body, proof and refusals as `POST /api/hub/selfservice/hives` (including `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER`), except that a repo list over `HIVE_HUB_SELFSERVICE_MAX_REPOS` answers `413 {error, limit: "max_repos", max_repos}` instead of `400`. `201 {registration, key, hub_url, snippets}` with `Location` and a strong `ETag` header; `registration` is the legacy view plus `etag` and `repo_proofs[{repo, checked_at}]` (when the owner's admin permission on each repo was last proven). The raw key appears once. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_api.go` | | `GET` | `/api/hub/v1/registrations` | Hub auth | The caller's own registrations: `{registrations[]}`, each with its `etag` and `repo_proofs`; never a key or a hash | `pkg/hub/selfservice_v1_api.go` | @@ -65,26 +65,26 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PATCH` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner only, by hub session (a registration key is not accepted): change `repos` and/or `dashboard_url` in place with the heartbeat key kept valid ([#18642](https://github.com/hivecommons/hive/issues/18642)). Body: `repos` is a full list (replacement) or `{add[], remove[]}`; `dashboard_url` is an `https` URL or `""` to clear it. `If-Match` is required: `428` when absent, `412` carrying the current `ETag` when stale (checked before any GitHub call and again under the store lock). Only added repos are proven (`403` naming the first refused repo, nothing applied); kept repos keep their proof time and removed repos lose theirs. `org`, the owner, the ID and the keys are not editable: a body naming `org` or any other field is `400`, as is a list that would leave no repo. Over `HIVE_HUB_SELFSERVICE_MAX_REPOS` is `413 {error, limit: "max_repos", max_repos}`. Removing a repo the registration does not list is ignored; an edit that changes nothing answers `200` with the current `ETag` and does not bump the revision. `200 {registration}` with the new `ETag`; the key never appears. `404` for a missing hive, another user's hive and a hub admin who does not own it; `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_patch.go` | | `POST` | `/api/hub/v1/registrations/{id}/keys` | Hub auth | Owner only: rotate the heartbeat key; the previous key keeps authenticating for the 10 minute overlap. `201 {id, key, hub_url, overlap, snippets}` (the legacy rotate answers `200`) with the new `ETag`; the raw key appears once. Optional `If-Match` (`412` when stale). A body asking for a grace window is refused with `400`: caller-chosen grace is a later rollout step | `pkg/hub/selfservice_v1_api.go` | | `DELETE` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`. Optional `If-Match` (`412` when stale, carrying the current `ETag`) | `pkg/hub/selfservice_v1_api.go` | -| `POST` | `/api/hub/selfservice/hives/{id}/rotate` | Hub auth | Owner only: mint a new heartbeat key for `{id}`; the previous key keeps authenticating for `overlap` (10 minutes). `200 {id, key, hub_url, overlap, snippets}`, raw key once. Another user's hive, a missing hive and a hub admin who does not own it all get `404` | `pkg/hub/server.go:1793` | -| `DELETE` | `/api/hub/selfservice/hives/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`; another user's hive is `404` | `pkg/hub/server.go:1794` | -| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1798` | -| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1799` | -| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1800` | -| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1801` | +| `POST` | `/api/hub/selfservice/hives/{id}/rotate` | Hub auth | Owner only: mint a new heartbeat key for `{id}`; the previous key keeps authenticating for `overlap` (10 minutes). `200 {id, key, hub_url, overlap, snippets}`, raw key once. Another user's hive, a missing hive and a hub admin who does not own it all get `404` | `pkg/hub/server.go:1794` | +| `DELETE` | `/api/hub/selfservice/hives/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`; another user's hive is `404` | `pkg/hub/server.go:1795` | +| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1799` | +| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1800` | +| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1801` | +| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1802` | | `GET` | `/api/mail/hosts` | hive-mx bearer (`HIVE_HUB_MAIL_TOKEN`) | Hosts the mail receiver accepts `hive@` for ([#18395](https://github.com/hivecommons/hive/issues/18395)): `{hosts[]}`, sorted, lower-case: every hosted hive's subdomain host, vanity URL host and reported dashboard URL host. A host claimed by two hives is left out. `401` bad token, `404` while `HIVE_HUB_MAIL_TOKEN` is unset. `Cache-Control: no-store` | `pkg/hub/mail_relay.go` | | `POST` | `/api/mail/inbound` | hive-mx bearer (`HIVE_HUB_MAIL_TOKEN`) | One parsed mail delivery from hive-mx (`pkg/mailin/wire.Delivery`): JSON, or `multipart/form-data` for a large files delivery, routed by the `X-Hive-Mail-Delivery`, `X-Hive-Mail-Kind` and `X-Hive-Mail-Recipient` headers (at most 48 MiB, `HIVE_HUB_MAIL_MAX_BODY_BYTES`, this route only; without the headers, JSON of at most 8 MiB). The body is spooled to disk, never held whole in memory. The hub matches the recipient host to a hosted hive, signs the body byte for byte with that hive's relay key (`X-Hive-Relay-Timestamp`, `X-Hive-Relay-Signature-256` bound to `X-Hive-Relay-Delivery`) and forwards it to the spoke's `/api/meetings/invites`, `/api/inbox/email`, `/api/meetings/calendar-emails/proof` or `/api/inbox/email/report` (a refusal report, [#18699](https://github.com/hivecommons/hive/issues/18699)) by `kind`, behind the webhook relay's private-address guard and without following redirects. A files delivery that is multipart or larger than one piece (`HIVE_HUB_MAIL_CHUNK_BYTES`, 768 KiB) goes to `/api/inbox/email/chunk` in signed pieces instead ([#18564](https://github.com/hivecommons/hive/issues/18564)). Stores nothing once relayed; logs the delivery id only. `202` delivered; `400` invalid delivery; `404` no such hive; `413` too large; `422` the spoke refused it (permanent); `502`/`503` hive not reachable yet or unavailable (hive-mx asks the sender to retry) | `pkg/hub/mail_relay.go` | -| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1804` | -| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1805` | -| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1806` | -| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1809` | -| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1812` | -| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1813` | -| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1820` | -| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1821` | -| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1822` | -| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1839` | -| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1844` | -| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1846` | +| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1805` | +| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1806` | +| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1807` | +| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1810` | +| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1813` | +| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1814` | +| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1821` | +| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1822` | +| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1823` | +| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1840` | +| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1845` | +| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1847` | | `GET` | `/api/marketplace/workflows` | Public | Workflow-model marketplace index ([#17620](https://github.com/hivecommons/hive/issues/17620) phase 7): `{generatedAt, entries:[{name, version, hash, tier, description, source, states, columns, publishedAt, publishedBy, sourceSHA?, newerIngestAvailable, adoption:{}, ratings:{}, benchmarks:{}}]}`. Strong `ETag` (sha256 of the body) + `Cache-Control: no-cache`; `If-None-Match` → `304`. Tiers: `built-in`, `curated`, `ingested-unreviewed`, `local-published`. `404` when `HIVE_HUB_MARKETPLACE_DISABLED` is set | `pkg/hub/marketplace.go:36` | | `GET` | `/api/marketplace/workflows/{name}/{version}/bundle` | Public | One immutable signed bundle (`{apiVersion, model, profile, hash, createdAt, createdBy, tier}`), `Cache-Control: immutable`; `404` unknown, `400` malformed key | `pkg/hub/marketplace.go:37` | | `POST` | `/api/marketplace/workflows` | Spoke heartbeat bearer + `X-Hive-ID`, or Hub admin session | Publish a bundle. Body = bundle (≤ 4 MiB); the hub re-verifies the hash and recompiles the model before storing. Publisher may assert tier `local`/`local-published` (normalised to `local-published`) or `ingested-unreviewed`; `curated`/`built-in` require a hub admin session (`403` otherwise). `201 {published, created:true, entry}`; identical republish `200 created:false`; different content under an existing `name@version` `409`; verification failure `422`; unknown hive `403`; no hub secret `503` | `pkg/hub/marketplace.go:38` | From c6812090e4a52af5f53d7ab80ad05afdba5a308a Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:26:54 -0500 Subject: [PATCH 08/11] =?UTF-8?q?=F0=9F=90=9B=20ask:=20keep=20the=20panel?= =?UTF-8?q?=20stylesheet=20free=20of=20motion=20keywords,=20comment=20incl?= =?UTF-8?q?uded?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/askai/web/ask-panel.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/askai/web/ask-panel.css b/src/pkg/askai/web/ask-panel.css index c4509e02b1..4bab91c72e 100644 --- a/src/pkg/askai/web/ask-panel.css +++ b/src/pkg/askai/web/ask-panel.css @@ -1,6 +1,6 @@ /* Ask AI help panel (#19177). Uses the host dashboard's tokens with plain fallbacks, docks to the side instead of floating over data (#7160), and - has no animation, so reduced-motion needs no special case. */ + uses no motion effects, so reduced motion needs no special case. */ :root { --hive-ask-width: 380px; } From b0828af2bd8be2fe224f63ae650ea226746f6619 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:31:12 -0500 Subject: [PATCH 09/11] =?UTF-8?q?=F0=9F=A7=AA=20ask:=20rename=20the=20test?= =?UTF-8?q?=20helper=20that=20shadowed=20askOn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/api_ask_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/pkg/dashboard/api_ask_test.go b/src/pkg/dashboard/api_ask_test.go index 53be15abeb..b9e4e0c651 100644 --- a/src/pkg/dashboard/api_ask_test.go +++ b/src/pkg/dashboard/api_ask_test.go @@ -123,9 +123,9 @@ func askResult(t *testing.T, rec *httptest.ResponseRecorder) askai.Result { return r } -func askOn() *bool { v := true; return &v } +func askTrue() *bool { v := true; return &v } -var askDirect = config.AskConfig{Enabled: askOn(), Mode: config.AskModeDirect, +var askDirect = config.AskConfig{Enabled: askTrue(), Mode: config.AskModeDirect, Kapa: config.AskKapaConfig{ProjectID: askTestProject, IntegrationID: askTestIntegration, APIKeyFile: "key"}} // TestHiveAskOffIsInert: no ask block, or a half-configured one, answers 404 @@ -250,7 +250,7 @@ func TestHiveAskDirectModeFlow(t *testing.T) { // mode stays off. func TestHiveAskHubModeUsesTheRelay(t *testing.T) { hubSrv := newAskFakeRemote(t, askHubReply) - hubMode := config.AskConfig{Enabled: askOn(), Mode: config.AskModeHub} + hubMode := config.AskConfig{Enabled: askTrue(), Mode: config.AskModeHub} s, _ := askTestServer(t, hubMode, config.HubConfig{Enabled: true, URL: hubSrv.srv.URL, HiveType: config.HiveTypeHosted}, "") askCall(s, "PUT", "/api/ask/consent", `{"text_version":"`+askai.ConsentTextVersion+`"}`, "alice") r := askResult(t, askCall(s, "POST", "/api/ask", `{"question":"Where is pause?","section":"agents-section"}`, "alice")) From 91f432e1b815b1b177950d34f03cbf935a759069 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:56:01 -0500 Subject: [PATCH 10/11] =?UTF-8?q?=F0=9F=A7=AA=20ask:=20drop=20route-parity?= =?UTF-8?q?=20exceptions=20for=20the=20panel=20assets,=20the=20scanner=20d?= =?UTF-8?q?oes=20not=20count=20them?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/dashboard/openapi_route_parity_test.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/pkg/dashboard/openapi_route_parity_test.go b/src/pkg/dashboard/openapi_route_parity_test.go index c6a6ac23e8..252c127dc8 100644 --- a/src/pkg/dashboard/openapi_route_parity_test.go +++ b/src/pkg/dashboard/openapi_route_parity_test.go @@ -45,16 +45,6 @@ type routeParityException struct { // not listed here must appear in the spec (with a matching method) or the // test fails. var routeParityExceptions = []routeParityException{ - { - method: "GET", path: "/ask-panel.js", - reason: "Ask AI help panel script (#19184): a static same-origin asset " + - "served only while ask is on, not a JSON data operation.", - }, - { - method: "GET", path: "/ask-panel.css", - reason: "Ask AI help panel stylesheet (#19184): a static same-origin " + - "asset served only while ask is on, not a JSON data operation.", - }, { method: "GET", path: "/api/health", reason: "Kubernetes readiness probe. Returns a bare {\"status\":...} " + From 8cd49e43bb7e1bbf997b9530c2589bd290af4e1b Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:55:44 -0500 Subject: [PATCH 11/11] =?UTF-8?q?=F0=9F=A7=AA=20ask:=20record=20the=20ask?= =?UTF-8?q?=20block=20in=20the=20config=20golden=20and=20the=20askai=20imp?= =?UTF-8?q?ort=20in=20the=20dashboard=20ratchet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/internal/testutil/dashboard_import_allowlist.txt | 2 ++ src/pkg/config/testdata/agent_runtime_golden.json | 4 ++++ src/pkg/dashboard/import_count_test.go | 6 ++++-- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/internal/testutil/dashboard_import_allowlist.txt b/src/internal/testutil/dashboard_import_allowlist.txt index 56f701db7c..344564d5c0 100644 --- a/src/internal/testutil/dashboard_import_allowlist.txt +++ b/src/internal/testutil/dashboard_import_allowlist.txt @@ -10,6 +10,7 @@ # workflowmodel: /api/workflows handlers compile lifecycle models (Compile, Profile diagnostics) and the tracker emits per-repo workflow columns; the store and bindings already route through Dependencies (hivecommons/hive#17620 P2). # egressmark: deployment_upgrade.go dials the in-cluster Kubernetes API for the hive's own rollout; the dial must carry the forced-egress SO_MARK or nodes without xt_owner redirect it into the MITM proxy (hivecommons/hive#17817). # agentsmd: the /api/status repo entries carry each repo's last AGENTS.md injection status (size, effective cap, dropped sections) from agentsmd.StatusFor, the read side of the registry the scheduler records into (hivecommons/hive#18495). +# askai: the Ask AI help routes (/api/ask*) and the shared panel assets run the same consent, limits, credential-shape refusal, source filtering and hub-relay client the hub uses, so the hub and hive cannot drift (hivecommons/hive#19183). # buildcontains: GET /api/version/contains answers "does the running build contain PR #N" through the same dependency-free ancestry resolver the hub uses (yes/no/unknown, never a guess); a leaf package importing only the standard library (hivecommons/hive#18915). github.com/hivecommons/hive/crux github.com/hivecommons/hive/crux/agentsmd @@ -25,6 +26,7 @@ github.com/hivecommons/hive/crux/watchdog github.com/hivecommons/hive/pkg/acmmadvisor github.com/hivecommons/hive/pkg/advisory github.com/hivecommons/hive/pkg/agentaudit +github.com/hivecommons/hive/pkg/askai github.com/hivecommons/hive/pkg/beads github.com/hivecommons/hive/pkg/blocker github.com/hivecommons/hive/pkg/buildcontains diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index a52b7c543a..573b4388e2 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -793,6 +793,10 @@ "avatars": {}, "mention_search": {} }, + "ask": { + "kapa": {}, + "limits": {} + }, "duplicate_sweep": {}, "good_first_issue": {}, "supersession_sweep": {}, diff --git a/src/pkg/dashboard/import_count_test.go b/src/pkg/dashboard/import_count_test.go index 36f229eb0f..f8677d2c87 100644 --- a/src/pkg/dashboard/import_count_test.go +++ b/src/pkg/dashboard/import_count_test.go @@ -83,8 +83,10 @@ func TestDashboardInternalImportCountRatchet(t *testing.T) { // classifier behind isPrivateURL that the hub shares so the two copies // cannot drift (hivecommons/hive#18991), plus pkg/gfi, the umbrella and // owner-only classifier the contributor queue gates and the tracker-row - // pill share so the two cannot disagree (hivecommons/hive#19078). - const maxDashboardInternalImports = 68 + // pill share so the two cannot disagree (hivecommons/hive#19078), plus + // pkg/askai, the Ask AI help service and hub-relay client shared with the + // hub so consent, limits and filtering cannot drift (hivecommons/hive#19183). + const maxDashboardInternalImports = 69 entries, err := os.ReadDir(".") if err != nil {