From 626f1bce390512a1af5e5b6e32859408b2af3973 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 20:42:26 -0500 Subject: [PATCH 1/6] =?UTF-8?q?=E2=9C=A8=20ask:=20hub=20backend=20for=20op?= =?UTF-8?q?tional=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 c0ad209a71ef6972de0ebda98bf2cd34c7adb271 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 21:26:16 -0500 Subject: [PATCH 5/6] =?UTF-8?q?=F0=9F=93=96=20ask:=20resync=20hub=20API=20?= =?UTF-8?q?reference=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 6/6] =?UTF-8?q?=F0=9F=90=9B=20ask:=20keep=20the=20panel=20?= =?UTF-8?q?stylesheet=20free=20of=20motion=20keywords,=20comment=20include?= =?UTF-8?q?d?= 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; }