diff --git a/changelog.d/changed-retire-campaigns-api.md b/changelog.d/changed-retire-campaigns-api.md new file mode 100644 index 0000000000..23f26f7523 --- /dev/null +++ b/changelog.d/changed-retire-campaigns-api.md @@ -0,0 +1 @@ +- Inception campaigns are retired in favour of Inception (spek) sessions. The `/api/campaigns` endpoints are removed, including resume, release, revise, delete, recheck and every `/jam` route. Campaign Jam (threads, suggestions, polls, spec revisions and GitHub Projects sync) and campaign recheck (continuous convergence and outward discovery) go with them. The Spek recheck block in Settings is removed too. Jam no longer feeds achievements, and since Jam was the only source of the review role, Full SDLC Fireteam now counts spec, plan and implement coverage by three distinct actors. Nothing is deleted. On the first start after the upgrade, if `/data/inception/campaigns/` or `campaign-jam.json` exists, Hive writes one read-only export to `/data/exports/campaigns-.tar.gz` (mode 0600) and logs its path once. The original files stay in place for one release. `runs.spektacular.recheck` in `hive.yaml` is still accepted on load and never fails validation, but it has no effect and logs a one-line deprecation warning. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 6b8c7e3396..d8b0de225b 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -68,10 +68,6 @@ "name": "Inception", "description": "Greenfield project scaffolding and ideation workflow" }, - { - "name": "Campaigns", - "description": "Resumable Inception and Spektacular campaigns" - }, { "name": "Knowledge", "description": "Knowledge base facts, vaults, git sources, documents, and channels" @@ -35129,914 +35125,6 @@ } } }, - "/api/campaigns": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "List resumable campaigns", - "description": "Lists archived Inception sessions and retained Spektacular runs. Supports search/q, repo, stage, status, and owner query filters.", - "parameters": [ - { - "name": "search", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "q", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "repo", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "stage", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "status", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "owner", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Campaign list", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean" - }, - "campaigns": { - "type": "array", - "items": { - "type": "object", - "required": [ - "id", - "title", - "current_stage", - "status", - "engine", - "type" - ], - "properties": { - "id": { - "type": "string" - }, - "title": { - "type": "string" - }, - "source": { - "type": "string" - }, - "repos": { - "type": "array", - "items": { - "type": "string" - } - }, - "current_stage": { - "type": "string" - }, - "current_step": { - "type": "string" - }, - "artifacts": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string" - }, - "label": { - "type": "string" - }, - "url": { - "type": "string" - } - } - } - }, - "linked_prs": { - "type": "array", - "items": { - "type": "string" - } - }, - "linked_issues": { - "type": "array", - "items": { - "type": "string" - } - }, - "contributors": { - "type": "array", - "items": { - "type": "string" - } - }, - "last_activity": { - "type": "string" - }, - "status": { - "type": "string" - }, - "engine": { - "type": "string" - }, - "type": { - "type": "string" - }, - "run_key": { - "type": "string" - }, - "run_url": { - "type": "string" - }, - "lease_owner": { - "type": "string" - } - } - } - } - } - } - } - } - } - } - } - }, - "/api/campaigns/{id}": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "Get a campaign", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Campaign detail", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean" - }, - "campaign": { - "type": "object", - "required": [ - "id", - "title", - "current_stage", - "status", - "engine", - "type" - ], - "properties": { - "id": { - "type": "string" - }, - "title": { - "type": "string" - }, - "source": { - "type": "string" - }, - "repos": { - "type": "array", - "items": { - "type": "string" - } - }, - "current_stage": { - "type": "string" - }, - "current_step": { - "type": "string" - }, - "artifacts": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string" - }, - "label": { - "type": "string" - }, - "url": { - "type": "string" - } - } - } - }, - "linked_prs": { - "type": "array", - "items": { - "type": "string" - } - }, - "linked_issues": { - "type": "array", - "items": { - "type": "string" - } - }, - "contributors": { - "type": "array", - "items": { - "type": "string" - } - }, - "last_activity": { - "type": "string" - }, - "status": { - "type": "string" - }, - "engine": { - "type": "string" - }, - "type": { - "type": "string" - }, - "run_key": { - "type": "string" - }, - "run_url": { - "type": "string" - }, - "lease_owner": { - "type": "string" - } - } - } - } - } - } - } - }, - "404": { - "description": "Campaign not found" - } - } - }, - "delete": { - "tags": [ - "Campaigns" - ], - "summary": "Delete a campaign record", - "description": "Owner only. Removes the archived Inception state and wiki snapshot for the stable campaign id and audit-logs campaign_delete. Knowledge-base facts, Jam threads, scaffolded repo files and other revisions in the same chain are kept; deleting the live L1 session clears it. Run-backed Spektacular campaigns return 409.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Campaign record deleted", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean" - }, - "id": { - "type": "string" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "403": { - "description": "Owner access required" - }, - "404": { - "description": "Campaign not found" - }, - "409": { - "description": "Run-backed campaign cannot be deleted here" - } - } - } - }, - "/api/campaigns/{id}/resume": { - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Resume or pick up a campaign", - "description": "Restores archived Inception state and wiki files, or returns the retained Spektacular run plus a CLI status command.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": false, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "surface": { - "type": "string", - "enum": [ - "chat", - "contributor", - "cli", - "dashboard" - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Resume response", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean" - }, - "campaign": { - "type": "object", - "required": [ - "id", - "title", - "current_stage", - "status", - "engine", - "type" - ], - "properties": { - "id": { - "type": "string" - }, - "title": { - "type": "string" - }, - "source": { - "type": "string" - }, - "repos": { - "type": "array", - "items": { - "type": "string" - } - }, - "current_stage": { - "type": "string" - }, - "current_step": { - "type": "string" - }, - "artifacts": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string" - }, - "label": { - "type": "string" - }, - "url": { - "type": "string" - } - } - } - }, - "linked_prs": { - "type": "array", - "items": { - "type": "string" - } - }, - "linked_issues": { - "type": "array", - "items": { - "type": "string" - } - }, - "contributors": { - "type": "array", - "items": { - "type": "string" - } - }, - "last_activity": { - "type": "string" - }, - "status": { - "type": "string" - }, - "engine": { - "type": "string" - }, - "type": { - "type": "string" - }, - "run_key": { - "type": "string" - }, - "run_url": { - "type": "string" - }, - "lease_owner": { - "type": "string" - } - } - }, - "state": { - "type": "object" - }, - "run": { - "type": "object" - }, - "resume_command": { - "type": "string" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "404": { - "description": "Campaign not found" - }, - "409": { - "description": "Campaign lease held by another user" - } - } - } - }, - "/api/campaigns/{id}/release": { - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Release a campaign lease", - "description": "Clears the caller's active campaign lease and records a release audit event.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Campaign lease released" - }, - "404": { - "description": "Campaign not found" - }, - "409": { - "description": "Campaign is leased by another user or has no active lease" - } - } - } - }, - "/api/campaigns/{id}/revise": { - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Branch a new campaign revision", - "description": "Creates a linked revision campaign so shipped or parked work can be revisited without losing the previous campaign trail.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Campaign revision created" - }, - "404": { - "description": "Campaign not found" - } - } - } - }, - "/api/campaigns/{id}/recheck": { - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Create a Spek recheck revision", - "description": "Creates an immediate linked Spektacular recheck revision using the same cadence path. Returns 409 when a recheck revision is already in flight and 404 when recheck is disabled unless force=true is supplied.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "force", - "in": "query", - "required": false, - "schema": { - "type": "boolean" - } - } - ], - "responses": { - "200": { - "description": "Spek recheck revision created" - }, - "404": { - "description": "Campaign not found or recheck disabled" - }, - "409": { - "description": "A recheck revision is already in flight" - } - } - } - }, - "/api/campaigns/{id}/jam": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "Get campaign Jam state", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Jam state" - } - } - }, - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Record a Jam spec revision", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated Jam state" - }, - "403": { - "description": "Read-write access required" - } - } - } - }, - "/api/campaigns/{id}/jam/threads": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "List Jam threads", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Thread list" - } - } - }, - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Create a Jam thread or comment", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated Jam state" - }, - "403": { - "description": "Read-write access required" - } - } - } - }, - "/api/campaigns/{id}/jam/agents": { - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Invite an agent to a Jam thread", - "description": "Maintainer-only endpoint that posts an attributed Spektacular or configured-agent reply in a Jam thread and creates an open human-reviewable suggestion without applying a spec revision.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated Jam state" - }, - "403": { - "description": "Maintainer access required" - } - } - } - }, - "/api/campaigns/{id}/jam/suggestions": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "List Jam suggestions", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Suggestion list" - } - } - }, - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Create or resolve a Jam suggestion", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated Jam state" - }, - "403": { - "description": "Read-write or maintainer access required" - } - } - } - }, - "/api/campaigns/{id}/jam/polls": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "List Jam polls", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Poll list" - } - } - }, - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Create, vote, or decide a Jam poll", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated Jam state" - }, - "403": { - "description": "Read-write or maintainer access required" - } - } - } - }, - "/api/campaigns/{id}/jam/project-sync": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "Get Jam GitHub Projects sync status", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Project sync status" - } - } - }, - "post": { - "tags": [ - "Campaigns" - ], - "summary": "Configure or run Jam GitHub Projects sync", - "description": "Maintainer-only endpoint for enabling/disabling sync, publishing campaign specs/decisions/derived issues, and recording inbound project status updates.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true - }, - "responses": { - "200": { - "description": "Updated project sync state" - }, - "403": { - "description": "Maintainer access required" - } - } - } - }, - "/api/campaigns/{id}/jam/ws": { - "get": { - "tags": [ - "Campaigns" - ], - "summary": "Join Jam live presence and co-editing", - "description": "Upgrades to a WebSocket. Clients receive presence snapshots, section focus updates, accepted live edits and conflict messages. Live edits include base_revision_id and are rejected when stale.", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "101": { - "description": "WebSocket upgrade accepted" - }, - "403": { - "description": "Read access required" - } - } - } - }, "/api/swarm": { "get": { "tags": [ diff --git a/src/cmd/hive/boot_knowledge_deps.go b/src/cmd/hive/boot_knowledge_deps.go index e3dfb1c585..11f2f5c960 100644 --- a/src/cmd/hive/boot_knowledge_deps.go +++ b/src/cmd/hive/boot_knowledge_deps.go @@ -4,9 +4,12 @@ import ( "context" "log/slog" "os" + "time" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/campaignexport" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/dashboard" "github.com/hivecommons/hive/pkg/knowledge" "github.com/hivecommons/hive/pkg/knowledge/connector" @@ -41,7 +44,10 @@ type bootKnowledgeDeps struct { ensureNousDirs func(logger *slog.Logger) loadNousState func(logger *slog.Logger) *dashboard.NousState newInceptionEngine func(api *knowledge.KnowledgeAPI, logger *slog.Logger) *knowledge.InceptionEngine - restartBrainstorm func(ctx context.Context, mgr crux.Runtime, msg string) error + // exportRetiredCampaigns writes the one-time read-only export of retired + // inception campaign archives and campaign Jam data; nil skips it. + exportRetiredCampaigns func(cfg *config.Config, logger *slog.Logger) + restartBrainstorm func(ctx context.Context, mgr crux.Runtime, msg string) error // startConnectorSyncer runs the knowledge.connectors syncer (#11069); // nil leaves it built but not started. startConnectorSyncer func(ctx context.Context, s *connector.Syncer) @@ -77,6 +83,7 @@ func defaultBootKnowledgeDeps() bootKnowledgeDeps { newInceptionEngine: func(api *knowledge.KnowledgeAPI, logger *slog.Logger) *knowledge.InceptionEngine { return knowledge.NewInceptionEngine(inceptionDataDir, api, logger) }, + exportRetiredCampaigns: exportRetiredCampaigns, restartBrainstorm: func(ctx context.Context, mgr crux.Runtime, msg string) error { return mgr.RestartWithBootstrap(ctx, "brainstorm", msg) }, @@ -84,3 +91,24 @@ func defaultBootKnowledgeDeps() bootKnowledgeDeps { startPublishMirror: func(ctx context.Context, m *connector.Mirror) { go m.Start(ctx) }, } } + +// exportRetiredCampaigns bundles retired inception campaign archives and the +// campaign Jam store into /data/exports/campaigns-.tar.gz (0600) the +// first time either is found, and logs the path once. The sources are only +// read; they stay in place for one release. A failure is logged and never +// blocks boot. +func exportRetiredCampaigns(cfg *config.Config, logger *slog.Logger) { + var metrics, logs, agents string + if cfg != nil { + metrics, logs, agents = cfg.Data.MetricsDir, cfg.Data.LogsDir, cfg.Data.AgentsDir + } + path, err := campaignexport.Export(inceptionDataDir, campaignexport.JamPath(metrics, logs, agents), time.Now()) + if err != nil { + logger.Warn("retired campaigns export failed; the original files are untouched", "error", err) + return + } + if path != "" { + logger.Warn("retired campaigns exported", "path", path, + "detail", "inception campaigns, campaign Jam and recheck were retired in favour of Inception (spek) sessions; the original files stay in place for one release") + } +} diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 34fca672f8..7a750e1f44 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -3340,6 +3340,9 @@ func (b *boot) bootKnowledgeWith(deps bootKnowledgeDeps) { deps.startWorkspaceCleanup(b.ctx, b.logger, b.dashSrv.GetAudit()) deps.ensureNousDirs(b.logger) + if deps.exportRetiredCampaigns != nil { + deps.exportRetiredCampaigns(b.cfg, b.logger) + } b.nousState = deps.loadNousState(b.logger) b.nousState.SnapshotDir = nousSnapshotDir diff --git a/src/docs/adr/0020-spek-continuous-convergence.md b/src/docs/adr/0020-spek-continuous-convergence.md index 6bba5b69bc..6dc12203a5 100644 --- a/src/docs/adr/0020-spek-continuous-convergence.md +++ b/src/docs/adr/0020-spek-continuous-convergence.md @@ -2,7 +2,10 @@ ## Status -Accepted. +Accepted, then retired. Campaign recheck was removed together with inception +campaigns, `/api/campaigns` and campaign Jam in favour of Inception (spek) +sessions. `runs.spektacular.recheck` is still accepted in `hive.yaml` but has +no effect and logs a deprecation warning once. This record is kept for history. **Spek** is the Spektacular spec → plan → implement workflow. A **campaign** is one tracked run; a **revision** is a linked new run that rechecks it without diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index 2fd867e7f9..1a59c6b438 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -6,44 +6,44 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:139` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:143` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:144` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:145` | -| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:146` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:147` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:148` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:149` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:150` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:151` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:152` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:153` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:154` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:158` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:175` | -| `GET` | `/api/governor/pr-models` | Dashboard auth/session | Agent-authored PR distribution by normalized attribution model/backend for `window=7d`, `30d`, or `all`, including per-model rework stats and the top 10 most-reworked PRs | `pkg/dashboard/api.go:176` | -| `GET` | `/api/reviewer/accuracy` | Dashboard auth/session | Reviewer verdict calibration for the configured window: false-approve/false-block rates and confidence buckets per perspective and reviewer model | `pkg/dashboard/api.go:239` | -| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:519` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:522` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:523` | -| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:527` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:120` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:124` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:125` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:126` | +| `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:127` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:128` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:129` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:130` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:131` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:132` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:133` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:134` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:135` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:139` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:156` | +| `GET` | `/api/governor/pr-models` | Dashboard auth/session | Agent-authored PR distribution by normalized attribution model/backend for `window=7d`, `30d`, or `all`, including per-model rework stats and the top 10 most-reworked PRs | `pkg/dashboard/api.go:157` | +| `GET` | `/api/reviewer/accuracy` | Dashboard auth/session | Reviewer verdict calibration for the configured window: false-approve/false-block rates and confidence buckets per perspective and reviewer model | `pkg/dashboard/api.go:220` | +| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:500` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:503` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:504` | +| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:508` | | `GET` | `/api/review/dispatch/events` | Dashboard auth/session | Webhook review dispatch queue: `enabled`, `webhooks_configured`, `debounce_s`, `pending` (soonest first) and `recent` (newest first) dispatches with repo, number, head SHA, action, timestamps and coalesced count, plus `stats` counters; in memory, never calls GitHub | `pkg/dashboard/api_review_event_dispatch.go:15` | -| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:531` | -| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:532` | -| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:534` | -| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:537` | -| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:538` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:324` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:325` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:326` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:327` | - -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:126` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:130` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:133` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:134` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:135` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:157` | +| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:512` | +| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:513` | +| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:515` | +| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:518` | +| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:519` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:305` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:306` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:307` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:308` | + +| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:107` | +| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:111` | +| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:114` | +| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:115` | +| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:116` | +| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:138` | ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 824d9afd52..4fbaffcc1d 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -5,13 +5,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:180` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:181` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:182` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:183` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:184` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:185` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:186` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:161` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:162` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:163` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:164` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:165` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:166` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:167` | | `GET` | `/api/claude-auth/status` | Dashboard auth/session | Claude Auth Status | `pkg/dashboard/claude_auth.go:54` | | `POST` | `/api/claude-auth/start` | Dashboard auth/session | Claude Auth Start | `pkg/dashboard/claude_auth.go:55` | | `POST` | `/api/claude-auth/exchange` | Dashboard auth/session | Claude Auth Exchange | `pkg/dashboard/claude_auth.go:56` | @@ -27,7 +27,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1772` | | `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1773` | | `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1774` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:569` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:570` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:571` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:572` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:550` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:551` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:552` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:553` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index 7733ba6f91..b2f87ad343 100644 --- a/src/docs/api-reference/beads.md +++ b/src/docs/api-reference/beads.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:503` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:504` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:505` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:506` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:507` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:484` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:485` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:486` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:487` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:488` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 7eb3cf7fdb..e9c42d4ec1 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -10,13 +10,13 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:50` | | `GET` | `/api/config/triggers` | Verified owner only | Ordered Event triggers, opaque `version`/ETag, existing agents and managed repository values/labels; applies on next evaluation without restart | `pkg/dashboard/api_event_triggers.go` | | `PUT` | `/api/config/triggers` | Verified owner only | Compile-to-bool and durably compare-and-save `{rules:[{name,agent,expr,priority}],preset?:{index,kind,repo}}`; exact `If-Match` required (428 missing, 412 stale), validation 400, persistence failure 500 leaves live rules unchanged. No enabled field or source/webhook installation | `pkg/dashboard/api_event_triggers.go` | -| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:213` | -| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:214` | +| `GET` | `/api/config/dashboard` | Owner only | Dashboard runtime settings (`dashboard.*`): port, agent poll interval, `experiment_lab`, `subscription_gauge_header`, hub-proxied auth, whether an auth token is configured (never the token), access allowlist, issue bands and stage-tracker toast timings | `pkg/dashboard/api.go:194` | +| `PUT` | `/api/config/dashboard` | Owner only | Update any subset of those fields (an absent field is unchanged), including `subscription_gauge_header` (adds the owner-only usage gauge chip to the header, covering every plan the agents spend: Claude, Copilot and others); validated, saved and audit-logged as `config_dashboard_settings` | `pkg/dashboard/api.go:195` | | `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:59` | | `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:60` | | `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:51` | -| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:262` | -| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:263` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:243` | +| `PUT` | `/api/config/sla` | Owner only | Replace `sla.targets` (`{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}}`; each 0 (default) to 8760, validated before anything is persisted); the Throughput Delivery SLA panel recolours on the next status poll | `pkg/dashboard/api.go:244` | | `GET` | `/api/config/export` | Owner only | Redacted JSON export of the effective config, layer files, side files, and provenance | `pkg/dashboard/api_config_export.go` | | `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:54` | | `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:55` | @@ -24,104 +24,104 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:61` | | `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:62` | -| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:195` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:196` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:197` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:198` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:199` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:200` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:201` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:202` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:203` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:204` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:205` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:206` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:207` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:208` | +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:176` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:177` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences | `pkg/dashboard/api.go:178` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:179` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:180` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:181` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:182` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:183` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:184` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:185` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:186` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:187` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:188` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:189` | | `GET` | `/api/config/agent/{name}/variables` | Dashboard auth/session | Per-agent Variables tab: the agent's own `${VAR}` definitions plus the hive-level ones it inherits (each flagged `overridden` when the agent redefines it) and the seed-only exec/http gate flags. Never returns values — only name, type, scope and a non-secret source hint | `pkg/dashboard/api_variables.go:298` | | `PUT` | `/api/config/agent/{name}/variables/{var}` | Owner only | Create or update one per-agent variable (`static`/`env` only; `script`/`http` are 403 and seed-only; scope `template` or `both`; secret-looking static values rejected). Persisted on the agent entry; overrides a same-named hive-level variable in this agent's kick prompt | `pkg/dashboard/api_variables.go:299` | | `DELETE` | `/api/config/agent/{name}/variables/{var}` | Owner only | Delete one per-agent variable (404 for inherited hive-level variables — delete those via `/api/config/variables/{name}`) | `pkg/dashboard/api_variables.go:300` | -| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:209` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:211` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:190` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:192` | | `PATCH` | `/api/config/governor` | Owner only | Update `merge_train_stall_warn_s`; omitted values stay unchanged, 0 disables warnings; returns the effective interval | `pkg/dashboard/api_governor_merge_train.go` | -| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:216` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:223` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:224` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:228` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:229` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:241` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:242` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:243` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:244` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:245` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:196` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:197` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:204` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:205` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:209` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:222` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:223` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:224` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:225` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:226` | | `GET` | `/api/config/governor/backup` | Owner only | Backup Key Status (presence + safe source label; never the key value) | `pkg/dashboard/backup_key.go` | | `PUT` | `/api/config/governor/backup` | Owner only | Backup Key Set (64-hex AES-256 key; stored 0600, path-only in `hive.yaml`) | `pkg/dashboard/backup_key.go` | | `DELETE` | `/api/config/governor/backup` | Owner only | Backup Key Clear (backups are refused again) | `pkg/dashboard/backup_key.go` | -| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:291` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:292` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:293` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:272` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:273` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:274` | -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:217` | -| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:218` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:295` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:296` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:299` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:300` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:301` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:302` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:303` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:309` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:310` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:311` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:315` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:316` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:319` | +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:198` | +| `PUT` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Set (`cadenceScope`/`cadence_scope`: `aggregate`, `per_repo`, or empty for default) | `pkg/dashboard/api.go:199` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:276` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:277` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:280` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:281` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:282` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:283` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:284` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:290` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:291` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:292` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:296` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:297` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:300` | | `GET` | `/api/config/github/webhooks` | Owner only | Config GitHub Webhooks (payload URL, events, secret source, receiver health, App hook permissions) | `pkg/dashboard/api_github_webhook_setup.go:88` | | `POST` | `/api/config/github/webhooks/secret` | Owner only | Config GitHub Webhooks Generate Secret (returned once) | `pkg/dashboard/api_github_webhook_setup.go:89` | | `POST` | `/api/config/github/webhooks/create` | Owner only | Config GitHub Webhooks Create Hook (through the App installation) | `pkg/dashboard/api_github_webhook_setup.go:90` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:377` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:378` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:379` | -| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:369` | -| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:370` | -| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:371` | -| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:372` | -| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:373` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:374` | -| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:375` | -| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:545` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:358` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:359` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:360` | +| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:350` | +| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:351` | +| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:352` | +| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:353` | +| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:354` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:355` | +| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:356` | +| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:526` | -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:220` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:221` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:222` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:225` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:230` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:233` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:234` | -| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:541` | -| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:542` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:565` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:566` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:237` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:240` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:246` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:247` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:248` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:252` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:253` | +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:201` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:202` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:203` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:206` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:211` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:214` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:215` | +| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:522` | +| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:523` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:546` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:547` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:228` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:229` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:233` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:234` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | -| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:259` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:261` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:265` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:266` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:267` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:268` | -| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:278` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:279` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:280` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:281` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:282` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:297` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:298` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:240` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:242` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:246` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:247` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:248` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:249` | +| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:259` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:260` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security | `pkg/dashboard/api.go:261` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:262` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:263` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:278` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:279` | | `PUT` | `/api/workflows/enabled` | Owner only | Turn model-based stage derivation (`workflow.enabled`, [#17620](https://github.com/hivecommons/hive/issues/17620)) on or off from the dashboard, for hosted hives with no `hive.yaml` access. Body `{enabled: bool}`; persists `hive.yaml`; the stage engine and tracker read the live flag so it applies on the next derivation pass without a restart. Turning on also provisions every bound repository's model labels now (`warnings[]` lists repositories that could not be provisioned; the next sweep retries). Returns `{enabled, changed, bindings[], warnings?[]}`. Audited `workflow_enabled` / `workflow_disabled`; `400` on a non-boolean body | `pkg/dashboard/api_workflows.go:29` | diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index 9db06a2c75..ee842ada0b 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -6,15 +6,15 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:87` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:161` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:162` | -| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485) | `pkg/dashboard/api.go:163` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:142` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:143` | +| `GET` | `/api/cost` | Dashboard auth/session | Cost; `merged_prs` / `closed_issues` come from the webhook-incremented ForgeState counters reconciled hourly against search, with `count_stale`, `count_stale_since` and `count_source` (`forgestate` / `search`) when last-good counts are being served (#13376), `count_partial` when only some configured repos have an attributed baseline yet, and `count_error` naming why the latest attributed refresh failed or was partial (the reconcile asks GitHub about a budgeted slice of repos per pass so a many-repo hive stays inside search's rate limit); `daily_rollup` lists per-UTC-day estimated spend (`day`, `cost_usd`, `input_tokens`, `output_tokens`, `samples`) kept for ~2 years so the Cost chart can reach past the 30-day snapshot ring; `recording` reports `agent_models`, `unrecorded_models`, `recent_models`, `last_priced_growth_at`, `last_agent_model_growth_at`, `stale_after_ms` and `stale` so the card can flag stale live usage recording (#13485) | `pkg/dashboard/api.go:144` | | `GET` | `/api/repo-activity` | Dashboard auth/session | Per-repo audited activity | `pkg/dashboard/api.go` | | `GET` | `/api/repo-cost` | Dashboard auth/session | Per-repo estimated token cost (interval join, cached) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost` | Dashboard auth/session | Per-issue / PR / head-SHA estimated token cost from kick launch attribution (cached; `?ref=owner/repo#N` narrows) | `pkg/dashboard/api.go` | | `GET` | `/api/launch-cost/history` | Dashboard auth/session | Daily per-ref rollup of launch attribution (`daily_rollup[]`: `day`, `by_ref[]` with `ref`, `kind`, `launches`, `share_usd`), kept ~2 years on the `/data` PVC so cost per PR can be measured past the `/api/launch-cost` window | `pkg/dashboard/api.go` | -| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:169` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:172` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:174` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:150` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:153` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:155` | | `GET` | `/api/providers/headroom` | Owner only | Last stored per-provider usage readings (`providers[]` with `limits[]`, `captured_at`, `stale`, `probe_error_cause`, and `plan_type` when a provider reports one), from provider rotation or the default publish-only reading, plus `used_by`: per provider, the enabled agents whose backend spends its plan; serving it never triggers a new measurement. Feeds the Overview usage gauge and the rotation settings table | `pkg/dashboard/api.go:64` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:171` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:152` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 59ded08266..e6191dbe0c 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -25,7 +25,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:63` | -| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:514` | +| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:495` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:66` | | `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:69` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:67` | @@ -39,34 +39,34 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `GET` | `/api/pr-throughput` | Dashboard auth/session | Throughput: pull/merge requests and issues across tracked forges. Counts hive-created PRs/issues, hive/observed reviews, observed PR merges/closures, and issue closes over `?hours=N` (default 24, capped at audit retention; `hours=0` = all time from durable counters in `/data/pr-throughput-counters.json`) with optional exact case-insensitive `?repo=owner/name` and `?role=created\|reviewed\|merged` for the actor trend. The response keeps legacy `opened`/`merged`/`closed`, `merged_by_path`, `buckets`, velocity metrics, previous-window trends, top agents/repos/reasons, and `recorded_since`, and adds `by_actor` (`pr`/`issue` × `created`/`reviewed`/`merged`/`closed` × `hive`/`human`/`other`) plus `series` points (`t`, `hive`, `human`, `other`) for the selected role. | `pkg/dashboard/api.go:90` | -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:264` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:466` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:469` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:470` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:472` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:473` | +| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:245` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:447` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:450` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:451` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:453` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:454` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:215` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:216` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:217` | -| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:307` | -| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:308` | +| `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:288` | +| `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:289` | -| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:552` | -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:118` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:123` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:137` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:159` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:177` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:178` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:190` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:191` | -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:192` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:193` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:382` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:445` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:446` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:475` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:509` | +| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:533` | +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:99` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:104` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:118` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:140` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:158` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:159` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:171` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:172` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:173` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:174` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:363` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:426` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:427` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:456` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:490` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:350` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:351` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:352` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index c732bc2391..0bf1691337 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -51,23 +51,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:96` | | `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:97` | | `POST` | `/api/runs/{key}/reset` | Owner only | Move a run's lease back to an earlier stage (for example `implement` to `plan` after a rejected plan). Body `{"to": "", "reason": ""}`, both required. Mints a new generation so the relay holding the old one can no longer resume, persists before answering, and records the reason on the agent audit sink, the lifecycle timeline, and the `stage_completed` hook payload (`attrs.reset = "true"`). Returns `{ok, key, stage_from, stage, gen, reason}`. 400 for the same or a later stage or a missing reason, 404 when no live staged lease holds the key, 409 when the lease expired, 500 when the registry could not be written. | `pkg/dashboard/api.go:98` | -| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. API only: the dashboard's Campaigns tab was retired in favour of Inception (spek) sessions, and this endpoint is being retired. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:99` | -| `GET` | `/api/campaigns/{id}` | Dashboard auth/session | Return one campaign by URL-escaped stable campaign id or run key, using the same campaign shape as `/api/campaigns`; recheck revisions may include a `drift` block with `codebase_changed`, `prior_revision`, `delta_count`, `recheck_reason`, `external[]` (`source`, `kind`, `title`, `url`, `published_at`, `summary`), `external_count`, and `sources_failed`. | `pkg/dashboard/api.go:100` | -| `POST` | `/api/campaigns/{id}/resume` | Owner only | Resume or pick up a campaign. Archived Inception campaigns take a durable campaign lease, restore their saved state and wiki working files; Spek campaigns return the retained run detail plus a CLI status command that reloads state from Spek artifacts. Body may include `{ "surface": "chat"|"contributor"|"cli"|"dashboard" }`; 409 means another user holds the lease. | `pkg/dashboard/api.go:101` | -| `POST` | `/api/campaigns/{id}/release` | Owner only | Release the caller's Inception campaign lease and write a `campaign_release` audit entry so another user can continue it. Run-backed Spektacular campaigns return `409 Conflict`; this endpoint never revokes their run-lifecycle stage leases. | `pkg/dashboard/api.go:102` | -| `POST` | `/api/campaigns/{id}/revise` | Owner only | Create a linked revision campaign (`revision_of`, `revision`) for revisiting shipped or parked Inception/Spek work without overwriting the previous campaign. The new revision is leased to the caller and audit-logged as `campaign_revise`. | `pkg/dashboard/api.go:103` | -| `DELETE` | `/api/campaigns/{id}` | Owner only | Delete a campaign record: removes the archived Inception state and wiki snapshot for the stable campaign id and audit-logs `campaign_delete`. Knowledge-base facts, Jam threads, scaffolded repo files and other revisions in the same chain are kept; deleting the live L1 session clears it. Run-backed Spektacular campaigns return `409 Conflict`; unknown ids `404`. | `pkg/dashboard/api.go:104` | -| `POST` | `/api/campaigns/{id}/recheck` | Owner only | Create an immediate linked Spek recheck revision using the cadence path. Returns `409 Conflict` when a recheck revision is already in flight, `404 Not Found` when recheck is disabled unless `?force=true` is supplied, and records `campaign_recheck`. | `pkg/dashboard/api.go:105` | -| `GET` | `/api/campaigns/{id}/jam` | Dashboard auth/session | Return the per-campaign Jam workspace: section-anchored threads, comments, suggestions, polls, poll decisions, current spec revision and attributed revision history. | `pkg/dashboard/api.go:106` | -| `POST` | `/api/campaigns/{id}/jam` | Read-write role | Record an attributed spec revision for a campaign. Body includes `spec_content`, optional `reason`, and optional agent/model attribution fields. | `pkg/dashboard/api.go:107` | -| `GET` | `/api/campaigns/{id}/jam/threads` | Dashboard auth/session | List async Jam threads anchored to spec sections, including comments and author attribution. | `pkg/dashboard/api.go:108` | -| `POST` | `/api/campaigns/{id}/jam/threads` | Read-write role | Create a section-anchored Jam thread or add a comment to an existing thread. Body includes `section` and `body`, or `thread_id` and `body`. | `pkg/dashboard/api.go:109` | -| `POST` | `/api/campaigns/{id}/jam/agents` | Maintainer only | Invite Spektacular or a configured hive agent into a Jam thread. The agent reply is posted as an attributed thread comment and an open suggestion for human accept/reject; no spec revision is auto-applied. | `pkg/dashboard/api.go:110` | -| `GET` | `/api/campaigns/{id}/jam/suggestions` | Dashboard auth/session | List Jam suggestions with open/accepted/rejected status, proposed text, attribution and applied revision id when accepted. | `pkg/dashboard/api.go:111` | -| `POST` | `/api/campaigns/{id}/jam/suggestions` | Read-write role; maintainer for accept | Create a suggestion (`section`, `proposed_text`) or resolve it with `action: "accept"`/`"reject"` and `suggestion_id`. Accepting records a new attributed spec revision. | `pkg/dashboard/api.go:112` | -| `GET` | `/api/campaigns/{id}/jam/polls` | Dashboard auth/session | List Jam polls, advisory vote tallies and maintainer decisions stored against spec revisions. | `pkg/dashboard/api.go:113` | -| `POST` | `/api/campaigns/{id}/jam/polls` | Read-write role; maintainer for decide | Create polls (`section`, `question`, `options`), cast/update advisory votes (`action: "vote"`), or record a maintainer decision with rationale (`action: "decide"`). | `pkg/dashboard/api.go:114` | -| `GET` | `/api/campaigns/{id}/jam/project-sync` | Dashboard auth/session | Return the campaign's GitHub Projects sync configuration, last published items, last status, and retry guidance for failures. | `pkg/dashboard/api.go:115` | -| `POST` | `/api/campaigns/{id}/jam/project-sync` | Maintainer only | Enable/disable opt-in GitHub Projects sync, publish campaign specs/decisions/derived issues to the linked project, or record inbound project status updates without losing local Jam decisions. | `pkg/dashboard/api.go:116` | -| `GET` | `/api/campaigns/{id}/jam/ws` | Dashboard auth/session | Upgrade to a Jam WebSocket for live participant presence, section focus, and conflict-aware spec co-edit messages. Live edits require read-write role and stale `base_revision_id` values are rejected with a conflict message. | `pkg/dashboard/api.go:117` | | `GET` | `/api/runs/{key}/trace` | Dashboard auth/session | Resolve `Hive-Run`, `Hive-Plan`, and `Hive-Spec` commit trailers for `?sha=...`, returning the linked plan section, spek clause, approval audit record, rationale audit entries, and typed no-linkage results when trailers are missing. | `pkg/dashboard/api.go:94` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index f31ef9698f..92198c6b14 100644 --- a/src/docs/api-reference/inception.md +++ b/src/docs/api-reference/inception.md @@ -5,17 +5,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:448` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:449` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:450` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:451` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:452` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:453` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:454` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:455` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:456` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:457` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:458` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:459` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:460` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:461` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:429` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:430` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:431` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:432` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:433` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:434` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:435` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:436` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:437` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:438` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:439` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:440` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:441` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:442` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index 223bd6ace8..644e4c2244 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -5,38 +5,38 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:384` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:385` | -| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](../public-knowledge-mcp.md)) | `pkg/dashboard/api.go:394` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:386` | -| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:387` | -| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](../knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:388` | -| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:389` | -| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:391` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:395` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:396` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:397` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:398` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:399` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:400` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:401` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:402` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:408` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:409` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:410` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:411` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:412` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:413` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:414` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:415` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:416` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:417` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:418` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:419` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:420` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:421` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:422` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:423` | +| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:365` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:366` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](../public-knowledge-mcp.md)) | `pkg/dashboard/api.go:375` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:367` | +| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:368` | +| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](../knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:369` | +| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:370` | +| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:372` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:376` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:377` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:378` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:379` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:380` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:381` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:382` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:383` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:389` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:390` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:391` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:392` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:393` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:394` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:395` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:396` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:397` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:398` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:399` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:400` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:401` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:402` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:403` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:404` | | `GET` | `/api/config/knowledge/connectors` | Dashboard auth/session | Knowledge connectors config (name, type, layer, scope, env/file auth reference) and registered types | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/connectors` | Owner only | Replace `knowledge.connectors` after validation; inline secrets rejected | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/connectors/status` | Dashboard auth/session | Per-connector status pill, last sync, pages/facts, last error, `running` and the live `progress` block (phase, items_done/items_total, current item, started_at; see [knowledge-connectors.md](../knowledge-connectors.md#api)), plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -46,19 +46,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/knowledge/agent-scopes` | Owner only | Replace `knowledge.agent_scopes` after validating layer and state names; persisted and audited as `config_knowledge_agent_scopes` | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/pipeline` | Owner only | Scalar bead synthesizer, curator, code map and primer settings, plus the read-only engine, vault paths and primer merge strategy ([docs](../settings.md#knowledge)) | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/pipeline` | Owner only | Update those settings after `config.ValidateKnowledgePipeline`; 0 or empty restores the default; the bead synthesizer switch applies at once, the rest after a restart; audited as `config_knowledge_pipeline` | `pkg/dashboard/api.go` | -| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:433` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:434` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:435` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:436` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:437` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:438` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:439` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:440` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:441` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:442` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:443` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:406` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:407` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:414` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:415` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:416` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:418` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:419` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:420` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:421` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:422` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:423` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:424` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:387` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:388` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses, each with a live `progress` block while a sync runs, and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](../knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:25` | | `POST` | `/api/knowledge/publish/sync` | Owner only | Run a publish mirror batch now (202 with publish status; 503 mirror not running, 409 batch in progress) | `pkg/dashboard/api_knowledge_connectors.go:26` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index 0286d324e2..aa50f2970f 100644 --- a/src/docs/api-reference/nous.md +++ b/src/docs/api-reference/nous.md @@ -5,28 +5,28 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:477` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:478` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:479` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:480` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:481` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:482` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:483` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:484` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:485` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:486` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:487` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:488` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:489` | -| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:490` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:491` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:492` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:493` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:494` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:495` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:496` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:497` | -| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:498` | -| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:499` | -| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:500` | -| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:501` | +| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:458` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:459` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:460` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:461` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:462` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:463` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:464` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:465` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:466` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:467` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:468` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:469` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:470` | +| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:471` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:472` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:473` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:474` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:475` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:477` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:478` | +| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:479` | +| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:480` | +| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:481` | +| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:482` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 235afc8dd8..be1cb38008 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -5,29 +5,29 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:329` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:330` | -| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:331` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:310` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:311` | +| `PUT` | `/api/packs/level` | Owner only | Set the ACMM level. Body `{"level": N}` persists and applies the pack; optional `{"release_level_holds": true}` performs a deliberate one-off release of Hive App level-applied `hold` labels for the transition. Level holds are otherwise never auto-released. When the change makes the L6 self-authored merge sweep eligible, the success body adds `self_merge_sweep_active`, `level_changed_at`, `level_holds_pending: [{repo, number, title, url, agent}]`, and `repos: [{repo, auto_merge}]` so the dashboard can show the owner an informational notice and repo toggles. | `pkg/dashboard/api.go:312` | | `POST` | `/api/repos/rescan` | Dashboard auth/session | Re-enumerate watched repositories' open issues/PRs for the dashboard Projects cards. The scan is read-only with respect to agents/governor actions, collapses concurrent requests, and debounces repeated presses for 30 seconds (`repoRescanDebounce`) so the button cannot hammer GitHub | `pkg/dashboard/api.go`, `pkg/dashboard/api_repos_rescan.go` | | `POST` | `/api/repos/pause` | Owner | Quiet ONE repository without stopping the hive: agents stop writing to it and stop being handed work on it, while it keeps its dashboard card and ACMM eval. Body `{"repo": "...", "reason": "..."}` — the repo travels in the body because a `project.repos` entry may be an explicit cross-org `owner/name`. Records who/when/why; `changed: false` marks a no-op re-pause and leaves the original provenance intact; `persisted: false` means the pause is in force but could not be written to config. Rejects a repo outside `project.repos`. See [per-repo agent pause](../repo-pause.md) | `pkg/dashboard/api_repo_pause.go` | | `POST` | `/api/repos/resume` | Owner | Lift a repository's pause. Unlike pause, does not require the repo to be in `project.repos`, so a pause left behind by a removed repo can still be cleared | `pkg/dashboard/api_repo_pause.go` | | `GET` | `/api/repos/pauses` | Dashboard auth/session | Every repo pause with its provenance. Read-only — the same state is already on the repository cards | `pkg/dashboard/api_repo_pause.go` | -| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:346`, `pkg/dashboard/api_repo_hold.go` | +| `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:327`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:350`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:351`, `pkg/dashboard/api_repo_item_decision.go` | -| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:355`, `pkg/dashboard/api_maintainer_notes.go` | -| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:356`, `pkg/dashboard/api_maintainer_notes.go` | -| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:357`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label (shortened with a hash suffix when the plain spelling would exceed GitHub's 50-character label cap, [#17037](https://github.com/hivecommons/hive/issues/17037)); `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. A GitHub failure answers `424` with the step and GitHub's reason — never `502`/`503`, which the hosted Ingress replaces with its generic "hive unavailable" page. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:331`, `pkg/dashboard/api_repo_hold.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:332`, `pkg/dashboard/api_repo_item_decision.go` | +| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:336`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:337`, `pkg/dashboard/api_maintainer_notes.go` | +| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_maintainer_notes.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:360`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:361` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:362` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:563`, `pkg/dashboard/api_repo_item_accept_triage.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:352`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | -| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:364`, `pkg/dashboard/api_acmm_eval.go` | -| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:365` | -| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:366` | -| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:368`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:544`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | +| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_acmm_eval.go` | +| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:346` | +| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:347` | +| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:349`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/design/achievements-2.md b/src/docs/design/achievements-2.md index 43fa863e40..534d2d5c10 100644 --- a/src/docs/design/achievements-2.md +++ b/src/docs/design/achievements-2.md @@ -283,11 +283,10 @@ The shipped implementation uses existing data only: `agent`, `backend`, and `model` from `— hive: agent=… backend=… model=…`; - existing dashboard achievement/dossier/leaderboard records; - swarm player and achievement data from the existing swarm dashboard; -- Spektacular run/campaign data already projected under `/api/runs` and - `/api/campaigns` when present. +- Spektacular run data already projected under `/api/runs`. -The implementation joins the available Spektacular run projection, Campaign Jam -threads/suggestions/polls/revisions, the federation registry's +The implementation joins the available Spektacular run projection, the +federation registry's `active_contributor_names`, and swarm player records. It deliberately does not consume any private chat log or add a new GitHub credential path. @@ -321,7 +320,12 @@ Acceptance criteria: - guardrail review confirms no streaks, timers, random rewards, or pay-to-win rewards were added. -### Phase 2: Spek/Jam role evidence (**shipped**) +### Phase 2: Spek/Jam role evidence (**shipped**, Jam part retired) + +Campaign Jam was retired with inception campaigns, so Jam threads, suggestions, +polls and decisions no longer feed achievements. Run stages still do, and the +Full SDLC Fireteam badge now counts spec, plan and implement coverage by at +least three distinct actors (Jam was the only source of the review role). Join Spektacular run stages and Campaign Jam revisions, accepted suggestions, poll votes, and decisions to Fireteam/Raid roles so a spec can prove planning, diff --git a/src/docs/inception.md b/src/docs/inception.md index 60dc6cd122..12b1961ae0 100644 --- a/src/docs/inception.md +++ b/src/docs/inception.md @@ -11,11 +11,10 @@ see a session watches it live, one person at a time holds the keyboard, and and the [Sessions API](api-reference/sessions.md). The dashboard's old step-by-step Inception wizard was removed; Inception (spek) -replaces it. The **Campaigns** tab that carried the wizard's campaigns and Jam -view over into Inception (spek) has been retired too: start a session for new -inception work, and find Spektacular runs in [Runs](runs.md). The -`/api/campaigns` endpoints, campaign Jam and campaign recheck are being retired -in follow-up changes. +replaces it. Campaigns, their Jam workspace and campaign recheck have been +retired too: start a session for new inception work, and find Spektacular runs +in [Runs](runs.md). See [Retired campaigns export](#retired-campaigns-export) +for where their data went. The rest of this guide covers the ACMM **L1 ("Inception")** workflow behind `/api/inception/*`, which is unchanged and still available to API callers. It @@ -117,8 +116,8 @@ owner role for state-changing calls) drives them: 7. If anything goes wrong, `POST /api/inception/reset` first archives the current state and wiki files as an Inception campaign, then clears the active state and state file under `inception/campaigns//`, so a reset - does not discard completed work. The dashboard no longer lists these - archives. + does not discard completed work. Nothing lists these archives any more; + see [Retired campaigns export](#retired-campaigns-export). Optional wiki-management calls, usable at any point once an inception has produced wiki files: @@ -182,39 +181,38 @@ in `clarify`, produce fact beads in `structure`, emit scaffold content in "Normal Ideation Mode" — general feature/architecture/strategy proposals recorded as advisory beads, unrelated to any specific inception run. -## Campaigns and resume +## Retired campaigns export -The dashboard no longer shows campaigns: the **Campaigns** tab of the -Inception (spek) section was retired in favour of +Campaigns (`/api/campaigns`, the resume/release/revise/delete actions), campaign +Jam and campaign recheck were retired in favour of [Inception (spek) sessions](dashboard-sections/workflow-and-agents.md#inception-spek). -Until the endpoints are retired, `GET /api/campaigns` still lists them for API -callers. Each entry is a unit of work keyed by its stable session/spec id: - -- Archived L1 sessions have type `inception` and engine `Spec Kit`. - `POST /api/campaigns/{id}/resume` takes a durable - campaign lease and restores the saved inception state and wiki working - files, so the API workflow above continues from the archived phase (the - dashboard has no wizard to reopen). A second operator gets - a 409 until the holder calls `POST /api/campaigns/{id}/release` or the lease - expires. -- Spektacular (Spek)-backed runs have type `spektacular`, engine `Spektacular`, and a - `/api/runs/{key}` link. Resume returns the retained run detail and a CLI - status command; Spek itself reloads state from its working files and - speks. -- The list supports `search`/`q`, `repo`, `stage`, `status`, and `owner` - filters and keeps shipped/completed work visible. -- **Revise** calls `POST /api/campaigns/{id}/revise` and creates a new - campaign linked with `revision_of`/`revision`, so changed requirements branch - from the shipped campaign instead of erasing its trail. The list marks the - older campaign with `superseded_by`. -- `DELETE /api/campaigns/{id}` (owner only) removes only - the campaign record: the saved Inception state and the archived wiki - snapshot under `inception/campaigns//`. Knowledge-base facts, Jam - threads, scaffolded repo files and the other revisions in the chain are - kept. Deleting the campaign that is also the live L1 session clears that - session. Run-backed Spektacular campaigns return `409 Conflict`; their rows - come and go with the run. The deletion is audit-logged as - `campaign_delete`. +Their endpoints are gone, and `runs.spektacular.recheck` in `hive.yaml` is +accepted but ignored with a one-line deprecation warning. + +So nothing is lost, the first start after the upgrade writes a one-time, +read-only export when either of these exists: + +- `/data/inception/campaigns/` (archived Inception sessions: each campaign's + `state.json` and wiki snapshot), and +- `campaign-jam.json` in the metrics directory (`data.metrics_dir`, falling back + to `data.logs_dir`, then `data.agents_dir`): Jam threads, suggestions, polls, + decisions and spec revisions. + +The export is `/data/exports/campaigns-.tar.gz`, written with mode +`0600` (directory `0700`). Hive logs its path once, at `WARN`, as +`retired campaigns exported`. Inside the tarball, archive files keep their +`inception/campaigns//...` paths, the Jam store is `campaign-jam.json`, and +`inception/state.json` is included when present. Once any +`campaigns-*.tar.gz` exists in `/data/exports/`, Hive does not write another. + +The original files stay where they are for one release and are never deleted +by this change. Knowledge-base facts recorded by past inception runs (the +`inception-wiki` vault and the knowledge store) are separate from these files +and stay as they are. To read the export: + +```sh +tar -tzf /data/exports/campaigns-*.tar.gz +``` ## Configuring the brainstorm agent diff --git a/src/docs/integrations/spektacular.md b/src/docs/integrations/spektacular.md index dc36f755e6..885d965bae 100644 --- a/src/docs/integrations/spektacular.md +++ b/src/docs/integrations/spektacular.md @@ -121,7 +121,7 @@ Use `pkg/spektacular/testdata/spektacular-fake/spektacular`, which implements th - Auth and secrets: Hive invokes a local binary; any Spektacular backend credentials belong to that tool's own environment, not to Hive's dashboard token. - Rate limits: tune `poll_interval_s`; every active `spec` or `plan` stage is polled at that cadence (`src/pkg/config/runs_config.go:145`). - Failure modes: missing artifacts become typed not-found errors; stale/replaced documents are refused rather than silently rebound; expired leases retry until `max_stage_retries` then escalate (`src/pkg/spektacular/runner.go:300`, `src/pkg/spektacular/runner.go:520`). -- What is exposable: status JSON, plan export JSON, run-stage work items, stage receipts, and campaign projections through `/api/campaigns`. +- What is exposable: status JSON, plan export JSON, run-stage work items and stage receipts. (The `/api/campaigns` projection was retired with inception campaigns.) - What is not exposable: Hive does not open Spektacular files directly, does not provide a generic planning-engine registry, and does not let a third-party engine mutate Hive's leases except through the configured runner boundary. ## Gaps diff --git a/src/docs/runs.md b/src/docs/runs.md index 7d9a1db164..8e3080e574 100644 --- a/src/docs/runs.md +++ b/src/docs/runs.md @@ -174,7 +174,6 @@ See [spektacular.md](spektacular.md) for runner configuration and stage advancement, and [work-sources.md](work-sources.md) for how pending run stages are listed as work items. -Spek campaigns that opt into continuous convergence can mint linked recheck -revisions after `implement` completes. See -[spektacular.md#continuous-convergence](spektacular.md#continuous-convergence) -for the cadence, generation, drift-evidence, and delta-import contract. +Campaign recheck (continuous convergence) was retired with inception +campaigns; see +[spektacular.md#continuous-convergence-retired](spektacular.md#continuous-convergence-retired). diff --git a/src/docs/spektacular.md b/src/docs/spektacular.md index f1cc46ce37..bea6847368 100644 --- a/src/docs/spektacular.md +++ b/src/docs/spektacular.md @@ -10,55 +10,13 @@ The runner is OFF by default. With `runs.spektacular.enabled` unset or `false` Hive never starts a Spek process and every existing lease behaviour is unchanged. -Every retained Spek run is also projected as a campaign under -`GET /api/campaigns` (API only: the dashboard's Campaigns tab was retired in -favour of Inception (spek) sessions, and the run itself is listed in -[Runs](runs.md); the endpoint is being retired in a follow-up change). The campaign id is the stable run/spec key (the same bare -artifact name the status verbs use), the engine is `Spektacular`, and the row -links back to `/api/runs/{key}` when run detail is available. Picking up a -Spek campaign does not copy spek contents into Hive; `POST -/api/campaigns/{id}/resume` returns the retained run projection and a CLI status -command, while Spek reloads the current state from its working files and -spek backend. - -## Jam Sessions - -Each campaign also has a Jam workspace for team interaction around the spec, -backed by `/api/campaigns/{id}/jam` and the `/threads`, `/suggestions`, and -`/polls` subroutes. The dashboard no longer has a Jam view (it lived in the -retired Campaigns tab); use a shared -[Inception (spek) session](dashboard-sections/workflow-and-agents.md#inception-spek) -to work on a spec together. Phase 1 is async: participants with read-write access can anchor -threads and suggestions to spec sections, vote in advisory polls, and resume -the workspace after a restart. Maintainers record poll decisions with a -rationale; accepted suggestions and decisions create attributed spec revisions -with human or agent/model attribution and diffs. - -Live Jam mode upgrades `/api/campaigns/{id}/jam/ws` to a WebSocket so signed-in -participants can see who is present and which section each person is editing. -Live spec edits carry the sender's last seen spec revision; stale edits are -rejected with a conflict message instead of overwriting newer work, so -reconnecting clients can refresh and merge intentionally. - -Maintainers can opt a campaign into GitHub Projects sync through -`POST /api/campaigns/{id}/jam/project-sync`. The -sync publishes the current spec, recorded decisions, and derived suggestion -items to the linked project; inbound project status updates are recorded on the -campaign without rewriting local Jam decisions. Sync failures are kept with -retry guidance in the `project-sync` response so a caller can see what to fix -before trying again. - -Sync posts to `https://api.github.com/graphql` with the hive's `GITHUB_TOKEN`. -`HIVE_JAM_PROJECT_SYNC_URL` overrides the endpoint; an override must use -`https` (plain `http` is accepted only for loopback hosts) and never receives -`GITHUB_TOKEN`. Set `HIVE_JAM_PROJECT_SYNC_TOKEN` to give a custom endpoint its -own bearer token. - -Maintainers can invite Spektacular or another configured hive agent into a Jam -thread. Agent participation is deliberately review-gated: the attributed agent -reply is posted in-thread and any proposed spec text is created as an open -suggestion, but a permitted human maintainer must still accept it before the -spec revision changes. +Retained Spek runs are listed in [Runs](runs.md) (`GET /api/runs` and +`GET /api/runs/{key}`). The old campaign projection (`/api/campaigns`), campaign +Jam and campaign recheck were retired together with inception campaigns in +favour of [Inception (spek) sessions](dashboard-sections/workflow-and-agents.md#inception-spek). +On the first start after the upgrade Hive writes a one-time, read-only export of +any campaign archives and Jam data it finds; see +[Inception: retired campaigns export](inception.md#retired-campaigns-export). ## Enabling it @@ -423,99 +381,14 @@ lists `implement` only after `ApprovePlan` (`POST /api/plans/{id}/approve`) sets `plan_status` to `approved`. A run whose epic already carries a plan is not re-imported. -## Continuous convergence - -Spek campaigns can opt into a scheduler-owned recheck cadence without changing -the one-shot default. The feature is off unless -`runs.spektacular.recheck.enabled: true`; opted-in campaigns use -`runs.spektacular.recheck.default_interval` (default `168h`) unless their -retained campaign record carries `recheck.interval`, and imported delta tasks -are capped by `runs.spektacular.recheck.max_delta_tasks` (default `50`). - -When a completed `implement` campaign is due, or an owner posts -`POST /api/campaigns/{id}/recheck`, Hive creates a linked Spektacular revision -(`revision_of`, `revision`) and starts that revision at the `spec` stage. The -original campaign is never overwritten; the revision is a new generation with -the prior final spec/plan treated as prior artifacts by convention. Manual -requests return `409 Conflict` when another revision is already in flight and -`404 Not Found` when recheck is disabled unless `?force=true` is supplied. - -The recheck follows the same human checkpoints as any Spek run. A final spec -still waits at the spec boundary when that checkpoint is enabled, and a final -plan imports as a draft plan until approval. At final-plan import Hive compares -the revision task list with the prior final plan by normalized task-content -hash. Unchanged tasks reuse the prior logical operation identity and are not -imported again; only new or changed tasks become planner children. If the -codebase and prior plan are unchanged, the delta is empty and Hive creates no -new planner tasks or issues. If the delta exceeds `max_delta_tasks`, Hive -imports the first capped set and records `campaign_recheck_delta_capped`. - -Each revision carries a `drift` evidence block with `codebase_changed`, -`prior_revision`, `delta_count`, and `recheck_reason` (`cadence` or `manual`). -The codebase signal compares the prior recorded head SHA with the current Git -HEAD when available. Outward discovery can add two optional evidence shapes -before the revision's `spec` lease starts: typed release/activity/feed signals -as `drift.external[]`, and exact document snapshots as `drift.drift_source[]`. -Both default to empty and perform no discovery network access unless explicitly -configured. +## Continuous convergence (retired) -```yaml -runs: - spektacular: - recheck: - discovery: - enabled: true - timeout: 30s - max_total_items: 100 - sources: - - {kind: upstream_release, name: kubernetes, url_or_repo: kubernetes/kubernetes, max_items: 10} - - {kind: repo_activity, name: competitor-runtime, url_or_repo: example/runtime, allow_prerelease: true} - - {kind: standards_feed, name: ietf-http, url_or_repo: https://www.ietf.org/archive/id/atom.xml} - - {kind: landscape, name: project-landscape, max_items: 20} - discovery_proxy: http://relay:18443 - egress_allowlist: [api.github.com, www.ietf.org] - sources: - - name: upstream-release-doc - kind: release - url: https://api.github.com/repos/jumppad-labs/spektacular/releases/latest -variables: - security: - http_allowlist: [api.github.com, www.ietf.org] -``` - -Typed findings are recorded on the revision as -`drift.external[] = {source, kind, title, url, published_at, summary}` with -summaries capped at 280 characters, plus `external_count` and -`sources_failed[] = {name, reason}`. A failed source is non-fatal: Hive records -the typed reason and continues with the rest. The same evidence is included in -the `spec` stage assignment prompt as context so the spec generator can decide -what, if anything, belongs in the revised spec; the spec and plan human -checkpoints remain the only approval gates. - -Exact document sources use `runs.spektacular.recheck.sources`. -`discovery_proxy` must be the operator's existing relay egress proxy, with its -normal network policy and trust roots installed. It is required when exact -sources are configured; discovery never falls back to direct access, including -when `NO_PROXY` matches. `egress_allowlist` contains exact DNS hostnames, with -no wildcards or IP literals. Config validation rejects a source outside that -list, even when cadence is disabled, because forced manual rechecks use the -same policy. - -Each exact source declares a unique `name`, a `kind` (`release`, `changelog`, -`repo`, `standards`, or `landscape`), and an exact HTTPS `url`. Source kind -labels provenance; it does not enable crawling or additional API calls. A pass -makes one GET per declared document, at most 16 sources, with a 10-second -request timeout, a 30-second total deadline, and a 32 KiB UTF-8 response cap. -Redirects are refused. No links are followed and no writes are issued. Each -retained snapshot includes its name, kind, URL, SHA-256 and text; failed reads -retain an error instead of claiming no drift. This exact-document path does not -invoke `upstreamwatch`'s multi-page PR and release scanner. - -Campaign list/detail JSON includes -`recheck: {enabled, interval, last_at, next_at, in_flight, last_delta_count, -external_count, sources_failed}`; recheck revisions also include the `drift` -block above. The dashboard no longer renders campaigns (the Campaigns tab was -retired), so read the cadence and signals from the JSON. +Campaign recheck (scheduler-owned recheck revisions, outward discovery and the +`POST /api/campaigns/{id}/recheck` endpoint) was retired with inception +campaigns. `runs.spektacular.recheck` is still accepted in `hive.yaml` so an +existing file keeps loading and validating, but it has no effect and Hive logs a +one-line deprecation warning; remove the block. The design history is in +[ADR-0020](adr/0020-spek-continuous-convergence.md). ## Defensive handling of the open questions diff --git a/src/pkg/campaignexport/campaignexport.go b/src/pkg/campaignexport/campaignexport.go new file mode 100644 index 0000000000..a8362ce1d3 --- /dev/null +++ b/src/pkg/campaignexport/campaignexport.go @@ -0,0 +1,176 @@ +// Package campaignexport writes the one-time, read-only export of retired +// inception campaign data. Inception campaigns, campaign Jam and campaign +// recheck were retired in favour of Inception (spek) sessions; the endpoints +// that read their files are gone, so on the first start after the upgrade +// Hive bundles whatever is still on disk into a tarball an operator can keep. +// +// The export only reads the source files. It never moves or deletes them: +// they stay in place for one release so a rollback still finds them. +package campaignexport + +import ( + "archive/tar" + "compress/gzip" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + // CampaignsDir is the archived-campaign tree, relative to the data dir. + CampaignsDir = "inception/campaigns" + // InceptionStateFile is the live inception state, relative to the data dir. + InceptionStateFile = "inception/state.json" + // JamFileName is the campaign Jam store in the metrics directory. + JamFileName = "campaign-jam.json" + // ExportsDir is where the tarball lands, relative to the data dir. + ExportsDir = "exports" + // exportPrefix and exportSuffix frame campaigns-.tar.gz. + exportPrefix = "campaigns-" + exportSuffix = ".tar.gz" + exportDate = "2006-01-02" + // exportFileMode keeps the tarball readable by the hive user only: it + // carries idea text, Q&A, Jam threads and participant names. + exportFileMode fs.FileMode = 0o600 + // exportDirMode is used when the exports directory has to be created. + exportDirMode fs.FileMode = 0o700 +) + +// JamPath resolves campaign-jam.json the way the retired Jam store did: the +// metrics dir, else the logs dir, else the agents dir, else the working dir. +func JamPath(metricsDir, logsDir, agentsDir string) string { + for _, base := range []string{metricsDir, logsDir, agentsDir} { + if base = strings.TrimSpace(base); base != "" { + return filepath.Join(base, JamFileName) + } + } + return JamFileName +} + +// Export writes /exports/campaigns-.tar.gz when retired +// campaign data exists and no earlier export does. It returns the path it +// wrote, or "" when there was nothing to export or an export already exists +// (so the caller logs the path exactly once across restarts). +// +// The tarball holds inception/campaigns/** (archive state and wiki +// snapshots), inception/state.json when present, and campaign-jam.json. +// Symlinks and other non-regular files are skipped, never followed. +func Export(dataDir, jamPath string, now time.Time) (string, error) { + campaigns := filepath.Join(dataDir, CampaignsDir) + haveCampaigns := isDir(campaigns) + haveJam := jamPath != "" && isRegular(jamPath) + if !haveCampaigns && !haveJam { + return "", nil + } + exports := filepath.Join(dataDir, ExportsDir) + if existing, _ := filepath.Glob(filepath.Join(exports, exportPrefix+"*"+exportSuffix)); len(existing) > 0 { + return "", nil + } + if err := os.MkdirAll(exports, exportDirMode); err != nil { + return "", fmt.Errorf("campaign export: create %s: %w", exports, err) + } + tmp, err := os.CreateTemp(exports, "."+exportPrefix+"*.tmp") + if err != nil { + return "", fmt.Errorf("campaign export: create temp file: %w", err) + } + tmpName := tmp.Name() + err = writeArchive(tmp, dataDir, haveCampaigns, jamPath, haveJam) + if closeErr := tmp.Close(); err == nil { + err = closeErr + } + final := filepath.Join(exports, exportPrefix+now.UTC().Format(exportDate)+exportSuffix) + if err == nil { + err = os.Rename(tmpName, final) + } + if err != nil { + _ = os.Remove(tmpName) + return "", fmt.Errorf("campaign export: %w", err) + } + return final, nil +} + +// writeArchive streams the gzipped tar into f (already created 0600 by +// os.CreateTemp) and syncs it. +func writeArchive(f *os.File, dataDir string, haveCampaigns bool, jamPath string, haveJam bool) error { + if err := f.Chmod(exportFileMode); err != nil { + return err + } + gz := gzip.NewWriter(f) + tw := tar.NewWriter(gz) + var err error + if haveCampaigns { + err = addTree(tw, dataDir, filepath.Join(dataDir, CampaignsDir)) + } + if state := filepath.Join(dataDir, InceptionStateFile); err == nil && isRegular(state) { + err = addFile(tw, state, InceptionStateFile) + } + if err == nil && haveJam { + err = addFile(tw, jamPath, JamFileName) + } + if err == nil { + err = tw.Close() + } + if err == nil { + err = gz.Close() + } + if err == nil { + err = f.Sync() + } + return err +} + +// addTree adds every directory and regular file under root, named relative +// to base with forward slashes. Symlinks, sockets and devices are never +// followed or copied. +func addTree(tw *tar.Writer, base, root string) error { + return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(base, path) // path is always under base + name := filepath.ToSlash(rel) + switch { + case d.IsDir(): + return tw.WriteHeader(&tar.Header{Typeflag: tar.TypeDir, Name: name + "/", Mode: int64(exportDirMode)}) + case d.Type().IsRegular(): + return addFile(tw, path, name) + default: + return nil + } + }) +} + +// addFile copies one regular file into the tar under name. +func addFile(tw *tar.Writer, path, name string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return err + } + if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: name, Mode: int64(exportFileMode), Size: info.Size(), ModTime: info.ModTime()}); err != nil { + return err + } + _, err = io.Copy(tw, f) + return err +} + +func isDir(path string) bool { + info, err := os.Lstat(path) + return err == nil && info.IsDir() +} + +func isRegular(path string) bool { + info, err := os.Lstat(path) + if err != nil { + return false + } + return info.Mode().IsRegular() +} diff --git a/src/pkg/campaignexport/campaignexport_test.go b/src/pkg/campaignexport/campaignexport_test.go new file mode 100644 index 0000000000..91a8061700 --- /dev/null +++ b/src/pkg/campaignexport/campaignexport_test.go @@ -0,0 +1,250 @@ +package campaignexport + +import ( + "archive/tar" + "compress/gzip" + "io" + "os" + "path/filepath" + "sort" + "testing" + "time" +) + +var exportNow = time.Date(2026, 11, 16, 23, 30, 0, 0, time.UTC) + +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func readTar(t *testing.T, path string) map[string]string { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + t.Fatal(err) + } + tr := tar.NewReader(gz) + out := map[string]string{} + for { + hdr, err := tr.Next() + if err == io.EOF { + return out + } + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(tr) + if err != nil { + t.Fatal(err) + } + out[hdr.Name] = string(body) + } +} + +func TestExportBundlesArchivesStateAndJamOnceWithoutTouchingSources(t *testing.T) { + data := t.TempDir() + metrics := t.TempDir() + archive := filepath.Join(data, CampaignsDir, "idea-one", "state.json") + wiki := filepath.Join(data, CampaignsDir, "idea-one", "wiki", "vision.md") + state := filepath.Join(data, InceptionStateFile) + jam := JamPath(metrics, "", "") + writeFile(t, archive, `{"id":"idea-one"}`) + writeFile(t, wiki, "# Vision") + writeFile(t, state, `{"phase":"complete"}`) + writeFile(t, jam, `{"campaigns":{}}`) + if err := os.Symlink(state, filepath.Join(data, CampaignsDir, "idea-one", "link.json")); err != nil { + t.Fatal(err) + } + + path, err := Export(data, jam, exportNow) + if err != nil { + t.Fatalf("Export: %v", err) + } + if want := filepath.Join(data, ExportsDir, "campaigns-2026-11-16.tar.gz"); path != want { + t.Fatalf("path = %q, want %q", path, want) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != exportFileMode { + t.Fatalf("mode = %v, want %v", info.Mode().Perm(), exportFileMode) + } + got := readTar(t, path) + files := map[string]string{} + for name, body := range got { + if name[len(name)-1] != '/' { + files[name] = body + } + } + want := map[string]string{ + "inception/campaigns/idea-one/state.json": `{"id":"idea-one"}`, + "inception/campaigns/idea-one/wiki/vision.md": "# Vision", + InceptionStateFile: `{"phase":"complete"}`, + JamFileName: `{"campaigns":{}}`, + } + if len(files) != len(want) { + names := make([]string, 0, len(files)) + for n := range files { + names = append(names, n) + } + sort.Strings(names) + t.Fatalf("tar files = %v, want %d entries (symlinks must be skipped)", names, len(want)) + } + for name, body := range want { + if files[name] != body { + t.Fatalf("%s = %q, want %q", name, files[name], body) + } + } + for _, src := range []string{archive, wiki, state, jam} { + if _, err := os.Stat(src); err != nil { + t.Fatalf("source %s must stay in place: %v", src, err) + } + } + + again, err := Export(data, jam, exportNow.Add(24*time.Hour)) + if err != nil || again != "" { + t.Fatalf("second Export = %q, %v; want no new export", again, err) + } + leftovers, _ := filepath.Glob(filepath.Join(data, ExportsDir, ".*")) + if len(leftovers) != 0 { + t.Fatalf("temp files left behind: %v", leftovers) + } +} + +func TestExportJamOnly(t *testing.T) { + data := t.TempDir() + jam := filepath.Join(t.TempDir(), JamFileName) + writeFile(t, jam, `{"campaigns":{"a":{}}}`) + path, err := Export(data, jam, exportNow) + if err != nil || path == "" { + t.Fatalf("Export = %q, %v", path, err) + } + if got := readTar(t, path); len(got) != 1 || got[JamFileName] != `{"campaigns":{"a":{}}}` { + t.Fatalf("tar = %v", got) + } +} + +func TestExportNothingToDo(t *testing.T) { + data := t.TempDir() + path, err := Export(data, filepath.Join(data, JamFileName), exportNow) + if err != nil || path != "" { + t.Fatalf("Export = %q, %v; want nothing", path, err) + } + if _, err := os.Stat(filepath.Join(data, ExportsDir)); !os.IsNotExist(err) { + t.Fatalf("exports dir must not be created when there is nothing to export: %v", err) + } + if path, err := Export(data, "", exportNow); err != nil || path != "" { + t.Fatalf("Export with no jam path = %q, %v", path, err) + } +} + +func TestJamPathFallbacks(t *testing.T) { + for _, c := range []struct{ metrics, logs, agents, want string }{ + {"/m", "/l", "/a", "/m/" + JamFileName}, + {" ", "/l", "/a", "/l/" + JamFileName}, + {"", "", "/a", "/a/" + JamFileName}, + {"", "", "", JamFileName}, + } { + if got := JamPath(c.metrics, c.logs, c.agents); got != filepath.FromSlash(c.want) { + t.Fatalf("JamPath(%q,%q,%q) = %q, want %q", c.metrics, c.logs, c.agents, got, c.want) + } + } +} + +func skipIfRoot(t *testing.T) { + t.Helper() + if os.Geteuid() == 0 { + t.Skip("permission errors cannot be provoked as root") + } +} + +// assertNoExport fails when a tarball or a leftover temp file exists. +func assertNoExport(t *testing.T, data string) { + t.Helper() + left, _ := filepath.Glob(filepath.Join(data, ExportsDir, "*")) + hidden, _ := filepath.Glob(filepath.Join(data, ExportsDir, ".*")) + if len(left)+len(hidden) != 0 { + t.Fatalf("a failed export must leave nothing behind: %v %v", left, hidden) + } +} + +func TestExportErrorsLeaveSourcesAndNoPartialFile(t *testing.T) { + t.Run("exports path is a file", func(t *testing.T) { + data := t.TempDir() + writeFile(t, filepath.Join(data, CampaignsDir, "a", "state.json"), "{}") + writeFile(t, filepath.Join(data, ExportsDir), "not a dir") + if path, err := Export(data, "", exportNow); err == nil || path != "" { + t.Fatalf("Export = %q, %v; want an error", path, err) + } + }) + t.Run("exports dir not writable", func(t *testing.T) { + skipIfRoot(t) + data := t.TempDir() + writeFile(t, filepath.Join(data, CampaignsDir, "a", "state.json"), "{}") + exports := filepath.Join(data, ExportsDir) + if err := os.MkdirAll(exports, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(exports, 0o700) }) + if path, err := Export(data, "", exportNow); err == nil || path != "" { + t.Fatalf("Export = %q, %v; want an error", path, err) + } + }) + t.Run("unreadable archive file", func(t *testing.T) { + skipIfRoot(t) + data := t.TempDir() + src := filepath.Join(data, CampaignsDir, "a", "state.json") + writeFile(t, src, "{}") + if err := os.Chmod(src, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(src, 0o600) }) + if path, err := Export(data, "", exportNow); err == nil || path != "" { + t.Fatalf("Export = %q, %v; want an error", path, err) + } + assertNoExport(t, data) + if _, err := os.Lstat(src); err != nil { + t.Fatalf("source must stay: %v", err) + } + }) + t.Run("unreadable archive dir", func(t *testing.T) { + skipIfRoot(t) + data := t.TempDir() + dir := filepath.Join(data, CampaignsDir, "a") + writeFile(t, filepath.Join(dir, "state.json"), "{}") + if err := os.Chmod(dir, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + if path, err := Export(data, "", exportNow); err == nil || path != "" { + t.Fatalf("Export = %q, %v; want an error", path, err) + } + assertNoExport(t, data) + }) + t.Run("unreadable jam file", func(t *testing.T) { + skipIfRoot(t) + data := t.TempDir() + jam := filepath.Join(t.TempDir(), JamFileName) + writeFile(t, jam, "{}") + if err := os.Chmod(jam, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(jam, 0o600) }) + if path, err := Export(data, jam, exportNow); err == nil || path != "" { + t.Fatalf("Export = %q, %v; want an error", path, err) + } + assertNoExport(t, data) + }) +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 80a3e83bf0..5b0950dfe5 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -406,6 +406,13 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { c.Governor.mergeTrainStallWarnSet = true } } + // runs.spektacular.recheck is retired: accept the block, ignore it, and + // let WarnDeprecatedSpektacularRecheck say so once. + if runs := mappingValueNode(&node, "runs"); runs != nil { + if spek := mappingValueNode(runs, "spektacular"); spek != nil && mappingValueNode(spek, "recheck") != nil { + c.Runs.Spektacular.deprecatedRecheckSet = true + } + } return nil } @@ -6704,6 +6711,7 @@ func (c *Config) applyDefaults() { // value, after which this is a no-op for the life of the hive. c.MigrateReviewFixHumanPRs() c.WarnDeprecatedReviewAllAuthors() + c.WarnDeprecatedSpektacularRecheck() // Repo targets are built as org + "/" + repo, so an entry that already // carries the org resolves to "org/org/repo" and every agent fails. Strip a // matching org prefix off both primary_repo and every repos entry on load. diff --git a/src/pkg/config/runs_config.go b/src/pkg/config/runs_config.go index c75695fc1f..cf7260b9c4 100644 --- a/src/pkg/config/runs_config.go +++ b/src/pkg/config/runs_config.go @@ -1,7 +1,9 @@ package config import ( + "log" "strings" + "sync" "time" ) @@ -23,18 +25,6 @@ const ( // DefaultSpektacularPollS is how often, in seconds, the runner calls the // status verb for each active stage lease. DefaultSpektacularPollS = 30 - // DefaultSpektacularRecheckInterval is the default continuous convergence - // cadence for campaigns that opt in without a per-campaign override. - DefaultSpektacularRecheckInterval = 168 * time.Hour - // DefaultSpektacularMaxDeltaTasks caps how many changed/new plan tasks a - // recheck imports into the planner in one generation. - DefaultSpektacularMaxDeltaTasks = 50 - // DefaultSpektacularDiscoveryTimeoutS bounds each outward discovery pass. - DefaultSpektacularDiscoveryTimeoutS = 30 - // DefaultSpektacularDiscoveryMaxItems caps one configured discovery source. - DefaultSpektacularDiscoveryMaxItems = 20 - // DefaultSpektacularDiscoveryMaxTotalItems caps all discovery evidence for a revision. - DefaultSpektacularDiscoveryMaxTotalItems = 100 // DefaultRunsWaitTimeoutSeconds is how long a run checkpoint may wait for // owner approval before escalation. It also floors how far a held plan @@ -300,47 +290,10 @@ type SpektacularConfig struct { // PollIntervalS is the seconds between status calls per active stage. // Zero or negative means DefaultSpektacularPollS. PollIntervalS int `yaml:"poll_interval_s,omitempty" json:"poll_interval_s,omitempty"` - // Recheck configures continuous convergence revisions. Default off. - Recheck SpektacularRecheckConfig `yaml:"recheck,omitempty" json:"recheck,omitempty"` -} - -// SpektacularRecheckConfig controls cadence-driven Spek revision campaigns. -type SpektacularRecheckConfig struct { - // Sources is an opt-in list of exact discovery documents; empty disables all discovery I/O. - Sources []SpektacularDiscoverySource `yaml:"sources,omitempty" json:"sources,omitempty"` - // DiscoveryProxy is the relay egress proxy. Direct network fallback is forbidden. - DiscoveryProxy string `yaml:"discovery_proxy,omitempty" json:"discovery_proxy,omitempty"` - // EgressAllowlist contains exact HTTPS hostnames permitted for discovery. - EgressAllowlist []string `yaml:"egress_allowlist,omitempty" json:"egress_allowlist,omitempty"` - // Enabled turns scheduler-owned recheck cadence on. Manual recheck requires - // this too unless the request supplies force=true. - Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` - // DefaultInterval is the cadence for opted-in campaigns without their own - // interval. Zero means DefaultSpektacularRecheckInterval. - DefaultInterval time.Duration `yaml:"default_interval,omitempty" json:"default_interval,omitempty"` - // MaxDeltaTasks caps imported changed/new tasks. Zero or negative means - // DefaultSpektacularMaxDeltaTasks. - MaxDeltaTasks int `yaml:"max_delta_tasks,omitempty" json:"max_delta_tasks,omitempty"` - // Discovery configures opt-in outward evidence gathered before recheck spec. - Discovery SpektacularRecheckDiscoveryConfig `yaml:"discovery,omitempty" json:"discovery,omitempty"` -} - -// SpektacularRecheckDiscoveryConfig is the bounded, declared-source-only -// outward discovery step for recheck spec revisions. -type SpektacularRecheckDiscoveryConfig struct { - Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` - Sources []SpektacularRecheckDiscoverySource `yaml:"sources,omitempty" json:"sources,omitempty"` - Timeout time.Duration `yaml:"timeout,omitempty" json:"timeout,omitempty"` - MaxTotalItems int `yaml:"max_total_items,omitempty" json:"max_total_items,omitempty"` -} - -// SpektacularRecheckDiscoverySource declares one operator-approved source. -type SpektacularRecheckDiscoverySource struct { - Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` - Name string `yaml:"name,omitempty" json:"name,omitempty"` - URLOrRepo string `yaml:"url_or_repo,omitempty" json:"url_or_repo,omitempty"` - AllowPrerelease bool `yaml:"allow_prerelease,omitempty" json:"allow_prerelease,omitempty"` - MaxItems int `yaml:"max_items,omitempty" json:"max_items,omitempty"` + // deprecatedRecheckSet records that hive.yaml still carries the retired + // runs.spektacular.recheck block. The block is accepted and ignored; see + // WarnDeprecatedSpektacularRecheck. + deprecatedRecheckSet bool } // MaxStageRetriesOrDefault returns the configured retry budget or the default. @@ -399,39 +352,21 @@ func (s SpektacularConfig) PollInterval() time.Duration { return time.Duration(s.PollIntervalS) * time.Second } -// DefaultRecheckInterval returns the configured continuous convergence cadence. -func (s SpektacularConfig) DefaultRecheckInterval() time.Duration { - if s.Recheck.DefaultInterval <= 0 { - return DefaultSpektacularRecheckInterval - } - return s.Recheck.DefaultInterval -} - -// MaxDeltaTasks returns the configured cap for new/changed recheck tasks. -func (s SpektacularConfig) MaxDeltaTasks() int { - if s.Recheck.MaxDeltaTasks <= 0 { - return DefaultSpektacularMaxDeltaTasks - } - return s.Recheck.MaxDeltaTasks -} - -func (s SpektacularConfig) DiscoveryTimeout() time.Duration { - if s.Recheck.Discovery.Timeout <= 0 { - return time.Duration(DefaultSpektacularDiscoveryTimeoutS) * time.Second - } - return s.Recheck.Discovery.Timeout -} - -func (s SpektacularConfig) DiscoveryMaxTotalItems() int { - if s.Recheck.Discovery.MaxTotalItems <= 0 { - return DefaultSpektacularDiscoveryMaxTotalItems - } - return s.Recheck.Discovery.MaxTotalItems -} +// spektacularRecheckDeprecationLogOnce keeps the deprecation notice to one +// line per process across boot and every reload. +var spektacularRecheckDeprecationLogOnce sync.Once -func (s SpektacularRecheckDiscoverySource) EffectiveMaxItems() int { - if s.MaxItems <= 0 { - return DefaultSpektacularDiscoveryMaxItems +// WarnDeprecatedSpektacularRecheck logs once when hive.yaml still carries +// runs.spektacular.recheck. Campaign recheck (continuous convergence) was +// retired with inception campaigns; the block is still accepted on load so +// an existing hive.yaml keeps loading, it never fails validation, and it has +// no effect. Returns true when the block is present. +func (c *Config) WarnDeprecatedSpektacularRecheck() bool { + if c == nil || !c.Runs.Spektacular.deprecatedRecheckSet { + return false } - return s.MaxItems + spektacularRecheckDeprecationLogOnce.Do(func() { + log.Printf("[config] runs.spektacular.recheck is deprecated and has no effect: campaign recheck was retired with inception campaigns. Remove it from hive.yaml.") + }) + return true } diff --git a/src/pkg/config/runs_config_test.go b/src/pkg/config/runs_config_test.go index d88d076100..2e59844329 100644 --- a/src/pkg/config/runs_config_test.go +++ b/src/pkg/config/runs_config_test.go @@ -19,19 +19,10 @@ func TestRunsConfigDefaults(t *testing.T) { if got := r.Spektacular.PollInterval(); got != time.Duration(DefaultSpektacularPollS)*time.Second { t.Fatalf("PollInterval() = %s, want %ds", got, DefaultSpektacularPollS) } - if r.Spektacular.Recheck.Enabled { - t.Fatal("spektacular recheck must be off by default") - } - if got := r.Spektacular.DefaultRecheckInterval(); got != DefaultSpektacularRecheckInterval { - t.Fatalf("DefaultRecheckInterval() = %s, want %s", got, DefaultSpektacularRecheckInterval) - } - if got := r.Spektacular.MaxDeltaTasks(); got != DefaultSpektacularMaxDeltaTasks { - t.Fatalf("MaxDeltaTasks() = %d, want %d", got, DefaultSpektacularMaxDeltaTasks) - } } func TestRunsConfigOverrides(t *testing.T) { - r := RunsConfig{MaxStageRetries: 5, Spektacular: SpektacularConfig{Enabled: true, Binary: " /opt/bin/spektacular ", PollIntervalS: 7, Recheck: SpektacularRecheckConfig{Enabled: true, DefaultInterval: 24 * time.Hour, MaxDeltaTasks: 7}}} + r := RunsConfig{MaxStageRetries: 5, Spektacular: SpektacularConfig{Enabled: true, Binary: " /opt/bin/spektacular ", PollIntervalS: 7}} if got := r.MaxStageRetriesOrDefault(); got != 5 { t.Fatalf("MaxStageRetriesOrDefault() = %d, want 5", got) } @@ -41,12 +32,6 @@ func TestRunsConfigOverrides(t *testing.T) { if got := r.Spektacular.PollInterval(); got != 7*time.Second { t.Fatalf("PollInterval() = %s, want 7s", got) } - if got := r.Spektacular.DefaultRecheckInterval(); got != 24*time.Hour { - t.Fatalf("DefaultRecheckInterval() = %s, want 24h", got) - } - if got := r.Spektacular.MaxDeltaTasks(); got != 7 { - t.Fatalf("MaxDeltaTasks() = %d, want 7", got) - } neg := RunsConfig{MaxStageRetries: -1, Spektacular: SpektacularConfig{PollIntervalS: -3}} if neg.MaxStageRetriesOrDefault() != DefaultMaxStageRetries || neg.Spektacular.PollInterval() != time.Duration(DefaultSpektacularPollS)*time.Second { t.Fatal("negative values must fall back to defaults") diff --git a/src/pkg/config/spektacular_discovery.go b/src/pkg/config/spektacular_discovery.go deleted file mode 100644 index c3269c6920..0000000000 --- a/src/pkg/config/spektacular_discovery.go +++ /dev/null @@ -1,59 +0,0 @@ -package config - -import ( - "fmt" - "net" - "net/url" - "strings" -) - -// SpektacularDiscoverySource declares one document, never a crawl seed. -// Repo/standards/landscape sources use the same exact-document boundary. -type SpektacularDiscoverySource struct { - Name string `yaml:"name" json:"name"` - Kind string `yaml:"kind" json:"kind"` - URL string `yaml:"url" json:"url"` -} - -// ValidateDiscovery fails closed even when cadence is disabled: manual forced -// rechecks must obey the same egress policy. An empty source list is inert. -func (r SpektacularRecheckConfig) ValidateDiscovery() error { - if len(r.Sources) == 0 { - return nil - } - fail := func(reason string) error { return fmt.Errorf("runs.spektacular.recheck.sources: %s", reason) } - if len(r.Sources) > 16 { - return fail("at most 16 sources are permitted") - } - proxy, err := url.Parse(r.DiscoveryProxy) - if err != nil || proxy.Hostname() == "" || (proxy.Scheme != "http" && proxy.Scheme != "https") || proxy.User != nil || proxy.RawQuery != "" || proxy.Fragment != "" || (proxy.Path != "" && proxy.Path != "/") { - return fail("discovery_proxy must name the HTTP(S) relay proxy without credentials, path, query or fragment") - } - allowed := map[string]bool{} - for _, host := range r.EgressAllowlist { - if host == "" || host != strings.ToLower(host) || strings.ContainsAny(host, "/:*@?# ") || net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") { - return fail("egress_allowlist must contain exact DNS hostnames") - } - allowed[host] = true - } - names := map[string]bool{} - for _, source := range r.Sources { - if strings.TrimSpace(source.Name) == "" || len(source.Name) > 128 || names[source.Name] { - return fail("source names must be unique, nonempty and at most 128 bytes") - } - names[source.Name] = true - switch source.Kind { - case "release", "changelog", "repo", "standards", "landscape": - default: - return fail("unknown source kind") - } - u, err := url.Parse(source.URL) - if err != nil || len(source.URL) > 2048 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") { - return fail("sources must be exact HTTPS URLs without credentials or fragments") - } - if !allowed[u.Hostname()] { - return fail("source " + source.Name + " is outside the egress allow-list") - } - } - return nil -} diff --git a/src/pkg/config/spektacular_discovery_test.go b/src/pkg/config/spektacular_discovery_test.go deleted file mode 100644 index 24f7390347..0000000000 --- a/src/pkg/config/spektacular_discovery_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package config - -import ( - "strings" - "testing" -) - -func TestDiscoveryValidation(t *testing.T) { - valid := func() SpektacularRecheckConfig { - return SpektacularRecheckConfig{ - DiscoveryProxy: "http://relay:18443", EgressAllowlist: []string{"api.github.com"}, - Sources: []SpektacularDiscoverySource{{Name: "upstream", Kind: "release", URL: "https://api.github.com/repos/acme/tool/releases/latest"}}, - } - } - if err := (SpektacularRecheckConfig{}).ValidateDiscovery(); err != nil { - t.Fatal(err) - } - if err := valid().ValidateDiscovery(); err != nil { - t.Fatal(err) - } - for _, address := range []string{"https://evil.example/news", "https://api.github.com.evil.example/news", "https://api.github.com@evil.example/news", "http://api.github.com/news", "https://api.github.com:444/news", "https://api.github.com/news#fragment"} { - t.Run(address, func(t *testing.T) { - cfg := valid() - cfg.Sources[0].URL = address - if cfg.ValidateDiscovery() == nil { - t.Fatal("unsafe source accepted") - } - }) - } - cfg := valid() - cfg.DiscoveryProxy = "" - if cfg.ValidateDiscovery() == nil { - t.Fatal("direct fallback accepted") - } - cfg = valid() - cfg.EgressAllowlist = []string{"*.github.com"} - if cfg.ValidateDiscovery() == nil { - t.Fatal("wildcard accepted") - } - cfg = valid() - cfg.Sources = append(cfg.Sources, cfg.Sources[0]) - if cfg.ValidateDiscovery() == nil { - t.Fatal("duplicate accepted") - } - cfg = valid() - cfg.Sources[0].Kind = "crawl" - if cfg.ValidateDiscovery() == nil { - t.Fatal("crawl accepted") - } - // Exercise the actual configuration entry point, with cadence still off. - c := Config{} - c.Project.Org = "acme" - c.GitHub.Token = "test" - c.Runs.Spektacular.Recheck = valid() - c.Runs.Spektacular.Recheck.Sources[0].URL = "https://outside.example/news" - if err := c.ValidateWithOptions(ValidateOptions{}); err == nil || !strings.Contains(err.Error(), "outside the egress allow-list") { - t.Fatalf("validation = %v", err) - } -} diff --git a/src/pkg/config/spektacular_recheck_deprecated_test.go b/src/pkg/config/spektacular_recheck_deprecated_test.go new file mode 100644 index 0000000000..ab18242ddf --- /dev/null +++ b/src/pkg/config/spektacular_recheck_deprecated_test.go @@ -0,0 +1,52 @@ +package config + +import ( + "testing" + + "gopkg.in/yaml.v3" +) + +// TestSpektacularRecheckBlockIsAcceptedAndIgnored pins the retirement of +// campaign recheck: an existing hive.yaml that still carries +// runs.spektacular.recheck (even with sources the old validator rejected) +// keeps loading, keeps validating, and is reported as deprecated. +func TestSpektacularRecheckBlockIsAcceptedAndIgnored(t *testing.T) { + const withRecheck = ` +runs: + spektacular: + enabled: true + recheck: + enabled: true + default_interval: 72h + max_delta_tasks: 5 + discovery_proxy: "" + sources: + - {name: outside, kind: release, url: "https://outside.example/news"} + discovery: + enabled: true + sources: + - {kind: search_engine, name: bad, url_or_repo: "https://blocked.example.com/feed.xml"} +` + var c Config + if err := yaml.Unmarshal([]byte(withRecheck), &c); err != nil { + t.Fatalf("hive.yaml with the retired recheck block must load: %v", err) + } + if !c.Runs.Spektacular.Enabled { + t.Fatal("sibling runs.spektacular keys must still decode") + } + if !c.WarnDeprecatedSpektacularRecheck() { + t.Fatal("a recheck block must be reported as deprecated") + } + + var plain Config + if err := yaml.Unmarshal([]byte("runs:\n spektacular:\n enabled: true\n"), &plain); err != nil { + t.Fatalf("load: %v", err) + } + if plain.WarnDeprecatedSpektacularRecheck() { + t.Fatal("no recheck block must not be reported as deprecated") + } + var nilCfg *Config + if nilCfg.WarnDeprecatedSpektacularRecheck() { + t.Fatal("nil config must not report deprecation") + } +} diff --git a/src/pkg/config/spektacular_recheck_discovery_test.go b/src/pkg/config/spektacular_recheck_discovery_test.go deleted file mode 100644 index 2f8208099f..0000000000 --- a/src/pkg/config/spektacular_recheck_discovery_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package config - -import ( - "strings" - "testing" - "time" -) - -func TestSpektacularRecheckDiscoveryDefaults(t *testing.T) { - var cfg SpektacularConfig - if got := cfg.DiscoveryTimeout(); got != 30*time.Second { - t.Fatalf("DiscoveryTimeout = %s, want 30s", got) - } - if got := cfg.DiscoveryMaxTotalItems(); got != 100 { - t.Fatalf("DiscoveryMaxTotalItems = %d, want 100", got) - } - if got := (SpektacularRecheckDiscoverySource{}).EffectiveMaxItems(); got != 20 { - t.Fatalf("EffectiveMaxItems = %d, want 20", got) - } -} - -func TestValidateSpektacularRecheckDiscoveryRejectsBadKind(t *testing.T) { - cfg := Config{ - Project: ProjectConfig{Org: "org"}, - GitHub: GitHubConfig{Token: "x"}, - AgentRuntimeConfig: AgentRuntimeConfig{ - Agents: map[string]AgentConfig{"scanner": {Backend: "claude"}}, - }, - } - cfg.Runs.Spektacular.Recheck.Discovery = SpektacularRecheckDiscoveryConfig{ - Enabled: true, - Sources: []SpektacularRecheckDiscoverySource{{Kind: "search_engine", Name: "bad", URLOrRepo: "https://example.com/feed.xml"}}, - } - err := cfg.validate() - if err == nil || !strings.Contains(err.Error(), "invalid kind") { - t.Fatalf("validate() = %v, want invalid kind", err) - } -} - -func TestValidateSpektacularRecheckDiscoveryRejectsDisallowedHost(t *testing.T) { - cfg := Config{ - Project: ProjectConfig{Org: "org"}, - GitHub: GitHubConfig{Token: "x"}, - AgentRuntimeConfig: AgentRuntimeConfig{ - Agents: map[string]AgentConfig{"scanner": {Backend: "claude"}}, - }, - } - cfg.Variables.Security.HTTPAllowlist = []string{"allowed.example.com"} - cfg.Runs.Spektacular.Recheck.Discovery = SpektacularRecheckDiscoveryConfig{ - Enabled: true, - Sources: []SpektacularRecheckDiscoverySource{{Kind: "standards_feed", Name: "ietf", URLOrRepo: "https://blocked.example.com/feed.xml"}}, - } - err := cfg.validate() - if err == nil || !strings.Contains(err.Error(), "blocked.example.com") || !strings.Contains(err.Error(), "http_allowlist") { - t.Fatalf("validate() = %v, want host allowlist error", err) - } -} - -func TestValidateSpektacularRecheckDiscoveryAcceptsAllowlistedSources(t *testing.T) { - cfg := Config{ - Project: ProjectConfig{Org: "org"}, - GitHub: GitHubConfig{Token: "x"}, - AgentRuntimeConfig: AgentRuntimeConfig{ - Agents: map[string]AgentConfig{"scanner": {Backend: "claude"}}, - }, - } - cfg.Variables.Security.HTTPAllowlist = []string{"api.github.com", "standards.example.com"} - cfg.Runs.Spektacular.Recheck.Discovery = SpektacularRecheckDiscoveryConfig{ - Enabled: true, - Sources: []SpektacularRecheckDiscoverySource{ - {Kind: "upstream_release", Name: "up", URLOrRepo: "owner/repo"}, - {Kind: "repo_activity", Name: "activity", URLOrRepo: "owner/other"}, - {Kind: "standards_feed", Name: "feed", URLOrRepo: "https://standards.example.com/feed.xml"}, - {Kind: "landscape", Name: "landscape"}, - }, - } - if err := cfg.validate(); err != nil { - t.Fatalf("validate() = %v, want nil", err) - } -} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index b0a77ed986..ac2e1ecd62 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -729,11 +729,7 @@ "clarity_gate": {}, "prior_art": {} }, - "spektacular": { - "recheck": { - "discovery": {} - } - }, + "spektacular": {}, "external": { "flue": { "enabled": false diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index b0f769d37e..6ecaceddf6 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -19,69 +19,6 @@ func (c *Config) Validate() error { return c.ValidateWithOptions(ValidateOptions{RequireAgents: true}) } -func (c *Config) validateSpektacularRecheckDiscovery() error { - d := c.Runs.Spektacular.Recheck.Discovery - if !d.Enabled && len(d.Sources) == 0 { - return nil - } - allowedKinds := map[string]bool{ - "upstream_release": true, - "repo_activity": true, - "standards_feed": true, - "landscape": true, - } - for i, src := range d.Sources { - kind := strings.TrimSpace(src.Kind) - if !allowedKinds[kind] { - return fmt.Errorf("runs.spektacular.recheck.discovery.sources[%d]: invalid kind %q (must be upstream_release, repo_activity, standards_feed, or landscape)", i, src.Kind) - } - if strings.TrimSpace(src.Name) == "" { - return fmt.Errorf("runs.spektacular.recheck.discovery.sources[%d]: name is required", i) - } - if kind != "landscape" && strings.TrimSpace(src.URLOrRepo) == "" { - return fmt.Errorf("runs.spektacular.recheck.discovery.sources[%d]: url_or_repo is required", i) - } - for _, host := range discoverySourceHosts(kind, src.URLOrRepo) { - if !hostAllowedByHTTPList(host, c.Variables.Security.HTTPAllowlist) { - return fmt.Errorf("runs.spektacular.recheck.discovery.sources[%d]: host %q is not covered by variables.security.http_allowlist", i, host) - } - } - } - return nil -} - -func discoverySourceHosts(kind, value string) []string { - value = strings.TrimSpace(value) - switch kind { - case "upstream_release", "repo_activity": - return []string{"api.github.com"} - case "standards_feed": - u, err := url.Parse(value) - if err != nil || u.Hostname() == "" { - return []string{value} - } - return []string{strings.ToLower(u.Hostname())} - case "landscape": - return []string{"api.github.com"} - default: - return nil - } -} - -func hostAllowedByHTTPList(host string, allowlist []string) bool { - host = strings.ToLower(strings.TrimSpace(host)) - if host == "" { - return false - } - for _, allowed := range allowlist { - allowed = strings.ToLower(strings.TrimSpace(allowed)) - if allowed == host || allowed == "*" { - return true - } - } - return false -} - func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.IntegrationOrchestration.Validate(); err != nil { return err @@ -198,9 +135,6 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.validateGitHubActivityNotifications(); err != nil { return err } - if err := c.Runs.Spektacular.Recheck.ValidateDiscovery(); err != nil { - return err - } if err := c.validateUpstreamWatch(); err != nil { return err } @@ -226,9 +160,6 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := ValidateKnowledgeAgentScopes(c.Knowledge.AgentScopes); err != nil { return err } - if err := c.validateSpektacularRecheckDiscovery(); err != nil { - return err - } if err := c.AutoMerge.ValidateHumanMergePinOnly(); err != nil { return err } diff --git a/src/pkg/dashboard/achievements2.go b/src/pkg/dashboard/achievements2.go index 8174799281..392c6be842 100644 --- a/src/pkg/dashboard/achievements2.go +++ b/src/pkg/dashboard/achievements2.go @@ -68,7 +68,6 @@ type ContributorAbuseAnnotation struct { type achievement2Inputs struct { Activity []ActivityEntry Hives []ContributorHiveRel - JamStates []CampaignJamState Runs []Run SwarmPlayers []SwarmPlayer LocalHiveID string @@ -161,7 +160,7 @@ func buildAchievements2WithInputs(p *ContributorProfile, inputs achievement2Inpu add("reciprocal-trust", achievementTierDual, achievementTrackTeamwork, "Reciprocal Trust", "Work with the same collaborator more than once.", stats.maxOccasions >= achievementReciprocalOccasionMinCount, "profile.collaborators.occasions"), add("cross-hive-neighbor", achievementTierDual, achievementTrackTeamwork, "Cross-Hive Neighbor", "Contribute to another registered hive.", stats.crossHives >= 1, "federation.active_contributor_names"), add("commons-regular", achievementTierFireteam, achievementTrackTeamwork, "Commons Regular", "Show up on two or more hives in the Commons registry.", stats.crossHives >= achievementCrossHiveRegularThreshold, "federation.active_contributor_names"), - add("full-sdlc-fireteam", achievementTierFireteam, achievementTrackTeamwork, "Full SDLC Fireteam", "Cover a real spec/plan/implement/review SDLC unit with at least three distinct actors.", stats.fireteamUnits >= 1, "spektacular/jam/run roles"), + add("full-sdlc-fireteam", achievementTierFireteam, achievementTrackTeamwork, "Full SDLC Fireteam", "Cover a real spec/plan/implement SDLC unit with at least three distinct actors.", stats.fireteamUnits >= 1, "spektacular/run roles"), add("spec-sequence", achievementTierRaid, achievementTrackTeamwork, "Spec Sequence", "Participate in multiple spec-linked units or swarm speks.", stats.specSequenceUnits >= achievementSpecSequenceThreshold || stats.swarmSpeks >= achievementSpecSequenceThreshold, "spektacular/jam/swarm"), add("six-person-swarm", achievementTierRaid, achievementTrackTeamwork, "Six-Person Swarm", "Work with five distinct collaborators or join a qualifying swarm.", stats.collaborators >= achievementRaidCollaborators || stats.raidUnits >= 1, "profile.collaborators/swarm.players"), add("raid-clear", achievementTierRaid, achievementTrackTeamwork, "Raid Clear", "Clear a swarm or multi-spec sequence with SDLC evidence.", stats.raidUnits >= 1 || (stats.fireteamUnits >= 1 && stats.specSequenceUnits >= achievementSpecSequenceThreshold), "swarm/spektacular"), @@ -292,7 +291,7 @@ func (u sdlcRoleUnit) includes(actor string) bool { } func (u sdlcRoleUnit) fullCoverage() bool { - if len(u.roles["spec"]) == 0 || len(u.roles["plan"]) == 0 || len(u.roles["implement"]) == 0 || len(u.roles["review"]) == 0 { + if len(u.roles["spec"]) == 0 || len(u.roles["plan"]) == 0 || len(u.roles["implement"]) == 0 { return false } return len(u.actorNames()) >= 3 @@ -310,33 +309,6 @@ func sdlcRoleStatsForUser(username string, inputs achievement2Inputs) (fireteamU } return units[key] } - for _, jam := range inputs.JamStates { - u := unit(jam.CampaignID) - for _, rev := range jam.Revisions { - u.add("spec", rev.Author.Name) - } - for _, th := range jam.Threads { - u.add("spec", th.CreatedBy.Name) - for _, c := range th.Comments { - u.add("spec", c.Author.Name) - } - } - for _, sug := range jam.Suggestions { - u.add("spec", sug.Author.Name) - if sug.Status == jamSuggestionAccepted && sug.ResolvedBy != nil { - u.add("review", sug.ResolvedBy.Name) - } - } - for _, poll := range jam.Polls { - u.add("plan", poll.CreatedBy.Name) - for _, vote := range poll.Votes { - u.add("plan", vote.Voter.Name) - } - if poll.Decision != nil { - u.add("review", poll.Decision.DecidedBy.Name) - } - } - } for _, run := range inputs.Runs { u := unit(run.Key) if run.Assignee != "" { @@ -381,7 +353,6 @@ func (s *Server) achievement2BaseInputs() achievement2Inputs { return inputs } inputs.LocalHiveID = s.localHiveIdentity() - inputs.JamStates = s.achievementJamStates() if runs, err := s.activeRuns(true); err == nil { inputs.Runs = runs } @@ -390,22 +361,3 @@ func (s *Server) achievement2BaseInputs() achievement2Inputs { } return inputs } - -func (s *Server) achievementJamStates() []CampaignJamState { - if s == nil { - return nil - } - campaignJamStoreMu.Lock() - defer campaignJamStoreMu.Unlock() - disk, err := s.readCampaignJamDisk() - if err != nil || len(disk.Campaigns) == 0 { - return nil - } - out := make([]CampaignJamState, 0, len(disk.Campaigns)) - for _, state := range disk.Campaigns { - if state != nil { - out = append(out, *state.clone()) - } - } - return out -} diff --git a/src/pkg/dashboard/achievements2_test.go b/src/pkg/dashboard/achievements2_test.go index 0fcaf41f93..f3906b0d40 100644 --- a/src/pkg/dashboard/achievements2_test.go +++ b/src/pkg/dashboard/achievements2_test.go @@ -30,20 +30,6 @@ func TestBuildAchievements2LocalPaidHybridMastery(t *testing.T) { completedActivity("alice", "openai", "gpt-5.6-terra", "2026-09-22T14:00:00Z"), completedActivity("mallory", "ollama", "llama3", "2026-09-22T15:00:00Z"), }, - JamStates: []CampaignJamState{{ - CampaignID: "run-1", - Revisions: []CampaignRevision{{Author: CampaignJamActor{Name: "alice"}}}, - Polls: []CampaignPoll{{ - CreatedBy: CampaignJamActor{Name: "bob"}, - Votes: []CampaignPollVote{{Voter: CampaignJamActor{Name: "alice"}}}, - Decision: &CampaignDecision{DecidedBy: CampaignJamActor{Name: "carol"}}, - }}, - Suggestions: []CampaignSuggestion{{ - Status: jamSuggestionAccepted, - Author: CampaignJamActor{Name: "dave"}, - ResolvedBy: &CampaignJamActor{Name: "carol"}, - }}, - }}, Runs: []Run{{ Key: "run-1", Stage: StageImplement, Assignee: "dave", Stages: []RunStage{ diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index fa3528706f..d3c7f33d12 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -96,25 +96,6 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("POST /api/runs/{key}/checkpoint", s.handleRunCheckpointDecision) s.mux.HandleFunc("GET /api/runs/{key}", s.handleRunGet) s.mux.HandleFunc("POST /api/runs/{key}/reset", s.handleRunReset) - s.mux.HandleFunc("GET /api/campaigns", s.handleCampaignsList) - s.mux.HandleFunc("GET /api/campaigns/{id}", s.handleCampaignGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/resume", s.handleCampaignResume) - s.mux.HandleFunc("POST /api/campaigns/{id}/release", s.handleCampaignRelease) - s.mux.HandleFunc("POST /api/campaigns/{id}/revise", s.handleCampaignRevise) - s.mux.HandleFunc("DELETE /api/campaigns/{id}", s.handleCampaignDelete) - s.mux.HandleFunc("POST /api/campaigns/{id}/recheck", s.handleCampaignRecheck) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam", s.handleCampaignJamGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam", s.handleCampaignJamPost) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam/threads", s.handleCampaignJamThreadsGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam/threads", s.handleCampaignJamThreadsPost) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam/agents", s.handleCampaignJamAgentsPost) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam/suggestions", s.handleCampaignJamSuggestionsGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam/suggestions", s.handleCampaignJamSuggestionsPost) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam/polls", s.handleCampaignJamPollsGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam/polls", s.handleCampaignJamPollsPost) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam/project-sync", s.handleCampaignJamProjectSyncGet) - s.mux.HandleFunc("POST /api/campaigns/{id}/jam/project-sync", s.handleCampaignJamProjectSyncPost) - s.mux.HandleFunc("GET /api/campaigns/{id}/jam/ws", s.handleCampaignJamWebSocket) s.mux.HandleFunc("GET /api/widget", s.handleWidget) s.mux.HandleFunc("GET /api/widget/summary", s.handleWidgetSummary) s.mux.HandleFunc("GET /api/widget/token", s.handleWidgetTokenStatus) diff --git a/src/pkg/dashboard/api_campaigns.go b/src/pkg/dashboard/api_campaigns.go deleted file mode 100644 index b13910eaa3..0000000000 --- a/src/pkg/dashboard/api_campaigns.go +++ /dev/null @@ -1,645 +0,0 @@ -package dashboard - -import ( - "errors" - "net/http" - "net/url" - "sort" - "strings" - "time" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// Campaign is the dashboard projection for resumable inception/Spektacular work. -type Campaign struct { - ID string `json:"id"` - Title string `json:"title"` - Source string `json:"source,omitempty"` - Repos []string `json:"repos,omitempty"` - CurrentStage string `json:"current_stage"` - CurrentStep string `json:"current_step,omitempty"` - Artifacts []CampaignArtifact `json:"artifacts,omitempty"` - LinkedPRs []string `json:"linked_prs,omitempty"` - LinkedIssues []string `json:"linked_issues,omitempty"` - Contributors []string `json:"contributors,omitempty"` - LastActivity string `json:"last_activity,omitempty"` - Status string `json:"status"` - Engine string `json:"engine"` - Type string `json:"type"` - RunKey string `json:"run_key,omitempty"` - RunURL string `json:"run_url,omitempty"` - LeaseOwner string `json:"lease_owner,omitempty"` - RevisionOf string `json:"revision_of,omitempty"` - Revision int `json:"revision,omitempty"` - // SupersededBy is the id of the newer revision that branched from this - // campaign, so the dashboard can fold Revise chains into one row. - SupersededBy string `json:"superseded_by,omitempty"` - Recheck *CampaignRecheck `json:"recheck,omitempty"` - Drift *CampaignDrift `json:"drift,omitempty"` -} - -type CampaignRecheck struct { - Enabled bool `json:"enabled"` - Interval string `json:"interval,omitempty"` - LastAt string `json:"last_at,omitempty"` - NextAt string `json:"next_at,omitempty"` - InFlight bool `json:"in_flight"` - LastDeltaCount int `json:"last_delta_count,omitempty"` - ExternalCount int `json:"external_count,omitempty"` - SourcesFailed []CampaignSourceFailure `json:"sources_failed,omitempty"` -} - -type CampaignDrift struct { - DriftSource []knowledge.CampaignDriftSource `json:"drift_source,omitempty"` - CodebaseChanged bool `json:"codebase_changed"` - PriorHeadSHA string `json:"prior_head_sha,omitempty"` - CurrentHeadSHA string `json:"current_head_sha,omitempty"` - PriorRevision string `json:"prior_revision,omitempty"` - DeltaCount int `json:"delta_count"` - RecheckReason string `json:"recheck_reason,omitempty"` - External []CampaignExternalEvidence `json:"external,omitempty"` - ExternalCount int `json:"external_count,omitempty"` - SourcesFailed []CampaignSourceFailure `json:"sources_failed,omitempty"` -} - -type CampaignExternalEvidence struct { - Source string `json:"source"` - Kind string `json:"kind"` - Title string `json:"title"` - URL string `json:"url,omitempty"` - PublishedAt string `json:"published_at,omitempty"` - Summary string `json:"summary,omitempty"` -} - -type CampaignSourceFailure struct { - Name string `json:"name"` - Reason string `json:"reason"` -} - -type CampaignArtifact struct { - Kind string `json:"kind"` - Label string `json:"label"` - URL string `json:"url,omitempty"` -} - -type campaignResumeRequest struct { - Surface string `json:"surface"` -} - -type campaignResumeResponse struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - Run *Run `json:"run,omitempty"` - State interface{} `json:"state,omitempty"` - ResumeCommand string `json:"resume_command,omitempty"` - Message string `json:"message,omitempty"` -} - -type campaignReleaseResponse struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - Message string `json:"message,omitempty"` -} - -type campaignReviseResponse struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - Message string `json:"message,omitempty"` -} - -type campaignDeleteResponse struct { - OK bool `json:"ok"` - ID string `json:"id"` - Message string `json:"message,omitempty"` -} - -func (s *Server) handleCampaignsList(w http.ResponseWriter, r *http.Request) { - campaigns, err := s.campaignsForRequest(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - jsonResponse(w, map[string]interface{}{"ok": true, "campaigns": campaigns}) -} - -func (s *Server) handleCampaignGet(w http.ResponseWriter, r *http.Request) { - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - campaigns, err := s.campaignsForRequest(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - for _, campaign := range campaigns { - if campaign.ID == id || campaign.RunKey == id { - jsonResponse(w, map[string]interface{}{"ok": true, "campaign": campaign}) - return - } - } - jsonError(w, "campaign not found", http.StatusNotFound) -} - -func (s *Server) handleCampaignResume(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - var req campaignResumeRequest - if r.Body != nil && r.ContentLength != 0 { - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - } - campaigns, err := s.campaignsForRequest(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - for _, campaign := range campaigns { - if campaign.ID != id && campaign.RunKey != id { - continue - } - if campaign.Type == "inception" && s.deps != nil && s.deps.Inception != nil { - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - leased, err := s.deps.Inception.LeaseCampaignArchive(campaign.ID, requestUser(r), req.Surface, time.Now()) - if err != nil { - jsonError(w, err.Error(), campaignArchiveErrorStatus(err)) - return - } - state, err := s.deps.Inception.RestoreCampaignArchive(campaign.ID) - if err != nil { - jsonError(w, err.Error(), http.StatusNotFound) - return - } - campaign = campaignFromInceptionArchive(*leased) - s.auditFromRequest(r, "campaign_resume", auditDetail("campaign", campaign.ID, "type", campaign.Type, "surface", strings.TrimSpace(req.Surface)), "") - jsonResponse(w, campaignResumeResponse{OK: true, Campaign: campaign, State: state, Message: "Inception campaign restored"}) - return - } - if campaign.LeaseOwner != "" && campaign.LeaseOwner != requestUser(r) { - jsonError(w, "campaign lease held by "+campaign.LeaseOwner, http.StatusConflict) - return - } - run, _ := s.runByCampaignKey(campaign.RunKey) - s.auditFromRequest(r, "campaign_resume", auditDetail("campaign", campaign.ID, "type", campaign.Type, "surface", strings.TrimSpace(req.Surface)), "") - jsonResponse(w, campaignResumeResponse{OK: true, Campaign: campaign, Run: run, ResumeCommand: spektacularResumeCommand(campaign), Message: "Spektacular state is loaded from its artifact files; continue with the command or run link."}) - return - } - jsonError(w, "campaign not found", http.StatusNotFound) -} - -func (s *Server) handleCampaignRelease(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - if s.deps == nil || s.deps.Inception == nil { - jsonError(w, "campaign store unavailable", http.StatusServiceUnavailable) - return - } - campaigns, err := s.campaignsForRequest(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - for _, campaign := range campaigns { - if campaign.ID != id && campaign.RunKey != id { - continue - } - if campaign.RunKey != "" && campaign.Type == "spektacular" { - // Run-backed campaigns expose the runner's stage lease, not a - // separate campaign pickup lease. Revoking it here stops the - // contributor and can remove the run from both API projections - // (hivecommons/hive#10057). - jsonError(w, "run-backed campaigns cannot be released here; the contributor's stage lease is managed by the run lifecycle", http.StatusConflict) - return - } - archive, err := s.deps.Inception.ReleaseCampaignArchive(campaign.ID, requestUser(r), time.Now()) - if err != nil { - jsonError(w, err.Error(), campaignArchiveErrorStatus(err)) - return - } - released := campaignFromInceptionArchive(*archive) - s.auditFromRequest(r, "campaign_release", auditDetail("campaign", released.ID, "type", released.Type), "") - jsonResponse(w, campaignReleaseResponse{OK: true, Campaign: released, Message: "Campaign lease released"}) - return - } - jsonError(w, "campaign not found", http.StatusNotFound) -} - -func (s *Server) handleCampaignRevise(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - if s.deps == nil || s.deps.Inception == nil { - jsonError(w, "campaign store unavailable", http.StatusServiceUnavailable) - return - } - campaigns, err := s.campaignsForRequest(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - for _, campaign := range campaigns { - if campaign.ID != id && campaign.RunKey != id { - continue - } - var archive *knowledge.InceptionCampaignArchive - if campaign.Type == "inception" { - archive, err = s.deps.Inception.ReviseCampaignArchive(campaign.ID, requestUser(r), time.Now()) - } else { - archive, err = s.deps.Inception.ReviseExternalCampaign(campaign.ID, campaign.Title, campaign.Source, campaign.Engine, campaign.Type, requestUser(r), campaign.Repos, time.Now()) - } - if err != nil { - jsonError(w, err.Error(), campaignArchiveErrorStatus(err)) - return - } - revision := campaignFromInceptionArchive(*archive) - s.auditFromRequest(r, "campaign_revise", auditDetail("campaign", campaign.ID, "revision", revision.ID, "type", campaign.Type), "") - jsonResponse(w, campaignReviseResponse{OK: true, Campaign: revision, Message: "Campaign revision created"}) - return - } - jsonError(w, "campaign not found", http.StatusNotFound) -} - -// handleCampaignDelete removes a campaign's archive record. Durable artefacts -// (KB facts, Jam threads, scaffolded repo files) stay; only the saved -// inception state and its wiki snapshot are deleted (hivecommons/hive#12698). -func (s *Server) handleCampaignDelete(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - if s.deps == nil || s.deps.Inception == nil { - jsonError(w, "campaign store unavailable", http.StatusServiceUnavailable) - return - } - campaigns, err := s.allCampaigns(r) - if err != nil { - jsonError(w, err.Error(), http.StatusServiceUnavailable) - return - } - for _, campaign := range campaigns { - if campaign.ID != id && campaign.RunKey != id { - continue - } - if _, loadErr := s.deps.Inception.LoadCampaignArchive(campaign.ID); loadErr != nil && campaign.Type == "spektacular" { - // Run-backed rows are projections of the contributor run, not an - // archive we own; deleting them here would silently drop a live run. - jsonError(w, "run-backed campaigns are managed by the run lifecycle and cannot be deleted here", http.StatusConflict) - return - } - deleted, err := s.deps.Inception.DeleteCampaignArchive(campaign.ID) - if err != nil { - jsonError(w, err.Error(), campaignArchiveErrorStatus(err)) - return - } - s.auditFromRequest(r, "campaign_delete", auditDetail("campaign", deleted.ID, "type", campaign.Type, "revision_of", campaign.RevisionOf), "") - jsonResponse(w, campaignDeleteResponse{OK: true, ID: deleted.ID, Message: "Campaign record deleted; knowledge-base facts and Jam threads were kept"}) - return - } - jsonError(w, "campaign not found", http.StatusNotFound) -} - -func campaignIDFromRequest(r *http.Request) string { - id := strings.TrimSpace(r.PathValue("id")) - if unescaped, err := url.PathUnescape(id); err == nil { - id = strings.TrimSpace(unescaped) - } - return id -} - -func (s *Server) campaignsForRequest(r *http.Request) ([]Campaign, error) { - campaigns, err := s.allCampaigns(r) - if err != nil { - return nil, err - } - q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q"))) - if q == "" { - q = strings.ToLower(strings.TrimSpace(r.URL.Query().Get("search"))) - } - repo := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("repo"))) - stage := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("stage"))) - status := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("status"))) - owner := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("owner"))) - out := campaigns[:0] - for _, campaign := range campaigns { - if q != "" && !campaignMatchesSearch(campaign, q) { - continue - } - if repo != "" && !campaignHasValue(campaign.Repos, repo) { - continue - } - if stage != "" && !strings.EqualFold(campaign.CurrentStage, stage) { - continue - } - if status != "" && !strings.EqualFold(campaign.Status, status) { - continue - } - if owner != "" && !campaignHasValue(campaign.Contributors, owner) && !strings.EqualFold(campaign.LeaseOwner, owner) { - continue - } - out = append(out, campaign) - } - sort.Slice(out, func(i, j int) bool { return out[i].LastActivity > out[j].LastActivity }) - return out, nil -} - -func (s *Server) allCampaigns(r *http.Request) ([]Campaign, error) { - byID := map[string]Campaign{} - if s != nil && s.deps != nil && s.deps.Inception != nil { - archives, err := s.deps.Inception.ListCampaignArchives() - if err != nil { - return nil, err - } - for _, archive := range archives { - campaign := campaignFromInceptionArchive(archive) - byID[campaign.ID] = campaign - } - if state := s.deps.Inception.GetState(); state != nil && strings.TrimSpace(state.IdeaSlug) != "" { - campaign := campaignFromInceptionArchive(knowledge.InceptionCampaignArchive{ - ID: state.IdeaSlug, - Engine: "Spec Kit", - Type: "inception", - State: state, - }) - byID[campaign.ID] = campaign - } - } - if s != nil && s.contributeHub != nil { - runs, err := s.activeRuns(true) - if err != nil { - return nil, err - } - for _, run := range runs { - campaign := campaignFromRun(run) - if existing, ok := byID[campaign.ID]; ok { - campaign.RevisionOf = existing.RevisionOf - campaign.Revision = existing.Revision - campaign.Recheck = existing.Recheck - campaign.Drift = existing.Drift - } - byID[campaign.ID] = campaign - } - } - s.decorateCampaignRechecks(byID) - markSupersededCampaigns(byID) - out := make([]Campaign, 0, len(byID)) - for _, campaign := range byID { - out = append(out, campaign) - } - return out, nil -} - -// markSupersededCampaigns links each campaign to the newest revision that -// branched from it so the dashboard can show one row per Revise chain -// (hivecommons/hive#12698). When several revisions share a parent the highest -// revision number wins; ties fall back to the most recent activity. -func markSupersededCampaigns(byID map[string]Campaign) { - for id, campaign := range byID { - parent := strings.TrimSpace(campaign.RevisionOf) - if parent == "" || parent == id { - continue - } - base, ok := byID[parent] - if !ok { - continue - } - if current, ok := byID[base.SupersededBy]; ok && !campaignNewerRevision(campaign, current) { - continue - } - base.SupersededBy = id - byID[parent] = base - } -} - -func campaignNewerRevision(a, b Campaign) bool { - if a.Revision != b.Revision { - return a.Revision > b.Revision - } - return a.LastActivity > b.LastActivity -} - -func campaignFromInceptionArchive(archive knowledge.InceptionCampaignArchive) Campaign { - state := archive.State - title := firstRunNonEmpty(archive.Title, archive.ID) - stage := "inception" - step := "archived" - status := "parked" - last := archive.ArchivedAt - repos := append([]string{}, archive.Repos...) - linkedIssues := []string{} - leaseOwner := "" - runKey := "" - runURL := "" - contributors := []string{"brainstorm"} - if state != nil { - if strings.TrimSpace(state.IdeaText) != "" { - title = strings.TrimSpace(state.IdeaText) - } - step = string(state.Phase) - status = inceptionCampaignStatus(state.Phase) - if !state.StartedAt.IsZero() && last.IsZero() { - last = state.StartedAt - } - if state.PhaseChangedAt != nil { - last = *state.PhaseChangedAt - } - if strings.TrimSpace(state.RepoURL) != "" { - repos = append(repos, strings.TrimSpace(state.RepoURL)) - } - } else if firstRunNonEmpty(archive.Type, "inception") == "spektacular" { - stage = StagePlan - if archive.Drift != nil { - stage = StageSpec - } - step = "revision" - runKey = strings.TrimSpace(archive.Source) - if runKey != "" { - runURL = "/api/runs/" + url.PathEscape(runKey) - } - contributors = nil - } - if archive.Lease != nil && archive.Lease.Owner != "" && time.Now().Before(archive.Lease.ExpiresAt) { - leaseOwner = archive.Lease.Owner - } - artifacts := []CampaignArtifact{{Kind: "state", Label: "Inception state"}} - for _, file := range archive.WikiFiles { - artifacts = append(artifacts, CampaignArtifact{Kind: "fact", Label: file}) - } - campaign := Campaign{ - ID: archive.ID, Title: title, Source: firstRunNonEmpty(archive.Source, "inception"), Repos: repos, CurrentStage: stage, CurrentStep: step, - Artifacts: artifacts, LinkedIssues: linkedIssues, Contributors: contributors, LastActivity: formatRunTime(last), - Status: status, Engine: firstRunNonEmpty(archive.Engine, "Spec Kit"), Type: firstRunNonEmpty(archive.Type, "inception"), - RunKey: runKey, RunURL: runURL, LeaseOwner: leaseOwner, RevisionOf: archive.RevisionOf, Revision: archive.Revision, - Recheck: campaignRecheckFromArchive(archive, false), Drift: campaignDriftFromArchive(archive), - } - if campaign.Recheck != nil && campaign.Drift != nil { - campaign.Recheck.ExternalCount = campaign.Drift.ExternalCount - campaign.Recheck.SourcesFailed = campaign.Drift.SourcesFailed - } - return campaign -} - -func campaignFromRun(run Run) Campaign { - id := runKeyOfLease(run.Key, run.Repo) - if leaseKey := strings.TrimSpace(run.LeaseKey); leaseKey != "" { - id = runKeyOfLease(leaseKey, run.Repo) - } - prs := []string{} - for _, wave := range run.ReviewWaves { - for _, pr := range wave.PRs { - if pr.URL != "" { - prs = append(prs, pr.URL) - } - } - } - issues := []string{} - if run.Repo != "" && run.Key != "" { - issues = append(issues, run.Key) - } - artifacts := []CampaignArtifact{{Kind: "run", Label: "Run detail", URL: "/api/runs/" + url.PathEscape(run.Key)}} - if run.LastReceipt != "" { - artifacts = append(artifacts, CampaignArtifact{Kind: "receipt", Label: run.LastReceipt}) - } - return Campaign{ - ID: id, Title: run.Title, Source: run.Key, Repos: nonEmptyStrings(run.Repo), CurrentStage: run.Stage, - CurrentStep: firstRunNonEmpty(run.WaitingReason, run.TriageVerdict), Artifacts: artifacts, LinkedPRs: prs, LinkedIssues: issues, - Contributors: nonEmptyStrings(firstRunNonEmpty(run.Assignee, run.ClaimedBy)), LastActivity: firstRunNonEmpty(run.CompletedAt, run.StageStartedAt), - Status: runCampaignStatus(run), Engine: "Spektacular", Type: "spektacular", RunKey: run.Key, - RunURL: "/api/runs/" + url.PathEscape(run.Key), LeaseOwner: run.Assignee, - } -} - -func campaignArchiveErrorStatus(err error) int { - switch { - case errors.Is(err, knowledge.ErrCampaignLeaseHeld): - return http.StatusConflict - case errors.Is(err, knowledge.ErrCampaignNoLease): - return http.StatusConflict - case strings.Contains(err.Error(), "not found"): - return http.StatusNotFound - default: - return http.StatusInternalServerError - } -} - -func inceptionCampaignStatus(phase knowledge.InceptionPhase) string { - switch phase { - case knowledge.PhaseComplete: - return "shipped" - case knowledge.PhaseScaffold: - return "in review" - case knowledge.PhaseStructure: - return "planned" - case knowledge.PhaseClarify, knowledge.PhaseCapture: - return "drafting" - default: - return "parked" - } -} - -func runCampaignStatus(run Run) string { - if run.State == "completed" || run.Stage == "completed" { - return "shipped" - } - if run.WaitingOn == RunWaitingOnHuman { - return "in review" - } - switch run.Stage { - case StageSpec: - return "drafting" - case StagePlan: - return "planned" - case StageImplement: - return "implementing" - default: - if run.State == "queued" { - return "parked" - } - return firstRunNonEmpty(run.State, "parked") - } -} - -func (s *Server) runByCampaignKey(key string) (*Run, bool) { - if s == nil || s.contributeHub == nil || key == "" { - return nil, false - } - runs, err := s.activeRuns(true) - if err != nil { - return nil, false - } - for _, run := range runs { - if run.Key == key || run.LeaseKey == key { - cp := run - return &cp, true - } - } - return nil, false -} - -func spektacularResumeCommand(c Campaign) string { - stage := strings.TrimSpace(c.CurrentStage) - if stage == "" || stage == StageImplement || stage == "completed" { - stage = StagePlan - } - return "spektacular " + stage + " status " + c.ID -} - -func campaignMatchesSearch(c Campaign, q string) bool { - fields := []string{c.ID, c.Title, c.Source, c.CurrentStage, c.CurrentStep, c.Status, c.Engine, c.Type, c.RunKey, c.LeaseOwner} - fields = append(fields, c.Repos...) - fields = append(fields, c.LinkedIssues...) - fields = append(fields, c.LinkedPRs...) - fields = append(fields, c.Contributors...) - for _, field := range fields { - if strings.Contains(strings.ToLower(field), q) { - return true - } - } - return false -} - -func campaignHasValue(values []string, want string) bool { - for _, value := range values { - if strings.Contains(strings.ToLower(value), want) { - return true - } - } - return false -} - -func nonEmptyStrings(values ...string) []string { - out := []string{} - for _, value := range values { - if strings.TrimSpace(value) != "" { - out = append(out, strings.TrimSpace(value)) - } - } - return out -} diff --git a/src/pkg/dashboard/api_campaigns_jam.go b/src/pkg/dashboard/api_campaigns_jam.go deleted file mode 100644 index d7444e43ee..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam.go +++ /dev/null @@ -1,711 +0,0 @@ -package dashboard - -import ( - "encoding/json" - "errors" - "net/http" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/hivecommons/hive/pkg/config" -) - -const ( - jamSuggestionOpen = "open" - jamSuggestionAccepted = "accepted" - jamSuggestionRejected = "rejected" - jamPollOpen = "open" - jamPollDecided = "decided" -) - -type CampaignJamState struct { - CampaignID string `json:"campaign_id"` - SpecRevisionID string `json:"spec_revision_id,omitempty"` - SpecContent string `json:"spec_content,omitempty"` - Threads []CampaignThread `json:"threads,omitempty"` - Suggestions []CampaignSuggestion `json:"suggestions,omitempty"` - Polls []CampaignPoll `json:"polls,omitempty"` - Revisions []CampaignRevision `json:"revisions,omitempty"` - ProjectSync *CampaignProjectSync `json:"project_sync,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -type CampaignProjectSync struct { - Enabled bool `json:"enabled"` - ProjectURL string `json:"project_url,omitempty"` - ProjectID string `json:"project_id,omitempty"` - LastStatus string `json:"last_status,omitempty"` - LastSyncAt string `json:"last_sync_at,omitempty"` - LastError string `json:"last_error,omitempty"` - RetryAdvice string `json:"retry_advice,omitempty"` - PublishedItems []CampaignProjectItem `json:"published_items,omitempty"` -} - -type CampaignProjectItem struct { - Type string `json:"type"` - Title string `json:"title"` - Body string `json:"body,omitempty"` - Status string `json:"status,omitempty"` - ExternalID string `json:"external_id,omitempty"` - UpdatedAt string `json:"updated_at"` -} - -type CampaignThread struct { - ID string `json:"id"` - Section string `json:"section"` - Title string `json:"title,omitempty"` - Comments []CampaignComment `json:"comments,omitempty"` - CreatedBy CampaignJamActor `json:"created_by"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} - -type CampaignComment struct { - ID string `json:"id"` - Body string `json:"body"` - Author CampaignJamActor `json:"author"` - CreatedAt string `json:"created_at"` -} - -type CampaignSuggestion struct { - ID string `json:"id"` - ThreadID string `json:"thread_id,omitempty"` - Section string `json:"section"` - Body string `json:"body,omitempty"` - ProposedText string `json:"proposed_text"` - Status string `json:"status"` - Author CampaignJamActor `json:"author"` - CreatedAt string `json:"created_at"` - ResolvedBy *CampaignJamActor `json:"resolved_by,omitempty"` - ResolvedAt string `json:"resolved_at,omitempty"` - ResolutionComment string `json:"resolution_comment,omitempty"` - AppliedRevisionID string `json:"applied_revision_id,omitempty"` -} - -type CampaignPoll struct { - ID string `json:"id"` - Section string `json:"section"` - Question string `json:"question"` - Options []CampaignPollOption `json:"options"` - Votes []CampaignPollVote `json:"votes,omitempty"` - Status string `json:"status"` - CreatedBy CampaignJamActor `json:"created_by"` - CreatedAt string `json:"created_at"` - Decision *CampaignDecision `json:"decision,omitempty"` -} - -type CampaignPollOption struct { - ID string `json:"id"` - Label string `json:"label"` - Count int `json:"count"` -} - -type CampaignPollVote struct { - Voter CampaignJamActor `json:"voter"` - OptionID string `json:"option_id"` - VotedAt string `json:"voted_at"` -} - -type CampaignDecision struct { - Outcome string `json:"outcome"` - Rationale string `json:"rationale"` - DecidedBy CampaignJamActor `json:"decided_by"` - DecidedAt string `json:"decided_at"` - RevisionID string `json:"revision_id"` -} - -type CampaignRevision struct { - ID string `json:"id"` - Content string `json:"content,omitempty"` - Diff string `json:"diff,omitempty"` - Reason string `json:"reason,omitempty"` - Author CampaignJamActor `json:"author"` - CreatedAt string `json:"created_at"` - Model string `json:"model,omitempty"` - Agent string `json:"agent,omitempty"` - Decisions []CampaignDecision `json:"decisions,omitempty"` -} - -type CampaignJamActor struct { - Type string `json:"type"` - Name string `json:"name"` - Model string `json:"model,omitempty"` - Agent string `json:"agent,omitempty"` -} - -type campaignJamPostRequest struct { - SpecContent string `json:"spec_content"` - Reason string `json:"reason"` - Model string `json:"model"` - Agent string `json:"agent"` -} - -type campaignJamThreadRequest struct { - ThreadID string `json:"thread_id"` - Section string `json:"section"` - Title string `json:"title"` - Body string `json:"body"` - Model string `json:"model"` - Agent string `json:"agent"` -} - -type campaignJamSuggestionRequest struct { - Action string `json:"action"` - SuggestionID string `json:"suggestion_id"` - ThreadID string `json:"thread_id"` - Section string `json:"section"` - Body string `json:"body"` - ProposedText string `json:"proposed_text"` - ResolutionComment string `json:"resolution_comment"` - SpecContent string `json:"spec_content"` - Model string `json:"model"` - Agent string `json:"agent"` -} - -type campaignJamPollRequest struct { - Action string `json:"action"` - PollID string `json:"poll_id"` - Section string `json:"section"` - Question string `json:"question"` - Options []string `json:"options"` - OptionID string `json:"option_id"` - Outcome string `json:"outcome"` - Rationale string `json:"rationale"` - Model string `json:"model"` - Agent string `json:"agent"` -} - -type campaignJamDisk struct { - Campaigns map[string]*CampaignJamState `json:"campaigns"` -} - -var campaignJamStoreMu sync.Mutex -var campaignJamIDSeq uint64 - -func (s *Server) handleCampaignJamGet(w http.ResponseWriter, r *http.Request) { - state, err := s.loadCampaignJam(campaignIDFromRequest(r)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -func (s *Server) handleCampaignJamPost(w http.ResponseWriter, r *http.Request) { - if !requireJamWriteRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignJamPostRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - req.SpecContent = strings.TrimSpace(req.SpecContent) - if req.SpecContent == "" { - jsonError(w, "spec_content required", http.StatusBadRequest) - return - } - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - recordJamRevision(state, req.SpecContent, strings.TrimSpace(req.Reason), jamActorFromRequest(r, req.Agent, req.Model), nil) - return nil - }) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - s.auditFromRequest(r, "campaign_jam_revision", auditDetail("campaign", id), strings.TrimSpace(req.Agent)) - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -func (s *Server) handleCampaignJamThreadsGet(w http.ResponseWriter, r *http.Request) { - state, err := s.loadCampaignJam(campaignIDFromRequest(r)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "threads": state.Threads}) -} - -func (s *Server) handleCampaignJamThreadsPost(w http.ResponseWriter, r *http.Request) { - if !requireJamWriteRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignJamThreadRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - now := jamNow() - actor := jamActorFromRequest(r, req.Agent, req.Model) - if strings.TrimSpace(req.ThreadID) != "" { - for i := range state.Threads { - if state.Threads[i].ID == strings.TrimSpace(req.ThreadID) { - body := strings.TrimSpace(req.Body) - if body == "" { - return errors.New("body required") - } - state.Threads[i].Comments = append(state.Threads[i].Comments, CampaignComment{ID: jamID("comment"), Body: body, Author: actor, CreatedAt: now}) - state.Threads[i].UpdatedAt = now - return nil - } - } - return errors.New("thread not found") - } - section := strings.TrimSpace(req.Section) - body := strings.TrimSpace(req.Body) - if section == "" || body == "" { - return errors.New("section and body required") - } - thread := CampaignThread{ID: jamID("thread"), Section: section, Title: strings.TrimSpace(req.Title), CreatedBy: actor, CreatedAt: now, UpdatedAt: now} - thread.Comments = append(thread.Comments, CampaignComment{ID: jamID("comment"), Body: body, Author: actor, CreatedAt: now}) - state.Threads = append(state.Threads, thread) - return nil - }) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -func (s *Server) handleCampaignJamSuggestionsGet(w http.ResponseWriter, r *http.Request) { - state, err := s.loadCampaignJam(campaignIDFromRequest(r)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "suggestions": state.Suggestions}) -} - -func (s *Server) handleCampaignJamSuggestionsPost(w http.ResponseWriter, r *http.Request) { - if !requireJamWriteRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignJamSuggestionRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - action := firstRunNonEmpty(strings.TrimSpace(req.Action), "create") - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - actor := jamActorFromRequest(r, req.Agent, req.Model) - switch action { - case "create": - section := strings.TrimSpace(req.Section) - proposed := strings.TrimSpace(req.ProposedText) - if section == "" || proposed == "" { - return errors.New("section and proposed_text required") - } - state.Suggestions = append(state.Suggestions, CampaignSuggestion{ - ID: jamID("suggestion"), ThreadID: strings.TrimSpace(req.ThreadID), Section: section, Body: strings.TrimSpace(req.Body), - ProposedText: proposed, Status: jamSuggestionOpen, Author: actor, CreatedAt: jamNow(), - }) - case "accept", "reject": - if action == "accept" && !requireJamMaintainerRole(w, r) { - return errJamResponseWritten - } - return resolveJamSuggestion(state, strings.TrimSpace(req.SuggestionID), action, strings.TrimSpace(req.SpecContent), strings.TrimSpace(req.ResolutionComment), actor) - default: - return errors.New("unsupported suggestion action") - } - return nil - }) - if errors.Is(err, errJamResponseWritten) { - return - } - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -func (s *Server) handleCampaignJamPollsGet(w http.ResponseWriter, r *http.Request) { - state, err := s.loadCampaignJam(campaignIDFromRequest(r)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "polls": state.Polls}) -} - -func (s *Server) handleCampaignJamPollsPost(w http.ResponseWriter, r *http.Request) { - if !requireJamWriteRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignJamPollRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - action := firstRunNonEmpty(strings.TrimSpace(req.Action), "create") - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - actor := jamActorFromRequest(r, req.Agent, req.Model) - switch action { - case "create": - return createJamPoll(state, req, actor) - case "vote": - return voteJamPoll(state, strings.TrimSpace(req.PollID), strings.TrimSpace(req.OptionID), actor) - case "decide": - if !requireJamMaintainerRole(w, r) { - return errJamResponseWritten - } - return decideJamPoll(state, strings.TrimSpace(req.PollID), strings.TrimSpace(req.Outcome), strings.TrimSpace(req.Rationale), actor) - default: - return errors.New("unsupported poll action") - } - }) - if errors.Is(err, errJamResponseWritten) { - return - } - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -var errJamResponseWritten = errors.New("jam response written") - -func requireJamWriteRole(w http.ResponseWriter, r *http.Request) bool { - if !config.RoleAtLeast(r.Header.Get("X-Hive-Role"), config.RoleReadWrite) { - jsonError(w, "read-write access required", http.StatusForbidden) - return false - } - return true -} - -func requireJamMaintainerRole(w http.ResponseWriter, r *http.Request) bool { - return requireMergerOrOwnerRole(w, r) -} - -func (s *Server) loadCampaignJam(id string) (*CampaignJamState, error) { - if strings.TrimSpace(id) == "" { - return nil, errors.New("campaign id required") - } - campaignJamStoreMu.Lock() - defer campaignJamStoreMu.Unlock() - disk, err := s.readCampaignJamDisk() - if err != nil { - return nil, err - } - return ensureCampaignJamState(disk, id).clone(), nil -} - -func (s *Server) mutateCampaignJam(id string, fn func(*CampaignJamState) error) (*CampaignJamState, error) { - if strings.TrimSpace(id) == "" { - return nil, errors.New("campaign id required") - } - campaignJamStoreMu.Lock() - defer campaignJamStoreMu.Unlock() - disk, err := s.readCampaignJamDisk() - if err != nil { - return nil, err - } - state := ensureCampaignJamState(disk, id) - if err := fn(state); err != nil { - return nil, err - } - state.UpdatedAt = jamNow() - sortJamState(state) - if err := s.writeCampaignJamDisk(disk); err != nil { - return nil, err - } - return state.clone(), nil -} - -func ensureCampaignJamState(disk campaignJamDisk, id string) *CampaignJamState { - id = strings.TrimSpace(id) - state := disk.Campaigns[id] - if state == nil { - state = &CampaignJamState{CampaignID: id} - disk.Campaigns[id] = state - } - return state -} - -func (s *Server) readCampaignJamDisk() (campaignJamDisk, error) { - disk := campaignJamDisk{Campaigns: map[string]*CampaignJamState{}} - path := s.campaignJamPath() - raw, err := os.ReadFile(path) - if errors.Is(err, os.ErrNotExist) { - return disk, nil - } - if err != nil { - return disk, err - } - if len(raw) == 0 { - return disk, nil - } - if err := json.Unmarshal(raw, &disk); err != nil { - return campaignJamDisk{}, err - } - if disk.Campaigns == nil { - disk.Campaigns = map[string]*CampaignJamState{} - } - return disk, nil -} - -func (s *Server) writeCampaignJamDisk(disk campaignJamDisk) error { - path := s.campaignJamPath() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return err - } - raw, err := json.MarshalIndent(disk, "", " ") - if err != nil { - return err - } - return os.WriteFile(path, raw, 0o600) -} - -func (s *Server) campaignJamPath() string { - base := "" - if s != nil && s.deps != nil && s.deps.Config != nil { - base = strings.TrimSpace(s.deps.Config.Data.MetricsDir) - if base == "" { - base = strings.TrimSpace(s.deps.Config.Data.LogsDir) - } - if base == "" { - base = strings.TrimSpace(s.deps.Config.Data.AgentsDir) - } - } - if base == "" { - base = "." - } - return filepath.Join(base, "campaign-jam.json") -} - -func recordJamRevision(state *CampaignJamState, content, reason string, actor CampaignJamActor, decisions []CampaignDecision) CampaignRevision { - now := jamNow() - revision := CampaignRevision{ - ID: jamID("rev"), Content: content, Diff: jamDiff(state.SpecContent, content), Reason: reason, - Author: actor, CreatedAt: now, Model: actor.Model, Agent: actor.Agent, Decisions: decisions, - } - state.Revisions = append(state.Revisions, revision) - state.SpecContent = content - state.SpecRevisionID = revision.ID - return revision -} - -func resolveJamSuggestion(state *CampaignJamState, id, action, content, comment string, actor CampaignJamActor) error { - if id == "" { - return errors.New("suggestion_id required") - } - for i := range state.Suggestions { - if state.Suggestions[i].ID != id { - continue - } - if state.Suggestions[i].Status != jamSuggestionOpen { - return errors.New("suggestion already resolved") - } - now := jamNow() - state.Suggestions[i].ResolvedBy = &actor - state.Suggestions[i].ResolvedAt = now - state.Suggestions[i].ResolutionComment = comment - if action == "reject" { - state.Suggestions[i].Status = jamSuggestionRejected - return nil - } - if content == "" { - content = applySectionSuggestion(state.SpecContent, state.Suggestions[i].Section, state.Suggestions[i].ProposedText) - } - rev := recordJamRevision(state, content, "accepted suggestion "+id, actor, nil) - state.Suggestions[i].Status = jamSuggestionAccepted - state.Suggestions[i].AppliedRevisionID = rev.ID - return nil - } - return errors.New("suggestion not found") -} - -func createJamPoll(state *CampaignJamState, req campaignJamPollRequest, actor CampaignJamActor) error { - section := strings.TrimSpace(req.Section) - question := strings.TrimSpace(req.Question) - if section == "" || question == "" || len(req.Options) < 2 { - return errors.New("section, question, and at least two options required") - } - options := make([]CampaignPollOption, 0, len(req.Options)) - for _, option := range req.Options { - label := strings.TrimSpace(option) - if label == "" { - continue - } - options = append(options, CampaignPollOption{ID: jamID("option"), Label: label}) - } - if len(options) < 2 { - return errors.New("at least two non-empty options required") - } - state.Polls = append(state.Polls, CampaignPoll{ID: jamID("poll"), Section: section, Question: question, Options: options, Status: jamPollOpen, CreatedBy: actor, CreatedAt: jamNow()}) - return nil -} - -func voteJamPoll(state *CampaignJamState, pollID, optionID string, actor CampaignJamActor) error { - if pollID == "" || optionID == "" { - return errors.New("poll_id and option_id required") - } - for i := range state.Polls { - poll := &state.Polls[i] - if poll.ID != pollID { - continue - } - if poll.Status != jamPollOpen { - return errors.New("poll is closed") - } - if !pollHasOption(poll, optionID) { - return errors.New("poll option not found") - } - for j := range poll.Votes { - if poll.Votes[j].Voter.Name == actor.Name { - decrementPollOption(poll, poll.Votes[j].OptionID) - poll.Votes[j].OptionID = optionID - poll.Votes[j].VotedAt = jamNow() - incrementPollOption(poll, optionID) - return nil - } - } - poll.Votes = append(poll.Votes, CampaignPollVote{Voter: actor, OptionID: optionID, VotedAt: jamNow()}) - incrementPollOption(poll, optionID) - return nil - } - return errors.New("poll not found") -} - -func decideJamPoll(state *CampaignJamState, pollID, outcome, rationale string, actor CampaignJamActor) error { - if pollID == "" || outcome == "" || rationale == "" { - return errors.New("poll_id, outcome, and rationale required") - } - for i := range state.Polls { - poll := &state.Polls[i] - if poll.ID != pollID { - continue - } - decision := CampaignDecision{Outcome: outcome, Rationale: rationale, DecidedBy: actor, DecidedAt: jamNow()} - content := state.SpecContent - if content != "" { - content += "\n\n" - } - content += "Decision (" + poll.Section + "): " + outcome + "\nRationale: " + rationale - rev := recordJamRevision(state, content, "poll decision "+pollID, actor, []CampaignDecision{decision}) - decision.RevisionID = rev.ID - state.Polls[i].Status = jamPollDecided - state.Polls[i].Decision = &decision - state.Revisions[len(state.Revisions)-1].Decisions = []CampaignDecision{decision} - return nil - } - return errors.New("poll not found") -} - -func pollHasOption(poll *CampaignPoll, optionID string) bool { - for _, option := range poll.Options { - if option.ID == optionID { - return true - } - } - return false -} - -func incrementPollOption(poll *CampaignPoll, optionID string) { - for i := range poll.Options { - if poll.Options[i].ID == optionID { - poll.Options[i].Count++ - return - } - } -} - -func decrementPollOption(poll *CampaignPoll, optionID string) { - for i := range poll.Options { - if poll.Options[i].ID == optionID && poll.Options[i].Count > 0 { - poll.Options[i].Count-- - return - } - } -} - -func applySectionSuggestion(current, section, proposed string) string { - if strings.TrimSpace(current) == "" { - return strings.TrimSpace(proposed) - } - marker := "## " + strings.TrimSpace(section) - lines := strings.Split(current, "\n") - start := -1 - for i, line := range lines { - if strings.TrimSpace(line) == marker { - start = i - break - } - } - if start < 0 { - return strings.TrimRight(current, "\n") + "\n\n" + marker + "\n" + strings.TrimSpace(proposed) - } - end := len(lines) - for i := start + 1; i < len(lines); i++ { - if strings.HasPrefix(strings.TrimSpace(lines[i]), "## ") { - end = i - break - } - } - out := append([]string{}, lines[:start+1]...) - out = append(out, strings.Split(strings.TrimSpace(proposed), "\n")...) - out = append(out, lines[end:]...) - return strings.TrimRight(strings.Join(out, "\n"), "\n") -} - -func jamDiff(before, after string) string { - before = strings.TrimSpace(before) - after = strings.TrimSpace(after) - if before == after { - return "" - } - if before == "" { - return "+ " + after - } - if after == "" { - return "- " + before - } - return "- " + before + "\n+ " + after -} - -func jamActorFromRequest(r *http.Request, agent, model string) CampaignJamActor { - agent = strings.TrimSpace(agent) - model = strings.TrimSpace(model) - if agent != "" { - return CampaignJamActor{Type: "agent", Name: agent, Agent: agent, Model: model} - } - return CampaignJamActor{Type: "human", Name: requestUser(r), Model: model} -} - -func jamNow() string { - return time.Now().UTC().Format(time.RFC3339Nano) -} - -func jamID(prefix string) string { - seq := atomic.AddUint64(&campaignJamIDSeq, 1) - return prefix + "-" + strings.ReplaceAll(time.Now().UTC().Format("20060102150405.000000000"), ".", "") + "-" + strconv.FormatUint(seq, 10) -} - -func sortJamState(state *CampaignJamState) { - sort.SliceStable(state.Threads, func(i, j int) bool { return state.Threads[i].UpdatedAt > state.Threads[j].UpdatedAt }) - sort.SliceStable(state.Suggestions, func(i, j int) bool { return state.Suggestions[i].CreatedAt > state.Suggestions[j].CreatedAt }) - sort.SliceStable(state.Polls, func(i, j int) bool { return state.Polls[i].CreatedAt > state.Polls[j].CreatedAt }) -} - -func (state *CampaignJamState) clone() *CampaignJamState { - if state == nil { - return nil - } - raw, _ := json.Marshal(state) - var out CampaignJamState - _ = json.Unmarshal(raw, &out) - return &out -} diff --git a/src/pkg/dashboard/api_campaigns_jam_agents.go b/src/pkg/dashboard/api_campaigns_jam_agents.go deleted file mode 100644 index dbe56eb9f7..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_agents.go +++ /dev/null @@ -1,113 +0,0 @@ -package dashboard - -import ( - "errors" - "net/http" - "strings" -) - -type campaignJamAgentRequest struct { - ThreadID string `json:"thread_id"` - Agent string `json:"agent"` - Model string `json:"model"` - Prompt string `json:"prompt"` - Reply string `json:"reply"` - ProposedText string `json:"proposed_text"` -} - -func (s *Server) handleCampaignJamAgentsPost(w http.ResponseWriter, r *http.Request) { - if !requireJamMaintainerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignJamAgentRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - agent := strings.TrimSpace(req.Agent) - if agent == "" { - agent = "spektacular" - } - model := strings.TrimSpace(req.Model) - if model == "" { - model = s.campaignJamAgentModel(agent) - } - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - return s.inviteCampaignJamAgent(state, req, agent, model) - }) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - s.auditFromRequest(r, "campaign_jam_agent_invite", auditDetail("campaign", id), agent) - jsonResponse(w, map[string]any{"ok": true, "jam": state}) -} - -func (s *Server) inviteCampaignJamAgent(state *CampaignJamState, req campaignJamAgentRequest, agent, model string) error { - if !s.campaignJamAgentAllowed(agent) { - return errors.New("agent is not configured for Jam replies") - } - threadID := strings.TrimSpace(req.ThreadID) - if threadID == "" { - return errors.New("thread_id required") - } - reply := strings.TrimSpace(req.Reply) - if reply == "" { - reply = campaignJamAgentReply(agent, strings.TrimSpace(req.Prompt)) - } - actor := CampaignJamActor{Type: "agent", Name: agent, Agent: agent, Model: model} - now := jamNow() - for i := range state.Threads { - thread := &state.Threads[i] - if thread.ID != threadID { - continue - } - thread.Comments = append(thread.Comments, CampaignComment{ID: jamID("comment"), Body: reply, Author: actor, CreatedAt: now}) - thread.UpdatedAt = now - proposed := strings.TrimSpace(req.ProposedText) - if proposed == "" { - proposed = campaignJamAgentSuggestionText(thread.Section, reply) - } - state.Suggestions = append(state.Suggestions, CampaignSuggestion{ - ID: jamID("suggestion"), ThreadID: thread.ID, Section: thread.Section, Body: "Agent-proposed spec text from " + agent, - ProposedText: proposed, Status: jamSuggestionOpen, Author: actor, CreatedAt: now, - }) - return nil - } - return errors.New("thread not found") -} - -func (s *Server) campaignJamAgentAllowed(agent string) bool { - if strings.EqualFold(agent, "spektacular") { - return true - } - if s != nil && s.deps != nil && s.deps.Config != nil { - _, ok := s.deps.Config.Agents[agent] - return ok - } - return false -} - -func (s *Server) campaignJamAgentModel(agent string) string { - if s != nil && s.deps != nil && s.deps.Config != nil { - if cfg, ok := s.deps.Config.Agents[agent]; ok { - return strings.TrimSpace(cfg.Model) - } - } - return "" -} - -func campaignJamAgentReply(agent, prompt string) string { - if prompt == "" { - return agent + " reviewed the Jam thread and proposed follow-up spec text." - } - return agent + " reviewed the Jam thread: " + prompt -} - -func campaignJamAgentSuggestionText(section, reply string) string { - if strings.TrimSpace(section) == "" { - return reply - } - return "Update " + strings.TrimSpace(section) + ":\n" + reply -} diff --git a/src/pkg/dashboard/api_campaigns_jam_agents_test.go b/src/pkg/dashboard/api_campaigns_jam_agents_test.go deleted file mode 100644 index 98b8cc197a..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_agents_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package dashboard - -import ( - "net/http" - "testing" - - "github.com/hivecommons/hive/pkg/config" -) - -func TestCampaignJamAgentInviteCreatesAttributedReplyAndSuggestion(t *testing.T) { - s := jamTestServer(t) - s.deps.Config.Agents["architect"] = config.AgentConfig{Model: "gpt-5.4", Enabled: true} - thread := jamPostAs(t, s, "/api/campaigns/spec-agent/jam/threads", "read-write", "alice", map[string]any{ - "section": "Goals", - "body": "Can an agent draft the reliability goal?", - }, false) - if thread.Code != http.StatusOK { - t.Fatalf("thread create = %d body=%s", thread.Code, thread.Body.String()) - } - jam := decodeJam(t, thread) - - invite := jamPostAs(t, s, "/api/campaigns/spec-agent/jam/agents", "owner", "maintainer", map[string]any{ - "thread_id": jam.Threads[0].ID, - "agent": "architect", - "reply": "Add a reliability target and owner.", - "proposed_text": "Reliability target: 99.9% availability with an on-call owner.", - }, true) - if invite.Code != http.StatusOK { - t.Fatalf("agent invite = %d body=%s", invite.Code, invite.Body.String()) - } - jam = decodeJam(t, invite) - if got := jam.Threads[0].Comments[len(jam.Threads[0].Comments)-1].Author; got.Type != "agent" || got.Name != "architect" || got.Model != "gpt-5.4" { - t.Fatalf("agent comment attribution = %+v", got) - } - if len(jam.Suggestions) != 1 || jam.Suggestions[0].Status != jamSuggestionOpen || jam.Suggestions[0].Author.Agent != "architect" { - t.Fatalf("agent suggestion = %+v", jam.Suggestions) - } - if len(jam.Revisions) != 0 { - t.Fatalf("agent invite must not auto-apply revisions: %+v", jam.Revisions) - } -} - -func TestCampaignJamAgentInvitePermissionBoundaries(t *testing.T) { - s := jamTestServer(t) - thread := jamPostAs(t, s, "/api/campaigns/spec-agent-perms/jam/threads", "read-write", "alice", map[string]any{ - "section": "Scope", - "body": "Ask for help", - }, false) - if thread.Code != http.StatusOK { - t.Fatalf("thread create = %d body=%s", thread.Code, thread.Body.String()) - } - jam := decodeJam(t, thread) - body := map[string]any{"thread_id": jam.Threads[0].ID, "agent": "spektacular"} - notMaintainer := jamPostAs(t, s, "/api/campaigns/spec-agent-perms/jam/agents", "read-write", "alice", body, false) - if notMaintainer.Code != http.StatusForbidden { - t.Fatalf("read-write invite = %d body=%s", notMaintainer.Code, notMaintainer.Body.String()) - } - unknown := jamPostAs(t, s, "/api/campaigns/spec-agent-perms/jam/agents", "owner", "maintainer", map[string]any{ - "thread_id": jam.Threads[0].ID, - "agent": "missing-agent", - }, true) - if unknown.Code != http.StatusBadRequest { - t.Fatalf("unknown agent invite = %d body=%s", unknown.Code, unknown.Body.String()) - } - allowed := jamPostAs(t, s, "/api/campaigns/spec-agent-perms/jam/agents", "owner", "maintainer", body, true) - if allowed.Code != http.StatusOK { - t.Fatalf("spektacular invite = %d body=%s", allowed.Code, allowed.Body.String()) - } -} diff --git a/src/pkg/dashboard/api_campaigns_jam_collections_test.go b/src/pkg/dashboard/api_campaigns_jam_collections_test.go deleted file mode 100644 index 329ba4a3ab..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_collections_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package dashboard - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" -) - -func jamGetAs(t *testing.T, s *Server, path, role, user string) *httptest.ResponseRecorder { - t.Helper() - req := httptest.NewRequest(http.MethodGet, path, nil) - req.Header.Set("X-Hive-Role", role) - req.Header.Set("X-Hive-User", user) - rec := httptest.NewRecorder() - s.mux.ServeHTTP(rec, req) - return rec -} - -func decodeJamCollection(t *testing.T, rec *httptest.ResponseRecorder, key string) []json.RawMessage { - t.Helper() - if rec.Code != http.StatusOK { - t.Fatalf("GET %s = %d body=%s", key, rec.Code, rec.Body.String()) - } - var resp map[string]json.RawMessage - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode %s: %v body=%s", key, err, rec.Body.String()) - } - if string(resp["ok"]) != "true" { - t.Fatalf("%s response not ok: %s", key, rec.Body.String()) - } - raw, present := resp[key] - if !present { - t.Fatalf("%s response missing %q key: %s", key, key, rec.Body.String()) - } - for _, other := range []string{"jam", "threads", "suggestions", "polls"} { - if other != key { - if _, leaked := resp[other]; leaked { - t.Fatalf("%s response also carries %q: %s", key, other, rec.Body.String()) - } - } - } - if string(raw) == "null" { - return nil - } - var items []json.RawMessage - if err := json.Unmarshal(raw, &items); err != nil { - t.Fatalf("decode %s items: %v raw=%s", key, err, raw) - } - return items -} - -func TestCampaignJamCollectionGetsReturnOnlyTheirSlice(t *testing.T) { - s := jamTestServer(t) - const base = "/api/campaigns/spec-collections/jam" - - for _, key := range []string{"threads", "suggestions", "polls"} { - if items := decodeJamCollection(t, jamGetAs(t, s, base+"/"+key, "read", "reader"), key); len(items) != 0 { - t.Fatalf("fresh campaign %s = %d items, want 0", key, len(items)) - } - } - - if rec := jamPostAs(t, s, base+"/threads", "read-write", "alice", map[string]any{ - "section": "Goals", "title": "Reviewers", "body": "Can we include async reviewers?", - }, false); rec.Code != http.StatusOK { - t.Fatalf("thread post = %d body=%s", rec.Code, rec.Body.String()) - } - if rec := jamPostAs(t, s, base+"/suggestions", "read-write", "bob", map[string]any{ - "section": "Goals", "proposed_text": "Include async reviewers.", - }, false); rec.Code != http.StatusOK { - t.Fatalf("suggestion post = %d body=%s", rec.Code, rec.Body.String()) - } - if rec := jamPostAs(t, s, base+"/polls", "read-write", "carol", map[string]any{ - "section": "Scope", "question": "Which milestone?", "options": []string{"alpha", "beta"}, - }, false); rec.Code != http.StatusOK { - t.Fatalf("poll post = %d body=%s", rec.Code, rec.Body.String()) - } - - threads := decodeJamCollection(t, jamGetAs(t, s, base+"/threads", "read", "reader"), "threads") - if len(threads) != 1 || !strings.Contains(string(threads[0]), `"section":"Goals"`) || !strings.Contains(string(threads[0]), `"title":"Reviewers"`) { - t.Fatalf("threads = %s", threads) - } - suggestions := decodeJamCollection(t, jamGetAs(t, s, base+"/suggestions", "read", "reader"), "suggestions") - if len(suggestions) != 1 || !strings.Contains(string(suggestions[0]), `"proposed_text":"Include async reviewers."`) { - t.Fatalf("suggestions = %s", suggestions) - } - polls := decodeJamCollection(t, jamGetAs(t, s, base+"/polls", "read", "reader"), "polls") - if len(polls) != 1 || !strings.Contains(string(polls[0]), `"question":"Which milestone?"`) { - t.Fatalf("polls = %s", polls) - } - - // Read-only callers may read every collection; the role gate is on writes only. - for _, key := range []string{"threads", "suggestions", "polls"} { - if rec := jamGetAs(t, s, base+"/"+key, "read", "reader"); rec.Code != http.StatusOK { - t.Fatalf("read role GET %s = %d body=%s", key, rec.Code, rec.Body.String()) - } - } - - // A different campaign id does not see this campaign's items. - for _, key := range []string{"threads", "suggestions", "polls"} { - if items := decodeJamCollection(t, jamGetAs(t, s, "/api/campaigns/spec-other/jam/"+key, "read", "reader"), key); len(items) != 0 { - t.Fatalf("other campaign %s = %d items, want 0", key, len(items)) - } - } -} - -func TestCampaignJamGetsReportUnreadableStore(t *testing.T) { - s := jamTestServer(t) - path := s.campaignJamPath() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil { - t.Fatal(err) - } - for _, suffix := range []string{"", "/threads", "/suggestions", "/polls"} { - rec := jamGetAs(t, s, "/api/campaigns/spec-broken/jam"+suffix, "owner", "owner") - if rec.Code != http.StatusBadRequest { - t.Fatalf("GET jam%s with corrupt store = %d body=%s", suffix, rec.Code, rec.Body.String()) - } - var resp struct { - OK bool `json:"ok"` - Error string `json:"error"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode error body: %v body=%s", err, rec.Body.String()) - } - if resp.OK || resp.Error == "" { - t.Fatalf("GET jam%s error body = %s", suffix, rec.Body.String()) - } - } - // The corrupt file is left alone: a read never rewrites the store. - raw, err := os.ReadFile(path) - if err != nil || string(raw) != "{not json" { - t.Fatalf("store after failed reads = %q err=%v", raw, err) - } -} - -func TestCampaignJamPollVoteChangeMovesCount(t *testing.T) { - s := jamTestServer(t) - const polls = "/api/campaigns/spec-votes/jam/polls" - create := jamPostAs(t, s, polls, "read-write", "alice", map[string]any{ - "section": "Storage", "question": "JSON or sqlite?", "options": []string{"json", "sqlite"}, - }, false) - if create.Code != http.StatusOK { - t.Fatalf("poll create = %d body=%s", create.Code, create.Body.String()) - } - jam := decodeJam(t, create) - pollID := jam.Polls[0].ID - jsonOpt, sqliteOpt := jam.Polls[0].Options[0].ID, jam.Polls[0].Options[1].ID - - vote := func(user, option string) *httptest.ResponseRecorder { - return jamPostAs(t, s, polls, "read-write", user, map[string]any{"action": "vote", "poll_id": pollID, "option_id": option}, false) - } - counts := func(rec *httptest.ResponseRecorder) (int, int, int) { - t.Helper() - if rec.Code != http.StatusOK { - t.Fatalf("vote = %d body=%s", rec.Code, rec.Body.String()) - } - poll := decodeJam(t, rec).Polls[0] - var j, q int - for _, option := range poll.Options { - switch option.ID { - case jsonOpt: - j = option.Count - case sqliteOpt: - q = option.Count - } - } - return j, q, len(poll.Votes) - } - - if j, q, n := counts(vote("bob", jsonOpt)); j != 1 || q != 0 || n != 1 { - t.Fatalf("after first vote json=%d sqlite=%d votes=%d", j, q, n) - } - if j, q, n := counts(vote("carol", jsonOpt)); j != 2 || q != 0 || n != 2 { - t.Fatalf("after second voter json=%d sqlite=%d votes=%d", j, q, n) - } - // Changing a vote moves the count instead of adding a second ballot. - if j, q, n := counts(vote("bob", sqliteOpt)); j != 1 || q != 1 || n != 2 { - t.Fatalf("after bob changed vote json=%d sqlite=%d votes=%d", j, q, n) - } - // Re-casting the same choice is idempotent on counts and ballots. - if j, q, n := counts(vote("bob", sqliteOpt)); j != 1 || q != 1 || n != 2 { - t.Fatalf("after bob repeated vote json=%d sqlite=%d votes=%d", j, q, n) - } - - for name, body := range map[string]map[string]any{ - "missing option": {"action": "vote", "poll_id": pollID}, - "missing poll": {"action": "vote", "option_id": jsonOpt}, - "unknown poll": {"action": "vote", "poll_id": "poll-nope", "option_id": jsonOpt}, - "unknown option": {"action": "vote", "poll_id": pollID, "option_id": "option-nope"}, - "unsupported verb": {"action": "tally", "poll_id": pollID}, - } { - rec := jamPostAs(t, s, polls, "read-write", "dave", body, false) - if rec.Code != http.StatusBadRequest { - t.Fatalf("%s: vote = %d body=%s", name, rec.Code, rec.Body.String()) - } - } - // Rejected votes did not disturb the tallies. - if j, q, n := counts(vote("carol", jsonOpt)); j != 1 || q != 1 || n != 2 { - t.Fatalf("after rejected votes json=%d sqlite=%d votes=%d", j, q, n) - } - - decide := jamPostAs(t, s, polls, "merger", "maintainer", map[string]any{ - "action": "decide", "poll_id": pollID, "outcome": "sqlite", "rationale": "queryable", - }, false) - if decide.Code != http.StatusOK { - t.Fatalf("decide = %d body=%s", decide.Code, decide.Body.String()) - } - closed := vote("erin", jsonOpt) - if closed.Code != http.StatusBadRequest || !strings.Contains(closed.Body.String(), "poll is closed") { - t.Fatalf("vote on decided poll = %d body=%s", closed.Code, closed.Body.String()) - } -} - -func TestDecrementPollOptionNeverGoesNegative(t *testing.T) { - poll := &CampaignPoll{Options: []CampaignPollOption{{ID: "a", Count: 0}, {ID: "b", Count: 2}}} - decrementPollOption(poll, "a") - decrementPollOption(poll, "missing") - decrementPollOption(poll, "b") - if poll.Options[0].Count != 0 || poll.Options[1].Count != 1 { - t.Fatalf("options after decrement = %+v", poll.Options) - } -} diff --git a/src/pkg/dashboard/api_campaigns_jam_live.go b/src/pkg/dashboard/api_campaigns_jam_live.go deleted file mode 100644 index 42e4d1d37b..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_live.go +++ /dev/null @@ -1,254 +0,0 @@ -package dashboard - -import ( - "errors" - "net/http" - "sync" - "time" - - "github.com/gorilla/websocket" - "github.com/hivecommons/hive/pkg/config" -) - -const ( - jamLiveSnapshot = "snapshot" - jamLivePresence = "presence" - jamLiveFocus = "focus" - jamLiveEdit = "edit" - jamLiveEditApplied = "edit_applied" - jamLiveConflict = "conflict" - jamLiveError = "error" -) - -type jamLiveMessage struct { - Type string `json:"type"` - ClientID string `json:"client_id,omitempty"` - Section string `json:"section,omitempty"` - Content string `json:"content,omitempty"` - BaseRevisionID string `json:"base_revision_id,omitempty"` - Reason string `json:"reason,omitempty"` - RevisionID string `json:"revision_id,omitempty"` - Expected string `json:"expected_revision_id,omitempty"` - Presence []CampaignJamParticipant `json:"presence,omitempty"` - Actor *CampaignJamActor `json:"actor,omitempty"` - Jam *CampaignJamState `json:"jam,omitempty"` - Error string `json:"error,omitempty"` -} - -type CampaignJamParticipant struct { - ClientID string `json:"client_id"` - Actor CampaignJamActor `json:"actor"` - Section string `json:"section,omitempty"` - Connected string `json:"connected_at"` - Seen string `json:"seen_at"` -} - -type jamLiveClient struct { - id string - campaign string - role string - section string - actor CampaignJamActor - conn *websocket.Conn - send chan jamLiveMessage - hub *jamLiveHub -} - -type jamLiveHub struct { - mu sync.Mutex - clients map[string]*jamLiveClient -} - -var ( - jamLiveHubsMu sync.Mutex - jamLiveHubs = map[string]*jamLiveHub{} - // SECURITY: same-origin CheckOrigin (shared with contribute_ws). The jam - // socket authenticates via the dashboard session cookie, which browsers - // also attach cross-site; allowing every Origin here let any web page a - // logged-in operator visited read the full jam state and push live spec - // edits with the victim's role (cross-site WebSocket hijacking). - jamLiveUpgrader = websocket.Upgrader{CheckOrigin: wsSameOrigin} -) - -func (s *Server) handleCampaignJamWebSocket(w http.ResponseWriter, r *http.Request) { - if !config.RoleAtLeast(r.Header.Get("X-Hive-Role"), config.RoleRead) { - jsonError(w, "read access required", http.StatusForbidden) - return - } - campaignID := campaignIDFromRequest(r) - if campaignID == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - conn, err := jamLiveUpgrader.Upgrade(w, r, nil) - if err != nil { - return - } - actor := jamActorFromRequest(r, r.URL.Query().Get("agent"), r.URL.Query().Get("model")) - client := &jamLiveClient{ - id: jamID("client"), - campaign: campaignID, - role: r.Header.Get("X-Hive-Role"), - actor: actor, - conn: conn, - send: make(chan jamLiveMessage, 16), - hub: jamHubForCampaign(campaignID), - } - client.hub.add(client) - state, err := s.loadCampaignJam(campaignID) - if err != nil { - client.enqueue(jamLiveMessage{Type: jamLiveError, Error: err.Error()}) - } else { - client.enqueue(jamLiveMessage{Type: jamLiveSnapshot, ClientID: client.id, Presence: client.hub.presence(), Jam: state}) - } - client.hub.broadcast(jamLiveMessage{Type: jamLivePresence, Presence: client.hub.presence()}) - - done := make(chan struct{}) - go client.writeLoop(done) - client.readLoop(s) - close(done) - client.hub.remove(client.id) - client.hub.broadcast(jamLiveMessage{Type: jamLivePresence, Presence: client.hub.presence()}) -} - -func jamHubForCampaign(campaign string) *jamLiveHub { - jamLiveHubsMu.Lock() - defer jamLiveHubsMu.Unlock() - hub := jamLiveHubs[campaign] - if hub == nil { - hub = &jamLiveHub{clients: map[string]*jamLiveClient{}} - jamLiveHubs[campaign] = hub - } - return hub -} - -func (h *jamLiveHub) add(c *jamLiveClient) { - h.mu.Lock() - defer h.mu.Unlock() - h.clients[c.id] = c -} - -func (h *jamLiveHub) remove(id string) { - h.mu.Lock() - defer h.mu.Unlock() - delete(h.clients, id) -} - -func (h *jamLiveHub) broadcast(msg jamLiveMessage) { - h.mu.Lock() - defer h.mu.Unlock() - for _, client := range h.clients { - client.enqueueLocked(msg) - } -} - -func (h *jamLiveHub) presence() []CampaignJamParticipant { - h.mu.Lock() - defer h.mu.Unlock() - return h.presenceLocked() -} - -func (h *jamLiveHub) presenceLocked() []CampaignJamParticipant { - out := make([]CampaignJamParticipant, 0, len(h.clients)) - for _, client := range h.clients { - out = append(out, CampaignJamParticipant{ClientID: client.id, Actor: client.actor, Section: client.section, Connected: client.connectedAt(), Seen: jamNow()}) - } - return out -} - -func (c *jamLiveClient) connectedAt() string { - return c.id[len("client-") : len("client-")+23] -} - -func (c *jamLiveClient) enqueue(msg jamLiveMessage) { - c.hub.mu.Lock() - defer c.hub.mu.Unlock() - c.enqueueLocked(msg) -} - -func (c *jamLiveClient) enqueueLocked(msg jamLiveMessage) { - select { - case c.send <- msg: - default: - } -} - -func (c *jamLiveClient) writeLoop(done <-chan struct{}) { - for { - select { - case msg := <-c.send: - _ = c.conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) - if err := c.conn.WriteJSON(msg); err != nil { - return - } - case <-done: - return - } - } -} - -func (c *jamLiveClient) readLoop(s *Server) { - defer c.conn.Close() - for { - var msg jamLiveMessage - if err := c.conn.ReadJSON(&msg); err != nil { - return - } - switch msg.Type { - case jamLiveFocus: - c.setFocus(msg.Section) - case jamLiveEdit: - c.applyEdit(s, msg) - default: - c.enqueue(jamLiveMessage{Type: jamLiveError, Error: "unsupported jam live message"}) - } - } -} - -func (c *jamLiveClient) setFocus(section string) { - c.hub.mu.Lock() - if live := c.hub.clients[c.id]; live != nil { - live.actor = c.actor - live.section = section - } - presence := make([]CampaignJamParticipant, 0, len(c.hub.clients)) - for _, client := range c.hub.clients { - presence = append(presence, CampaignJamParticipant{ClientID: client.id, Actor: client.actor, Section: client.section, Connected: client.connectedAt(), Seen: jamNow()}) - } - for _, client := range c.hub.clients { - client.enqueueLocked(jamLiveMessage{Type: jamLivePresence, Presence: presence}) - } - c.hub.mu.Unlock() -} - -func (c *jamLiveClient) applyEdit(s *Server, msg jamLiveMessage) { - if !config.RoleAtLeast(c.role, config.RoleReadWrite) { - c.enqueue(jamLiveMessage{Type: jamLiveError, Error: "read-write access required"}) - return - } - var revisionID string - state, err := s.mutateCampaignJam(c.campaign, func(state *CampaignJamState) error { - if msg.BaseRevisionID != state.SpecRevisionID { - return errJamLiveConflict - } - rev := recordJamRevision(state, msg.Content, firstRunNonEmpty(msg.Reason, "live co-edit"), c.actor, nil) - revisionID = rev.ID - return nil - }) - if errors.Is(err, errJamLiveConflict) { - current, _ := s.loadCampaignJam(c.campaign) - expected := "" - if current != nil { - expected = current.SpecRevisionID - } - c.enqueue(jamLiveMessage{Type: jamLiveConflict, Expected: expected, Jam: current}) - return - } - if err != nil { - c.enqueue(jamLiveMessage{Type: jamLiveError, Error: err.Error()}) - return - } - c.hub.broadcast(jamLiveMessage{Type: jamLiveEditApplied, RevisionID: revisionID, Jam: state, Actor: &c.actor}) -} - -var errJamLiveConflict = errors.New("jam live edit conflict") diff --git a/src/pkg/dashboard/api_campaigns_jam_live_test.go b/src/pkg/dashboard/api_campaigns_jam_live_test.go deleted file mode 100644 index 5e311d16cf..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_live_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package dashboard - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/gorilla/websocket" -) - -func jamLiveDial(t *testing.T, srv *httptest.Server, user, role string) *websocket.Conn { - t.Helper() - header := http.Header{} - header.Set("X-Hive-User", user) - header.Set("X-Hive-Role", role) - wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/api/campaigns/spec-live/jam/ws" - conn, _, err := websocket.DefaultDialer.Dial(wsURL, header) - if err != nil { - t.Fatalf("dial jam websocket: %v", err) - } - t.Cleanup(func() { _ = conn.Close() }) - return conn -} - -func readJamLiveUntil(t *testing.T, conn *websocket.Conn, want string, match func(jamLiveMessage) bool) jamLiveMessage { - t.Helper() - // One deadline for the whole wait: gorilla/websocket marks the connection - // permanently failed after any read error (a deadline timeout included), so - // retrying ReadJSON after a short timeout panics with "repeated read on - // failed websocket connection" instead of waiting for the next frame. - if err := conn.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { - t.Fatalf("set read deadline: %v", err) - } - for { - var msg jamLiveMessage - if err := conn.ReadJSON(&msg); err != nil { - if strings.Contains(err.Error(), "i/o timeout") { - t.Fatalf("timed out waiting for live message %s", want) - } - t.Fatalf("read live message %s: %v", want, err) - } - if msg.Type == want && (match == nil || match(msg)) { - return msg - } - } -} - -// jamLiveQuietGap is the silence TestReadJamLiveUntilWaitsPastShortGaps puts -// between the client's "ready" frame and the server's snapshot. It must stay -// longer than any per-read poll interval readJamLiveUntil might apply (the -// retired implementation used 250 ms); the test fails if it is not honoured. -const jamLiveQuietGap = 300 * time.Millisecond - -// TestReadJamLiveUntilWaitsPastShortGaps guards the helper above: a frame that -// arrives after a quiet gap longer than any per-read poll interval must still -// be delivered rather than tripping gorilla's failed-connection panic. -func TestReadJamLiveUntilWaitsPastShortGaps(t *testing.T) { - upgrader := websocket.Upgrader{} - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - return - } - defer conn.Close() - // Hand-off by signal: the client writes a frame once it is about to - // block in readJamLiveUntil, so the quiet gap below is measured from a - // known point rather than from an arbitrary moment after the dial. - if _, _, err := conn.ReadMessage(); err != nil { - return - } - // Simulate a slow producer: the socket stays silent for longer than the - // per-read poll the helper used to apply before the snapshot lands. - <-time.After(jamLiveQuietGap) - _ = conn.WriteJSON(jamLiveMessage{Type: jamLiveSnapshot}) - // Keep the socket open until the client is done reading. - _, _, _ = conn.ReadMessage() - })) - t.Cleanup(srv.Close) - - conn, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil) - if err != nil { - t.Fatalf("dial: %v", err) - } - t.Cleanup(func() { _ = conn.Close() }) - - // The test goroutine is the only reader on conn: gorilla/websocket allows - // one concurrent reader per connection, so the ready signal is a write. - if err := conn.WriteJSON(jamLiveMessage{Type: jamLiveFocus}); err != nil { - t.Fatalf("write ready signal: %v", err) - } - started := time.Now() - got := readJamLiveUntil(t, conn, jamLiveSnapshot, nil) - if got.Type != jamLiveSnapshot { - t.Fatalf("message type = %q, want %q", got.Type, jamLiveSnapshot) - } - if waited := time.Since(started); waited < jamLiveQuietGap { - t.Fatalf("snapshot arrived after %v, want a quiet gap of at least %v", waited, jamLiveQuietGap) - } -} - -func TestCampaignJamLiveRejectsCrossOriginHandshake(t *testing.T) { - s := jamTestServer(t) - httpSrv := httptest.NewServer(s.mux) - t.Cleanup(httpSrv.Close) - - wsURL := "ws" + strings.TrimPrefix(httpSrv.URL, "http") + "/api/campaigns/spec-live/jam/ws" - - header := http.Header{} - header.Set("X-Hive-Role", "read-write") - header.Set("Origin", "https://evil.example") - conn, resp, err := websocket.DefaultDialer.Dial(wsURL, header) - if err == nil { - conn.Close() - t.Fatal("cross-origin jam websocket handshake succeeded, want rejection") - } - if resp == nil || resp.StatusCode != http.StatusForbidden { - t.Fatalf("cross-origin handshake response = %+v, want 403", resp) - } - - header.Set("Origin", httpSrv.URL) - conn, _, err = websocket.DefaultDialer.Dial(wsURL, header) - if err != nil { - t.Fatalf("same-origin jam websocket handshake failed: %v", err) - } - conn.Close() -} - -func TestCampaignJamLivePresenceFocusAndReconnect(t *testing.T) { - s := jamTestServer(t) - httpSrv := httptest.NewServer(s.mux) - t.Cleanup(httpSrv.Close) - - alice := jamLiveDial(t, httpSrv, "alice", "read-write") - _ = readJamLiveUntil(t, alice, jamLiveSnapshot, nil) - bob := jamLiveDial(t, httpSrv, "bob", "read-write") - _ = readJamLiveUntil(t, bob, jamLiveSnapshot, nil) - _ = readJamLiveUntil(t, alice, jamLivePresence, func(msg jamLiveMessage) bool { - return len(msg.Presence) == 2 - }) - - if err := alice.WriteJSON(jamLiveMessage{Type: jamLiveFocus, Section: "Goals"}); err != nil { - t.Fatalf("write focus: %v", err) - } - focused := readJamLiveUntil(t, bob, jamLivePresence, func(msg jamLiveMessage) bool { - for _, participant := range msg.Presence { - if participant.Actor.Name == "alice" && participant.Section == "Goals" { - return true - } - } - return false - }) - if len(focused.Presence) != 2 { - t.Fatalf("focused presence participants = %d, want 2", len(focused.Presence)) - } - - if err := bob.Close(); err != nil { - t.Fatalf("close bob: %v", err) - } - _ = readJamLiveUntil(t, alice, jamLivePresence, func(msg jamLiveMessage) bool { - return len(msg.Presence) == 1 - }) - bob = jamLiveDial(t, httpSrv, "bob", "read-write") - reconnected := readJamLiveUntil(t, bob, jamLiveSnapshot, nil) - if len(reconnected.Presence) != 2 { - t.Fatalf("reconnected presence = %+v, want alice and bob", reconnected.Presence) - } -} - -func TestCampaignJamLiveConflictingEdits(t *testing.T) { - s := jamTestServer(t) - httpSrv := httptest.NewServer(s.mux) - t.Cleanup(httpSrv.Close) - - alice := jamLiveDial(t, httpSrv, "alice", "read-write") - bob := jamLiveDial(t, httpSrv, "bob", "read-write") - aliceSnapshot := readJamLiveUntil(t, alice, jamLiveSnapshot, nil) - bobSnapshot := readJamLiveUntil(t, bob, jamLiveSnapshot, nil) - if aliceSnapshot.Jam.SpecRevisionID != "" || bobSnapshot.Jam.SpecRevisionID != "" { - t.Fatalf("new jam revisions = %q/%q, want empty", aliceSnapshot.Jam.SpecRevisionID, bobSnapshot.Jam.SpecRevisionID) - } - - if err := alice.WriteJSON(jamLiveMessage{Type: jamLiveEdit, BaseRevisionID: "", Content: "## Goals\nAlice"}); err != nil { - t.Fatalf("write alice edit: %v", err) - } - applied := readJamLiveUntil(t, alice, jamLiveEditApplied, nil) - if applied.RevisionID == "" || applied.Jam.SpecContent != "## Goals\nAlice" { - t.Fatalf("applied edit = %+v", applied) - } - - if err := bob.WriteJSON(jamLiveMessage{Type: jamLiveEdit, BaseRevisionID: "", Content: "## Goals\nBob"}); err != nil { - t.Fatalf("write stale bob edit: %v", err) - } - conflict := readJamLiveUntil(t, bob, jamLiveConflict, nil) - if conflict.Expected != applied.RevisionID || conflict.Jam.SpecContent != "## Goals\nAlice" { - t.Fatalf("conflict = %+v, want expected %s and alice content", conflict, applied.RevisionID) - } - - get := doOwnerGet(s, "/api/campaigns/spec-live/jam") - jam := decodeJam(t, get) - if jam.SpecContent != "## Goals\nAlice" || len(jam.Revisions) != 1 { - t.Fatalf("stale edit overwrote state: %+v", jam) - } -} diff --git a/src/pkg/dashboard/api_campaigns_jam_projects.go b/src/pkg/dashboard/api_campaigns_jam_projects.go deleted file mode 100644 index 27208fb058..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_projects.go +++ /dev/null @@ -1,285 +0,0 @@ -package dashboard - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "os" - "strings" - "time" -) - -const ( - jamProjectSyncEndpointEnv = "HIVE_JAM_PROJECT_SYNC_URL" - jamProjectSyncTokenEnv = "HIVE_JAM_PROJECT_SYNC_TOKEN" - jamProjectSyncDefaultURL = "https://api.github.com/graphql" - jamProjectSyncGitHubHost = "api.github.com" - jamProjectSyncTimeout = 10 * time.Second -) - -// jamProjectSyncAuth resolves the sync endpoint and the bearer token it may -// receive. GITHUB_TOKEN is only ever sent to api.github.com over https; a -// custom endpoint gets HIVE_JAM_PROJECT_SYNC_TOKEN instead, and plain http is -// allowed only for loopback hosts so no credential crosses the network in -// cleartext (#8811). -func jamProjectSyncAuth(endpoint string) (string, string, error) { - u, err := url.Parse(endpoint) - if err != nil || u.Host == "" { - return "", "", fmt.Errorf("%s is not a valid URL", jamProjectSyncEndpointEnv) - } - host := u.Hostname() - switch u.Scheme { - case "https": - case "http": - if !jamProjectSyncLoopback(host) { - return "", "", fmt.Errorf("%s must use https (http is allowed only for loopback hosts)", jamProjectSyncEndpointEnv) - } - default: - return "", "", fmt.Errorf("%s must use https", jamProjectSyncEndpointEnv) - } - if u.Scheme == "https" && strings.EqualFold(host, jamProjectSyncGitHubHost) { - token := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")) - if token == "" { - return "", "", errors.New("GITHUB_TOKEN required for GitHub Projects sync") - } - return u.String(), token, nil - } - return u.String(), strings.TrimSpace(os.Getenv(jamProjectSyncTokenEnv)), nil -} - -func jamProjectSyncLoopback(host string) bool { - if strings.EqualFold(host, "localhost") { - return true - } - ip := net.ParseIP(host) - return ip != nil && ip.IsLoopback() -} - -type campaignProjectSyncRequest struct { - Action string `json:"action"` - ProjectURL string `json:"project_url"` - ProjectID string `json:"project_id"` - ItemType string `json:"item_type"` - ExternalID string `json:"external_id"` - Status string `json:"status"` -} - -type campaignProjectSyncPayload struct { - CampaignID string `json:"campaign_id"` - ProjectURL string `json:"project_url,omitempty"` - ProjectID string `json:"project_id,omitempty"` - Spec string `json:"spec,omitempty"` - Decisions []CampaignDecision `json:"decisions,omitempty"` - Items []CampaignProjectItem `json:"items,omitempty"` -} - -func (s *Server) handleCampaignJamProjectSyncGet(w http.ResponseWriter, r *http.Request) { - state, err := s.loadCampaignJam(campaignIDFromRequest(r)) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "project_sync": state.ProjectSync}) -} - -func (s *Server) handleCampaignJamProjectSyncPost(w http.ResponseWriter, r *http.Request) { - if !requireJamMaintainerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - var req campaignProjectSyncRequest - if err := decodeBody(r, &req); err != nil { - jsonError(w, "invalid request body", http.StatusBadRequest) - return - } - action := firstRunNonEmpty(strings.TrimSpace(req.Action), "sync") - switch action { - case "enable", "disable", "inbound_status": - state, err := s.mutateCampaignJam(id, func(state *CampaignJamState) error { - return updateCampaignProjectSync(state, req, action) - }) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - jsonResponse(w, map[string]any{"ok": true, "jam": state, "project_sync": state.ProjectSync}) - case "sync": - s.syncCampaignJamProject(w, r, id) - default: - jsonError(w, "unsupported project sync action", http.StatusBadRequest) - } -} - -func updateCampaignProjectSync(state *CampaignJamState, req campaignProjectSyncRequest, action string) error { - if state.ProjectSync == nil { - state.ProjectSync = &CampaignProjectSync{} - } - switch action { - case "enable": - projectURL := strings.TrimSpace(req.ProjectURL) - projectID := strings.TrimSpace(req.ProjectID) - if projectURL == "" && projectID == "" { - return errors.New("project_url or project_id required") - } - state.ProjectSync.Enabled = true - state.ProjectSync.ProjectURL = projectURL - state.ProjectSync.ProjectID = projectID - state.ProjectSync.LastStatus = "enabled" - state.ProjectSync.LastError = "" - state.ProjectSync.RetryAdvice = "" - case "disable": - state.ProjectSync.Enabled = false - state.ProjectSync.LastStatus = "disabled" - case "inbound_status": - status := strings.TrimSpace(req.Status) - if status == "" { - return errors.New("status required") - } - itemType := firstRunNonEmpty(strings.TrimSpace(req.ItemType), "status") - externalID := strings.TrimSpace(req.ExternalID) - now := jamNow() - state.ProjectSync.LastStatus = status - state.ProjectSync.LastError = "" - state.ProjectSync.RetryAdvice = "" - state.ProjectSync.PublishedItems = append(state.ProjectSync.PublishedItems, CampaignProjectItem{ - Type: itemType, Title: "Inbound project status", Status: status, ExternalID: externalID, UpdatedAt: now, - }) - } - return nil -} - -func (s *Server) syncCampaignJamProject(w http.ResponseWriter, r *http.Request, id string) { - state, err := s.loadCampaignJam(id) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - if state.ProjectSync == nil || !state.ProjectSync.Enabled { - jsonError(w, "project sync is disabled", http.StatusBadRequest) - return - } - payload := buildCampaignProjectSyncPayload(state) - if err := postCampaignProjectSync(payload); err != nil { - _, _ = s.mutateCampaignJam(id, func(state *CampaignJamState) error { - if state.ProjectSync == nil { - state.ProjectSync = &CampaignProjectSync{} - } - state.ProjectSync.LastStatus = "failed" - state.ProjectSync.LastError = err.Error() - state.ProjectSync.RetryAdvice = "Verify the GitHub token, project link, and retry project sync from the Jam tab." - return nil - }) - jsonError(w, err.Error(), http.StatusBadGateway) - return - } - state, err = s.mutateCampaignJam(id, func(state *CampaignJamState) error { - state.ProjectSync.LastStatus = "synced" - state.ProjectSync.LastSyncAt = jamNow() - state.ProjectSync.LastError = "" - state.ProjectSync.RetryAdvice = "" - state.ProjectSync.PublishedItems = payload.Items - return nil - }) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - s.auditFromRequest(r, "campaign_jam_project_sync", auditDetail("campaign", id), "") - jsonResponse(w, map[string]any{"ok": true, "jam": state, "project_sync": state.ProjectSync}) -} - -func buildCampaignProjectSyncPayload(state *CampaignJamState) campaignProjectSyncPayload { - payload := campaignProjectSyncPayload{ - CampaignID: state.CampaignID, - ProjectURL: state.ProjectSync.ProjectURL, - ProjectID: state.ProjectSync.ProjectID, - Spec: state.SpecContent, - Decisions: campaignProjectDecisions(state), - Items: campaignProjectItems(state), - } - return payload -} - -func campaignProjectDecisions(state *CampaignJamState) []CampaignDecision { - var decisions []CampaignDecision - for _, poll := range state.Polls { - if poll.Decision != nil { - decisions = append(decisions, *poll.Decision) - } - } - for _, rev := range state.Revisions { - decisions = append(decisions, rev.Decisions...) - } - return decisions -} - -func campaignProjectItems(state *CampaignJamState) []CampaignProjectItem { - now := jamNow() - items := []CampaignProjectItem{{ - Type: "spec", Title: "Campaign spec " + state.CampaignID, Body: state.SpecContent, Status: state.ProjectSync.LastStatus, ExternalID: state.SpecRevisionID, UpdatedAt: now, - }} - for _, poll := range state.Polls { - if poll.Decision == nil { - continue - } - items = append(items, CampaignProjectItem{ - Type: "decision", Title: poll.Question, Body: poll.Decision.Rationale, Status: poll.Decision.Outcome, ExternalID: poll.ID, UpdatedAt: now, - }) - } - for _, suggestion := range state.Suggestions { - items = append(items, CampaignProjectItem{ - Type: "derived_issue", Title: suggestion.Section, Body: suggestion.ProposedText, Status: suggestion.Status, ExternalID: suggestion.ID, UpdatedAt: now, - }) - } - return items -} - -func postCampaignProjectSync(payload campaignProjectSyncPayload) error { - endpoint := strings.TrimSpace(os.Getenv(jamProjectSyncEndpointEnv)) - if endpoint == "" { - endpoint = jamProjectSyncDefaultURL - } - endpoint, token, err := jamProjectSyncAuth(endpoint) - if err != nil { - return err - } - body := map[string]any{ - "query": "mutation HiveJamProjectSync($input: JSON!) { hiveJamProjectSync(input: $input) { ok } }", - "variables": map[string]any{"input": payload}, - } - raw, err := json.Marshal(body) - if err != nil { - return err - } - req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(raw)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - if token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - client := &http.Client{Timeout: jamProjectSyncTimeout} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - var decoded struct { - Errors []struct { - Message string `json:"message"` - } `json:"errors"` - } - _ = json.NewDecoder(resp.Body).Decode(&decoded) - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return fmt.Errorf("github projects sync failed with status %d", resp.StatusCode) - } - if len(decoded.Errors) > 0 { - return errors.New(decoded.Errors[0].Message) - } - return nil -} diff --git a/src/pkg/dashboard/api_campaigns_jam_projects_test.go b/src/pkg/dashboard/api_campaigns_jam_projects_test.go deleted file mode 100644 index b624c1043e..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_projects_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package dashboard - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "testing" -) - -func TestCampaignJamProjectSyncInitialPublish(t *testing.T) { - s := jamTestServer(t) - var captured campaignProjectSyncPayload - api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var body struct { - Variables struct { - Input campaignProjectSyncPayload `json:"input"` - } `json:"variables"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - t.Fatalf("decode project sync request: %v", err) - } - captured = body.Variables.Input - _, _ = w.Write([]byte(`{"data":{"hiveJamProjectSync":{"ok":true}}}`)) - })) - t.Cleanup(api.Close) - t.Setenv(jamProjectSyncEndpointEnv, api.URL) - - seed := jamPostAs(t, s, "/api/campaigns/spec-project/jam", "read-write", "alice", map[string]any{"spec_content": "## Goals\nShip together"}, false) - if seed.Code != http.StatusOK { - t.Fatalf("seed = %d body=%s", seed.Code, seed.Body.String()) - } - suggestion := jamPostAs(t, s, "/api/campaigns/spec-project/jam/suggestions", "read-write", "alice", map[string]any{ - "section": "Goals", - "proposed_text": "Add Projects sync", - }, false) - if suggestion.Code != http.StatusOK { - t.Fatalf("suggestion = %d body=%s", suggestion.Code, suggestion.Body.String()) - } - enable := jamPostAs(t, s, "/api/campaigns/spec-project/jam/project-sync", "owner", "maintainer", map[string]any{ - "action": "enable", - "project_url": "https://github.com/orgs/hivecommons/projects/7", - }, true) - if enable.Code != http.StatusOK { - t.Fatalf("enable sync = %d body=%s", enable.Code, enable.Body.String()) - } - sync := jamPostAs(t, s, "/api/campaigns/spec-project/jam/project-sync", "owner", "maintainer", map[string]any{"action": "sync"}, true) - if sync.Code != http.StatusOK { - t.Fatalf("sync = %d body=%s", sync.Code, sync.Body.String()) - } - jam := decodeJam(t, sync) - if jam.ProjectSync == nil || jam.ProjectSync.LastStatus != "synced" || len(jam.ProjectSync.PublishedItems) < 2 { - t.Fatalf("project sync state = %+v", jam.ProjectSync) - } - if captured.ProjectURL == "" || captured.Spec == "" || len(captured.Items) < 2 { - t.Fatalf("captured payload = %+v", captured) - } -} - -func TestCampaignJamProjectSyncInboundStatusPreservesDecisions(t *testing.T) { - s := jamTestServer(t) - create := jamPostAs(t, s, "/api/campaigns/spec-project-status/jam/polls", "read-write", "alice", map[string]any{ - "section": "Scope", "question": "Track status?", "options": []string{"yes", "no"}, - }, false) - if create.Code != http.StatusOK { - t.Fatalf("poll create = %d body=%s", create.Code, create.Body.String()) - } - jam := decodeJam(t, create) - decide := jamPostAs(t, s, "/api/campaigns/spec-project-status/jam/polls", "owner", "maintainer", map[string]any{ - "action": "decide", "poll_id": jam.Polls[0].ID, "outcome": "yes", "rationale": "Need visibility", - }, true) - if decide.Code != http.StatusOK { - t.Fatalf("poll decide = %d body=%s", decide.Code, decide.Body.String()) - } - enable := jamPostAs(t, s, "/api/campaigns/spec-project-status/jam/project-sync", "owner", "maintainer", map[string]any{ - "action": "enable", "project_id": "PVT_kwDOB", - }, true) - if enable.Code != http.StatusOK { - t.Fatalf("enable = %d body=%s", enable.Code, enable.Body.String()) - } - inbound := jamPostAs(t, s, "/api/campaigns/spec-project-status/jam/project-sync", "owner", "maintainer", map[string]any{ - "action": "inbound_status", "item_type": "derived_issue", "external_id": "item-1", "status": "Done", - }, true) - if inbound.Code != http.StatusOK { - t.Fatalf("inbound = %d body=%s", inbound.Code, inbound.Body.String()) - } - jam = decodeJam(t, inbound) - if jam.ProjectSync.LastStatus != "Done" || len(jam.Revisions) != 1 || len(jam.Revisions[0].Decisions) != 1 { - t.Fatalf("inbound status lost decision data: sync=%+v revisions=%+v", jam.ProjectSync, jam.Revisions) - } -} - -func TestCampaignJamProjectSyncDisabledAndFailureHandling(t *testing.T) { - s := jamTestServer(t) - called := false - api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - http.Error(w, "boom", http.StatusBadGateway) - })) - t.Cleanup(api.Close) - t.Setenv(jamProjectSyncEndpointEnv, api.URL) - - disabled := jamPostAs(t, s, "/api/campaigns/spec-project-fail/jam/project-sync", "owner", "maintainer", map[string]any{"action": "sync"}, true) - if disabled.Code != http.StatusBadRequest || called { - t.Fatalf("disabled sync code=%d called=%v body=%s", disabled.Code, called, disabled.Body.String()) - } - enable := jamPostAs(t, s, "/api/campaigns/spec-project-fail/jam/project-sync", "owner", "maintainer", map[string]any{"action": "enable", "project_id": "PVT_fail"}, true) - if enable.Code != http.StatusOK { - t.Fatalf("enable = %d body=%s", enable.Code, enable.Body.String()) - } - failed := jamPostAs(t, s, "/api/campaigns/spec-project-fail/jam/project-sync", "owner", "maintainer", map[string]any{"action": "sync"}, true) - if failed.Code != http.StatusBadGateway { - t.Fatalf("failed sync = %d body=%s", failed.Code, failed.Body.String()) - } - get := doOwnerGet(s, "/api/campaigns/spec-project-fail/jam") - jam := decodeJam(t, get) - if jam.ProjectSync.LastStatus != "failed" || jam.ProjectSync.LastError == "" || jam.ProjectSync.RetryAdvice == "" { - t.Fatalf("failure state not visible: %+v", jam.ProjectSync) - } -} - -func TestJamProjectSyncAuthRestrictsGitHubToken(t *testing.T) { - const githubToken = "gh-secret" - const customToken = "custom-secret" - t.Setenv("GITHUB_TOKEN", githubToken) - t.Setenv(jamProjectSyncTokenEnv, customToken) - - cases := []struct { - name string - endpoint string - wantToken string - wantErr bool - }{ - {name: "default github endpoint", endpoint: jamProjectSyncDefaultURL, wantToken: githubToken}, - {name: "custom https endpoint gets custom token", endpoint: "https://sync.example.com/graphql", wantToken: customToken}, - {name: "github host over http is not trusted", endpoint: "http://api.github.com/graphql", wantErr: true}, - {name: "plain http to remote host rejected", endpoint: "http://sync.example.com/graphql", wantErr: true}, - {name: "loopback http allowed", endpoint: "http://127.0.0.1:8080/graphql", wantToken: customToken}, - {name: "localhost http allowed", endpoint: "http://localhost:8080/graphql", wantToken: customToken}, - {name: "unsupported scheme rejected", endpoint: "ftp://sync.example.com/graphql", wantErr: true}, - {name: "invalid url rejected", endpoint: "not a url", wantErr: true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - _, token, err := jamProjectSyncAuth(tc.endpoint) - if tc.wantErr { - if err == nil { - t.Fatalf("jamProjectSyncAuth(%q) err = nil, want error", tc.endpoint) - } - return - } - if err != nil { - t.Fatalf("jamProjectSyncAuth(%q) err = %v", tc.endpoint, err) - } - if token != tc.wantToken { - t.Fatalf("jamProjectSyncAuth(%q) token = %q, want %q", tc.endpoint, token, tc.wantToken) - } - }) - } -} - -func TestJamProjectSyncAuthRequiresGitHubTokenForGitHub(t *testing.T) { - t.Setenv("GITHUB_TOKEN", "") - if _, _, err := jamProjectSyncAuth(jamProjectSyncDefaultURL); err == nil { - t.Fatal("jamProjectSyncAuth without GITHUB_TOKEN err = nil, want error") - } -} - -func TestCampaignJamProjectSyncDoesNotForwardGitHubTokenToCustomEndpoint(t *testing.T) { - s := jamTestServer(t) - authHeader := make(chan string, 1) - api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authHeader <- r.Header.Get("Authorization") - _, _ = w.Write([]byte(`{"data":{"hiveJamProjectSync":{"ok":true}}}`)) - })) - t.Cleanup(api.Close) - t.Setenv(jamProjectSyncEndpointEnv, api.URL) - t.Setenv("GITHUB_TOKEN", "gh-secret") - t.Setenv(jamProjectSyncTokenEnv, "") - - enable := jamPostAs(t, s, "/api/campaigns/spec-project-token/jam/project-sync", "owner", "maintainer", map[string]any{"action": "enable", "project_id": "PVT_token"}, true) - if enable.Code != http.StatusOK { - t.Fatalf("enable = %d body=%s", enable.Code, enable.Body.String()) - } - sync := jamPostAs(t, s, "/api/campaigns/spec-project-token/jam/project-sync", "owner", "maintainer", map[string]any{"action": "sync"}, true) - if sync.Code != http.StatusOK { - t.Fatalf("sync = %d body=%s", sync.Code, sync.Body.String()) - } - if got := <-authHeader; got != "" { - t.Fatalf("custom endpoint received Authorization %q, want none", got) - } -} diff --git a/src/pkg/dashboard/api_campaigns_jam_test.go b/src/pkg/dashboard/api_campaigns_jam_test.go deleted file mode 100644 index 8ec48891d7..0000000000 --- a/src/pkg/dashboard/api_campaigns_jam_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package dashboard - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "path/filepath" - "testing" -) - -func jamTestServer(t *testing.T) *Server { - t.Helper() - s := newMinimalServer(t) - s.deps.Config.Data.MetricsDir = filepath.Join(t.TempDir(), "metrics") - return s -} - -func jamPostAs(t *testing.T, s *Server, path, role, user string, body any, ownerVerified bool) *httptest.ResponseRecorder { - t.Helper() - var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(body); err != nil { - t.Fatalf("encode body: %v", err) - } - req := httptest.NewRequest(http.MethodPost, path, &b) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Hive-Role", role) - req.Header.Set("X-Hive-User", user) - if ownerVerified { - req.Header.Set(ownerRoleVerifiedHeader, "true") - } - rec := httptest.NewRecorder() - s.mux.ServeHTTP(rec, req) - return rec -} - -func decodeJam(t *testing.T, rec *httptest.ResponseRecorder) CampaignJamState { - t.Helper() - var resp struct { - OK bool `json:"ok"` - Jam CampaignJamState `json:"jam"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode jam: %v body=%s", err, rec.Body.String()) - } - if !resp.OK { - t.Fatalf("jam response not ok: %s", rec.Body.String()) - } - return resp.Jam -} - -func TestCampaignJamPersistsAcrossRestart(t *testing.T) { - s := jamTestServer(t) - dir := s.deps.Config.Data.MetricsDir - rec := jamPostAs(t, s, "/api/campaigns/spec-1/jam/threads", "read-write", "alice", map[string]any{ - "section": "Goals", - "body": "Can we include async reviewers?", - }, false) - if rec.Code != http.StatusOK { - t.Fatalf("thread post = %d body=%s", rec.Code, rec.Body.String()) - } - - restarted := newMinimalServer(t) - restarted.deps.Config.Data.MetricsDir = dir - get := doOwnerGet(restarted, "/api/campaigns/spec-1/jam") - if get.Code != http.StatusOK { - t.Fatalf("jam get after restart = %d body=%s", get.Code, get.Body.String()) - } - jam := decodeJam(t, get) - if len(jam.Threads) != 1 || len(jam.Threads[0].Comments) != 1 || jam.Threads[0].Comments[0].Author.Name != "alice" { - t.Fatalf("persisted jam = %+v", jam) - } -} - -func TestCampaignJamPermissions(t *testing.T) { - s := jamTestServer(t) - readOnly := jamPostAs(t, s, "/api/campaigns/spec-2/jam/threads", "read", "reader", map[string]any{ - "section": "Goals", - "body": "readers cannot mutate", - }, false) - if readOnly.Code != http.StatusForbidden { - t.Fatalf("read-only thread post = %d body=%s", readOnly.Code, readOnly.Body.String()) - } - - poll := jamPostAs(t, s, "/api/campaigns/spec-2/jam/polls", "read-write", "alice", map[string]any{ - "section": "Scope", - "question": "Which milestone?", - "options": []string{"alpha", "beta"}, - }, false) - if poll.Code != http.StatusOK { - t.Fatalf("poll create = %d body=%s", poll.Code, poll.Body.String()) - } - jam := decodeJam(t, poll) - decision := jamPostAs(t, s, "/api/campaigns/spec-2/jam/polls", "read-write", "alice", map[string]any{ - "action": "decide", - "poll_id": jam.Polls[0].ID, - "outcome": "alpha", - "rationale": "keeps the phase small", - }, false) - if decision.Code != http.StatusForbidden { - t.Fatalf("read-write decision = %d body=%s", decision.Code, decision.Body.String()) - } -} - -func TestCampaignJamPollDecisionStoredOnRevision(t *testing.T) { - s := jamTestServer(t) - create := jamPostAs(t, s, "/api/campaigns/spec-3/jam/polls", "read-write", "alice", map[string]any{ - "section": "Storage", - "question": "JSON or sqlite?", - "options": []string{"json", "sqlite"}, - }, false) - if create.Code != http.StatusOK { - t.Fatalf("poll create = %d body=%s", create.Code, create.Body.String()) - } - jam := decodeJam(t, create) - pollID := jam.Polls[0].ID - optionID := jam.Polls[0].Options[1].ID - vote := jamPostAs(t, s, "/api/campaigns/spec-3/jam/polls", "read-write", "bob", map[string]any{ - "action": "vote", - "poll_id": pollID, - "option_id": optionID, - }, false) - if vote.Code != http.StatusOK { - t.Fatalf("poll vote = %d body=%s", vote.Code, vote.Body.String()) - } - decide := jamPostAs(t, s, "/api/campaigns/spec-3/jam/polls", "merger", "maintainer", map[string]any{ - "action": "decide", - "poll_id": pollID, - "outcome": "sqlite", - "rationale": "queryable decisions matter", - }, false) - if decide.Code != http.StatusOK { - t.Fatalf("poll decide = %d body=%s", decide.Code, decide.Body.String()) - } - jam = decodeJam(t, decide) - if jam.Polls[0].Decision == nil || jam.Polls[0].Decision.Rationale != "queryable decisions matter" { - t.Fatalf("decision not stored on poll: %+v", jam.Polls[0]) - } - if len(jam.Revisions) != 1 || len(jam.Revisions[0].Decisions) != 1 || jam.Revisions[0].Decisions[0].RevisionID != jam.Revisions[0].ID { - t.Fatalf("decision not stored on revision: %+v", jam.Revisions) - } -} - -func TestCampaignJamRevisionAttributionAndSuggestionAcceptance(t *testing.T) { - s := jamTestServer(t) - rec := jamPostAs(t, s, "/api/campaigns/spec-4/jam", "read-write", "alice", map[string]any{ - "spec_content": "## Goals\nInitial", - "reason": "seed", - }, false) - if rec.Code != http.StatusOK { - t.Fatalf("seed revision = %d body=%s", rec.Code, rec.Body.String()) - } - suggestion := jamPostAs(t, s, "/api/campaigns/spec-4/jam/suggestions", "read-write", "agent-runner", map[string]any{ - "section": "Goals", - "proposed_text": "Initial\nAdd async reviewers", - "agent": "architect", - "model": "gpt-5.4", - }, false) - if suggestion.Code != http.StatusOK { - t.Fatalf("suggestion create = %d body=%s", suggestion.Code, suggestion.Body.String()) - } - jam := decodeJam(t, suggestion) - if jam.Suggestions[0].Author.Type != "agent" || jam.Suggestions[0].Author.Model != "gpt-5.4" { - t.Fatalf("suggestion attribution = %+v", jam.Suggestions[0].Author) - } - accept := jamPostAs(t, s, "/api/campaigns/spec-4/jam/suggestions", "owner", "maintainer", map[string]any{ - "action": "accept", - "suggestion_id": jam.Suggestions[0].ID, - }, true) - if accept.Code != http.StatusOK { - t.Fatalf("suggestion accept = %d body=%s", accept.Code, accept.Body.String()) - } - jam = decodeJam(t, accept) - if len(jam.Revisions) != 2 || jam.Revisions[1].Author.Name != "maintainer" || jam.Revisions[1].Diff == "" { - t.Fatalf("revision attribution/diff = %+v", jam.Revisions) - } - if jam.Suggestions[0].Status != jamSuggestionAccepted || jam.Suggestions[0].AppliedRevisionID != jam.Revisions[1].ID { - t.Fatalf("suggestion not accepted: %+v", jam.Suggestions[0]) - } -} - -func TestCampaignJamSuggestionMatchesExactSectionHeading(t *testing.T) { - current := "## Goals\nKeep team async review\n\n## Goal\nShort term target" - got := applySectionSuggestion(current, "Goal", "Ship phase 1 only") - want := "## Goals\nKeep team async review\n\n## Goal\nShip phase 1 only" - if got != want { - t.Fatalf("section replacement mismatch\ngot:\n%s\nwant:\n%s", got, want) - } -} diff --git a/src/pkg/dashboard/api_campaigns_test.go b/src/pkg/dashboard/api_campaigns_test.go deleted file mode 100644 index 1cf5276984..0000000000 --- a/src/pkg/dashboard/api_campaigns_test.go +++ /dev/null @@ -1,474 +0,0 @@ -package dashboard - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func doOwnerPostAsUser(s *Server, path, user string, body interface{}) *httptest.ResponseRecorder { - var b bytes.Buffer - json.NewEncoder(&b).Encode(body) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, path, &b) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Hive-User", user) - markOwnerRequest(req) - s.mux.ServeHTTP(rec, req) - return rec -} - -func decodeCampaignList(t *testing.T, body []byte) []Campaign { - t.Helper() - var resp struct { - OK bool `json:"ok"` - Campaigns []Campaign `json:"campaigns"` - } - if err := json.Unmarshal(body, &resp); err != nil { - t.Fatalf("decode campaigns: %v body=%s", err, string(body)) - } - if !resp.OK { - t.Fatalf("campaign response not ok: %s", string(body)) - } - return resp.Campaigns -} - -func TestCampaignsArchiveInceptionOnResetAndResume(t *testing.T) { - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - state, err := s.deps.Inception.Start("Prepare bootc-installer for a beta release") - if err != nil { - t.Fatalf("start inception: %v", err) - } - - reset := doOwnerPost(s, "/api/inception/reset", map[string]interface{}{}) - if reset.Code != http.StatusOK { - t.Fatalf("reset = %d body=%s", reset.Code, reset.Body.String()) - } - if active := s.deps.Inception.GetState(); active != nil { - t.Fatalf("state after reset = %+v, want nil", active) - } - - list := doOwnerGet(s, "/api/campaigns?search=bootc") - if list.Code != http.StatusOK { - t.Fatalf("campaigns list = %d body=%s", list.Code, list.Body.String()) - } - campaigns := decodeCampaignList(t, list.Body.Bytes()) - if len(campaigns) != 1 { - t.Fatalf("campaigns len = %d, want 1: %+v", len(campaigns), campaigns) - } - if campaigns[0].ID != state.IdeaSlug || campaigns[0].Engine != "Spec Kit" || campaigns[0].Type != "inception" { - t.Fatalf("archived campaign = %+v", campaigns[0]) - } - - resume := doOwnerPost(s, "/api/campaigns/"+state.IdeaSlug+"/resume", map[string]string{"surface": "chat"}) - if resume.Code != http.StatusOK { - t.Fatalf("resume = %d body=%s", resume.Code, resume.Body.String()) - } - restored := s.deps.Inception.GetState() - if restored == nil || restored.IdeaText != state.IdeaText || restored.IdeaSlug != state.IdeaSlug { - t.Fatalf("restored state = %+v, want idea %q slug %q", restored, state.IdeaText, state.IdeaSlug) - } - - reset = doOwnerPost(s, "/api/inception/reset", map[string]interface{}{}) - if reset.Code != http.StatusOK { - t.Fatalf("second reset = %d body=%s", reset.Code, reset.Body.String()) - } - second, err := s.deps.Inception.Start("Second campaign that must not be lost") - if err != nil { - t.Fatalf("start second inception: %v", err) - } - resume = doOwnerPost(s, "/api/campaigns/"+state.IdeaSlug+"/resume", map[string]string{"surface": "chat"}) - if resume.Code != http.StatusOK { - t.Fatalf("resume with active state = %d body=%s", resume.Code, resume.Body.String()) - } - list = doOwnerGet(s, "/api/campaigns?search=Second") - campaigns = decodeCampaignList(t, list.Body.Bytes()) - if len(campaigns) != 1 || campaigns[0].ID != second.IdeaSlug { - t.Fatalf("active state was not archived before resume: %+v", campaigns) - } -} - -func TestCampaignsArchiveCompletedInceptionBeforeStart(t *testing.T) { - resetLifecycleStore() - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - first, err := s.deps.Inception.Start("Completed campaign should stay resumable") - if err != nil { - t.Fatalf("start first inception: %v", err) - } - if err := s.deps.Inception.SetQuestions([]knowledge.Question{{ID: "goal", Text: "Goal?"}}); err != nil { - t.Fatalf("set questions: %v", err) - } - if _, err := s.deps.Inception.SubmitAnswers(map[string]string{"goal": "Ship it"}); err != nil { - t.Fatalf("submit answers: %v", err) - } - if err := s.deps.Inception.RecordFacts(context.Background(), []knowledge.IdeationFact{{Type: knowledge.FactRequirement, Title: "Ship", Body: "Ship it"}}); err != nil { - t.Fatalf("record facts: %v", err) - } - if err := s.deps.Inception.AdvanceToComplete(); err != nil { - t.Fatalf("complete inception: %v", err) - } - - rec := doOwnerPost(s, "/api/inception/start", map[string]string{"idea": "Brand new campaign"}) - if rec.Code != http.StatusOK { - t.Fatalf("start replacement = %d body=%s", rec.Code, rec.Body.String()) - } - list := doOwnerGet(s, "/api/campaigns?search=Completed") - if list.Code != http.StatusOK { - t.Fatalf("campaigns list = %d body=%s", list.Code, list.Body.String()) - } - campaigns := decodeCampaignList(t, list.Body.Bytes()) - if len(campaigns) != 1 || campaigns[0].ID != first.IdeaSlug || campaigns[0].Status != "shipped" { - t.Fatalf("completed inception was not archived before replacement: %+v", campaigns) - } -} - -func TestCampaignsIncludeSpektacularRunsAndFilters(t *testing.T) { - s, _ := runsTestServer(t) - now := time.Now() - if err := s.contributeHub.recordLeaseForKeyStage("alice", "task-8665", "myorg/repo1", 8665, "myorg/repo1!stable-spec-8665:plan", "contributor", StagePlan, 3, now); err != nil { - t.Fatalf("record lease: %v", err) - } - - rec := doOwnerGet(s, "/api/campaigns?repo=repo1&stage=plan&status=planned&owner=alice") - if rec.Code != http.StatusOK { - t.Fatalf("campaigns list = %d body=%s", rec.Code, rec.Body.String()) - } - campaigns := decodeCampaignList(t, rec.Body.Bytes()) - if len(campaigns) != 1 { - t.Fatalf("campaigns len = %d, want 1: %+v", len(campaigns), campaigns) - } - got := campaigns[0] - if got.ID != "stable-spec-8665" || got.Engine != "Spektacular" || got.RunURL == "" || got.Status != "planned" { - t.Fatalf("run campaign = %+v", got) - } - - resume := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/resume", "alice", map[string]string{"surface": "cli"}) - if resume.Code != http.StatusOK { - t.Fatalf("resume = %d body=%s", resume.Code, resume.Body.String()) - } - if !strings.Contains(resume.Body.String(), "spektacular plan status stable-spec-8665") { - t.Fatalf("resume body missing CLI command: %s", resume.Body.String()) - } -} - -func TestCampaignLeaseReleaseAndReviseFlows(t *testing.T) { - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - state, err := s.deps.Inception.Start("Lease protected campaign") - if err != nil { - t.Fatalf("start inception: %v", err) - } - if reset := doOwnerPost(s, "/api/inception/reset", map[string]interface{}{}); reset.Code != http.StatusOK { - t.Fatalf("reset = %d body=%s", reset.Code, reset.Body.String()) - } - - resume := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/resume", "alice", map[string]string{"surface": "chat"}) - if resume.Code != http.StatusOK { - t.Fatalf("alice resume = %d body=%s", resume.Code, resume.Body.String()) - } - blocked := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/resume", "bob", map[string]string{"surface": "chat"}) - if blocked.Code != http.StatusConflict { - t.Fatalf("bob resume = %d body=%s, want conflict", blocked.Code, blocked.Body.String()) - } - releaseBlocked := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/release", "bob", map[string]string{}) - if releaseBlocked.Code != http.StatusConflict { - t.Fatalf("bob release = %d body=%s, want conflict", releaseBlocked.Code, releaseBlocked.Body.String()) - } - released := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/release", "alice", map[string]string{}) - if released.Code != http.StatusOK { - t.Fatalf("alice release = %d body=%s", released.Code, released.Body.String()) - } - resume = doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/resume", "bob", map[string]string{"surface": "chat"}) - if resume.Code != http.StatusOK { - t.Fatalf("bob resume after release = %d body=%s", resume.Code, resume.Body.String()) - } - - revise := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/revise", "bob", map[string]string{}) - if revise.Code != http.StatusOK { - t.Fatalf("revise = %d body=%s", revise.Code, revise.Body.String()) - } - var resp struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - } - if err := json.Unmarshal(revise.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode revise: %v", err) - } - if !resp.OK || resp.Campaign.RevisionOf != state.IdeaSlug || resp.Campaign.Revision == 0 || resp.Campaign.LeaseOwner != "bob" { - t.Fatalf("revision campaign = %+v", resp.Campaign) - } -} - -func TestCampaignReviseSpektacularRunCreatesLinkedRevision(t *testing.T) { - s, _ := runsTestServer(t) - now := time.Now() - if err := s.contributeHub.recordLeaseForKeyStage("alice", "task-8665", "myorg/repo1", 8665, "myorg/repo1!stable-spec-8665:implement", "contributor", StageImplement, 3, now); err != nil { - t.Fatalf("record lease: %v", err) - } - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - - revise := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/revise", "bob", map[string]string{}) - if revise.Code != http.StatusOK { - t.Fatalf("revise = %d body=%s", revise.Code, revise.Body.String()) - } - var resp struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - } - if err := json.Unmarshal(revise.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode revise: %v", err) - } - if !resp.OK || resp.Campaign.RevisionOf != "stable-spec-8665" || resp.Campaign.Engine != "Spektacular" || resp.Campaign.Type != "spektacular" { - t.Fatalf("spektacular revision = %+v", resp.Campaign) - } - if resp.Campaign.CurrentStage != StagePlan || !strings.Contains(spektacularResumeCommand(resp.Campaign), "spektacular plan status ") { - t.Fatalf("spektacular revision resume shape = %+v command=%q", resp.Campaign, spektacularResumeCommand(resp.Campaign)) - } -} - -func TestCampaignRecheckManualForceAndConflict(t *testing.T) { - s, deps := runsTestServer(t) - deps.Config.Runs.Spektacular = config.SpektacularConfig{Enabled: true} - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - now := time.Now() - if err := s.contributeHub.recordLeaseForKeyStage("alice", "task-8665", "myorg/repo1", 8665, "myorg/repo1!stable-spec-8665:implement", "contributor", StageImplement, 3, now); err != nil { - t.Fatalf("record lease: %v", err) - } - - disabled := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/recheck", "bob", map[string]string{}) - if disabled.Code != http.StatusNotFound { - t.Fatalf("disabled recheck = %d body=%s, want 404", disabled.Code, disabled.Body.String()) - } - forced := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/recheck?force=true", "bob", map[string]string{}) - if forced.Code != http.StatusOK { - t.Fatalf("forced recheck = %d body=%s", forced.Code, forced.Body.String()) - } - var resp struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - } - if err := json.Unmarshal(forced.Body.Bytes(), &resp); err != nil { - t.Fatalf("decode forced recheck: %v", err) - } - if !resp.OK || resp.Campaign.RevisionOf == "" || resp.Campaign.CurrentStage != StageSpec || resp.Campaign.Drift == nil || resp.Campaign.Drift.RecheckReason != recheckReasonManual { - t.Fatalf("forced recheck campaign = %+v", resp.Campaign) - } - conflict := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/recheck?force=true", "bob", map[string]string{}) - if conflict.Code != http.StatusConflict { - t.Fatalf("second recheck = %d body=%s, want 409", conflict.Code, conflict.Body.String()) - } -} - -// Release on a run-backed Spektacular campaign must never revoke the -// contributor's stage lease: that lease is the run's only record, and -// revoking it drops the run from both /api/campaigns and /api/runs/{key} -// (hivecommons/hive#10057). -func TestCampaignReleasePreservesSpektacularRunLease(t *testing.T) { - for _, stage := range []string{StageSpec, StagePlan, StageImplement} { - t.Run(stage, func(t *testing.T) { - s, _ := runsTestServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - leaseKey := "myorg/repo1!stable-spec-8665:" + stage - if err := s.contributeHub.recordLeaseForKeyStage("alice", "task-8665", "myorg/repo1", 8665, leaseKey, "contributor", stage, 3, time.Now()); err != nil { - t.Fatalf("record lease: %v", err) - } - before, ok := s.contributeHub.runLeaseHolder(leaseKey, time.Now()) - if !ok { - t.Fatal("missing initial stage lease") - } - for _, user := range []string{"alice", "bob"} { - released := doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/release", user, map[string]string{}) - if released.Code != http.StatusConflict || !strings.Contains(released.Body.String(), "run-backed campaigns cannot be released here") { - t.Fatalf("%s release = %d body=%s, want explicit conflict", user, released.Code, released.Body.String()) - } - after, ok := s.contributeHub.runLeaseHolder(leaseKey, time.Now()) - if !ok || after.identity != before.identity || after.taskID != before.taskID || after.stage != before.stage || after.gen != before.gen || !after.expiresAt.Equal(before.expiresAt) { - t.Fatalf("release changed stage lease: before=%+v after=%+v held=%v", before, after, ok) - } - list := doOwnerGet(s, "/api/campaigns") - campaigns := decodeCampaignList(t, list.Body.Bytes()) - if len(campaigns) != 1 || campaigns[0].ID != "stable-spec-8665" || campaigns[0].LeaseOwner != "alice" || campaigns[0].CurrentStage != stage { - t.Fatalf("campaign disappeared or changed after release: %+v", campaigns) - } - runRec := doOwnerGet(s, "/api/runs/"+url.PathEscape(leaseKey)) - if runRec.Code != http.StatusOK { - t.Fatalf("run after release = %d body=%s", runRec.Code, runRec.Body.String()) - } - } - }) - } -} - -func TestCampaignFromCompletedRunUsesStableSpecID(t *testing.T) { - campaign := campaignFromRun(Run{ - Key: "myorg/repo1!stable-spec-8665:implement", - Repo: "myorg/repo1", - Stage: "completed", - State: "completed", - StageStartedAt: "2026-09-24T12:00:00Z", - }) - if campaign.ID != "stable-spec-8665" { - t.Fatalf("campaign id = %q, want stable spec id", campaign.ID) - } - if !strings.Contains(spektacularResumeCommand(campaign), "stable-spec-8665") { - t.Fatalf("resume command = %q, want stable spec id", spektacularResumeCommand(campaign)) - } -} - -func doOwnerDeleteAsUser(s *Server, path, user string) *httptest.ResponseRecorder { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, path, nil) - req.Header.Set("X-Hive-User", user) - markOwnerRequest(req) - s.mux.ServeHTTP(rec, req) - return rec -} - -// TestCampaignDeleteRemovesArchiveOnly pins hivecommons/hive#12698: DELETE -// drops the campaign archive (state + wiki snapshot) and the row vanishes, -// while the other revisions in the chain and the Jam state are untouched. -func TestCampaignDeleteRemovesArchiveOnly(t *testing.T) { - // The unfiltered list folds completed runs from the process-wide - // lifecycle store in; isolate it so journeys recorded by earlier tests - // (e.g. the wavefront completion tests) cannot show up here (#13167). - resetLifecycleStore() - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - state, err := s.deps.Inception.StartBrownfield("https://github.com/hivecommons/hive") - if err != nil { - t.Fatalf("start brownfield: %v", err) - } - if reset := doOwnerPost(s, "/api/inception/reset", map[string]interface{}{}); reset.Code != http.StatusOK { - t.Fatalf("reset = %d body=%s", reset.Code, reset.Body.String()) - } - revise := doOwnerPostAsUser(s, "/api/campaigns/"+state.IdeaSlug+"/revise", "alice", map[string]string{}) - if revise.Code != http.StatusOK { - t.Fatalf("revise = %d body=%s", revise.Code, revise.Body.String()) - } - var revised struct { - Campaign Campaign `json:"campaign"` - } - if err := json.Unmarshal(revise.Body.Bytes(), &revised); err != nil { - t.Fatalf("decode revise: %v", err) - } - - list := doOwnerGet(s, "/api/campaigns") - campaigns := decodeCampaignList(t, list.Body.Bytes()) - if len(campaigns) != 2 { - t.Fatalf("campaigns before delete = %d, want 2: %+v", len(campaigns), campaigns) - } - for _, c := range campaigns { - if c.ID == state.IdeaSlug && c.SupersededBy != revised.Campaign.ID { - t.Fatalf("root superseded_by = %q, want %q", c.SupersededBy, revised.Campaign.ID) - } - if c.ID == revised.Campaign.ID && c.SupersededBy != "" { - t.Fatalf("revision superseded_by = %q, want empty", c.SupersededBy) - } - } - - del := doOwnerDeleteAsUser(s, "/api/campaigns/"+revised.Campaign.ID, "alice") - if del.Code != http.StatusOK { - t.Fatalf("delete = %d body=%s", del.Code, del.Body.String()) - } - var resp campaignDeleteResponse - if err := json.Unmarshal(del.Body.Bytes(), &resp); err != nil || !resp.OK || resp.ID != revised.Campaign.ID { - t.Fatalf("delete response = %+v err=%v body=%s", resp, err, del.Body.String()) - } - if !strings.Contains(resp.Message, "kept") { - t.Fatalf("delete message should say what is kept: %q", resp.Message) - } - if _, err := s.deps.Inception.LoadCampaignArchive(revised.Campaign.ID); err == nil { - t.Fatalf("revision archive still present after delete") - } - if _, err := s.deps.Inception.LoadCampaignArchive(state.IdeaSlug); err != nil { - t.Fatalf("root archive removed with the revision: %v", err) - } - - campaigns = decodeCampaignList(t, doOwnerGet(s, "/api/campaigns").Body.Bytes()) - if len(campaigns) != 1 || campaigns[0].ID != state.IdeaSlug || campaigns[0].SupersededBy != "" { - t.Fatalf("campaigns after delete = %+v, want only root with no superseded_by", campaigns) - } - - again := doOwnerDeleteAsUser(s, "/api/campaigns/"+revised.Campaign.ID, "alice") - if again.Code != http.StatusNotFound { - t.Fatalf("second delete = %d body=%s, want 404", again.Code, again.Body.String()) - } - missing := doOwnerDeleteAsUser(s, "/api/campaigns/does-not-exist", "alice") - if missing.Code != http.StatusNotFound { - t.Fatalf("unknown delete = %d body=%s, want 404", missing.Code, missing.Body.String()) - } -} - -func TestCampaignDeleteRequiresOwnerRole(t *testing.T) { - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - state, err := s.deps.Inception.Start("Delete needs owner role") - if err != nil { - t.Fatalf("start inception: %v", err) - } - if reset := doOwnerPost(s, "/api/inception/reset", map[string]interface{}{}); reset.Code != http.StatusOK { - t.Fatalf("reset = %d body=%s", reset.Code, reset.Body.String()) - } - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/campaigns/"+state.IdeaSlug, nil) - req.Header.Set("X-Hive-User", "mallory") - s.mux.ServeHTTP(rec, req) - if rec.Code != http.StatusForbidden { - t.Fatalf("non-owner delete = %d body=%s, want 403", rec.Code, rec.Body.String()) - } - if _, err := s.deps.Inception.LoadCampaignArchive(state.IdeaSlug); err != nil { - t.Fatalf("archive removed by forbidden request: %v", err) - } -} - -// Deleting the campaign that is also the live L1 session clears that session -// so the dashboard does not resurrect the row on the next state poll. -func TestCampaignDeleteClearsActiveInceptionState(t *testing.T) { - // Campaigns also projects completed runs from the process-wide timeline. - // Start empty so earlier tests cannot add rows to this inception-only fixture. - resetLifecycleStore() - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - state, err := s.deps.Inception.StartBrownfield("https://github.com/hivecommons/hive") - if err != nil { - t.Fatalf("start brownfield: %v", err) - } - campaigns := decodeCampaignList(t, doOwnerGet(s, "/api/campaigns").Body.Bytes()) - if len(campaigns) != 1 || campaigns[0].ID != state.IdeaSlug { - t.Fatalf("active campaign not listed: %+v", campaigns) - } - del := doOwnerDeleteAsUser(s, "/api/campaigns/"+state.IdeaSlug, "alice") - if del.Code != http.StatusOK { - t.Fatalf("delete active = %d body=%s", del.Code, del.Body.String()) - } - if active := s.deps.Inception.GetState(); active != nil { - t.Fatalf("active state after delete = %+v, want nil", active) - } - if campaigns := decodeCampaignList(t, doOwnerGet(s, "/api/campaigns").Body.Bytes()); len(campaigns) != 0 { - t.Fatalf("campaigns after deleting active = %+v, want none", campaigns) - } -} - -func TestCampaignDeleteRejectsRunBackedSpektacular(t *testing.T) { - s, _ := runsTestServer(t) - now := time.Now() - if err := s.contributeHub.recordLeaseForKeyStage("alice", "task-12698", "myorg/repo1", 12698, "myorg/repo1!stable-spec-12698:implement", "contributor", StageImplement, 3, now); err != nil { - t.Fatalf("record lease: %v", err) - } - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - del := doOwnerDeleteAsUser(s, "/api/campaigns/stable-spec-12698", "alice") - if del.Code != http.StatusConflict { - t.Fatalf("run-backed delete = %d body=%s, want 409", del.Code, del.Body.String()) - } -} diff --git a/src/pkg/dashboard/api_governor_features.go b/src/pkg/dashboard/api_governor_features.go index 3dfece4a37..df92fcb11d 100644 --- a/src/pkg/dashboard/api_governor_features.go +++ b/src/pkg/dashboard/api_governor_features.go @@ -55,9 +55,9 @@ const ( // supersession_sweep, compliance.posture_checks, planning, swarm // and tool_approval.inbox_path (featuresPlatformBody in // api_governor_features_platform.go) -// - runs.checkpoints, runs.wait_*, runs.triage scalars, runs.spektacular.recheck -// scalars, the Flue endpoint, every workflow_version and the vibe-kanban -// host (featuresRunsBody in api_governor_features_runs.go) +// - runs.checkpoints, runs.wait_*, runs.triage scalars, the Flue endpoint, +// every workflow_version and the vibe-kanban host (featuresRunsBody in +// api_governor_features_runs.go) // // Every field is a pointer so an absent key leaves the corresponding config // untouched — the same "only what you send is changed" contract the other diff --git a/src/pkg/dashboard/api_governor_features_runs.go b/src/pkg/dashboard/api_governor_features_runs.go index 75ea5e5545..191674f06c 100644 --- a/src/pkg/dashboard/api_governor_features_runs.go +++ b/src/pkg/dashboard/api_governor_features_runs.go @@ -40,14 +40,6 @@ type featuresRunsBody struct { RunsTriagePriorArtMaxParksPerCycle *int `json:"runsTriagePriorArtMaxParksPerCycle"` RunsTriagePriorArtBotCloseTTL *string `json:"runsTriagePriorArtBotCloseTtl"` - RecheckEnabled *bool `json:"spektacularRecheckEnabled"` - RecheckDefaultInterval *string `json:"spektacularRecheckDefaultInterval"` - RecheckMaxDeltaTasks *int `json:"spektacularRecheckMaxDeltaTasks"` - RecheckDiscoveryProxy *string `json:"spektacularRecheckDiscoveryProxy"` - DiscoveryEnabled *bool `json:"spektacularDiscoveryEnabled"` - DiscoveryTimeout *string `json:"spektacularDiscoveryTimeout"` - DiscoveryMaxTotalItems *int `json:"spektacularDiscoveryMaxTotalItems"` - ExtFlueEndpoint *string `json:"extFlueEndpoint"` ExtFlueWorkflowVersion *string `json:"extFlueWorkflowVersion"` ExtOMPWorkflowVersion *string `json:"extOmpWorkflowVersion"` @@ -67,9 +59,11 @@ var runsWaitSeverities = []string{"decision", "info"} // the vibe-kanban project id). const maxRunsSettingLen = 200 -// prepare validates every field the request carried against cur and returns -// the mutation to apply. Nothing is changed when an error is returned. -func (b featuresRunsBody) prepare(cur *config.Config) (func(*config.Config), error) { +// prepare validates every field the request carried and returns the mutation +// to apply. Nothing is changed when an error is returned. The current config +// is accepted for symmetry with the other features bodies; no runs field +// needs it since the recheck discovery proxy was retired. +func (b featuresRunsBody) prepare(_ *config.Config) (func(*config.Config), error) { var steps []func(*config.Config) for _, f := range []struct { @@ -95,8 +89,6 @@ func (b featuresRunsBody) prepare(cur *config.Config) (func(*config.Config), err }{ {b.RunsTriageEnabled, func(c *config.Config) *bool { return &c.Runs.Triage.Enabled }}, {b.RunsTriageClarityGateEnabled, func(c *config.Config) *bool { return &c.Runs.Triage.ClarityGate.Enabled }}, - {b.RecheckEnabled, func(c *config.Config) *bool { return &c.Runs.Spektacular.Recheck.Enabled }}, - {b.DiscoveryEnabled, func(c *config.Config) *bool { return &c.Runs.Spektacular.Recheck.Discovery.Enabled }}, {b.ExtVibeKanbanEnabled, func(c *config.Config) *bool { return &c.Runs.External.VibeKanban.Enabled }}, } { if f.v == nil { @@ -116,8 +108,6 @@ func (b featuresRunsBody) prepare(cur *config.Config) (func(*config.Config), err {b.RunsTriageMinBodyChars, "runs triage min_body_chars", func(c *config.Config) *int { return &c.Runs.Triage.MinBodyChars }}, {b.RunsTriagePriorArtMaxFindings, "runs triage prior_art max_findings", func(c *config.Config) *int { return &c.Runs.Triage.PriorArt.MaxFindings }}, {b.RunsTriagePriorArtMaxParksPerCycle, "runs triage prior_art max_parks_per_cycle", func(c *config.Config) *int { return &c.Runs.Triage.PriorArt.MaxParksPerCycle }}, - {b.RecheckMaxDeltaTasks, "runs spektacular recheck max_delta_tasks", func(c *config.Config) *int { return &c.Runs.Spektacular.Recheck.MaxDeltaTasks }}, - {b.DiscoveryMaxTotalItems, "runs spektacular recheck discovery max_total_items", func(c *config.Config) *int { return &c.Runs.Spektacular.Recheck.Discovery.MaxTotalItems }}, } { if f.v == nil { continue @@ -183,38 +173,6 @@ func (b featuresRunsBody) prepare(cur *config.Config) (func(*config.Config), err steps = append(steps, func(c *config.Config) { c.Runs.WaitSeverity = v }) } - if b.RecheckDefaultInterval != nil { - d, err := parseSettingsDuration("runs spektacular recheck default_interval", *b.RecheckDefaultInterval) - if err != nil { - return nil, err - } - steps = append(steps, func(c *config.Config) { c.Runs.Spektacular.Recheck.DefaultInterval = d }) - } - if b.DiscoveryTimeout != nil { - d, err := parseSettingsDuration("runs spektacular recheck discovery timeout", *b.DiscoveryTimeout) - if err != nil { - return nil, err - } - steps = append(steps, func(c *config.Config) { c.Runs.Spektacular.Recheck.Discovery.Timeout = d }) - } - if b.RecheckDiscoveryProxy != nil { - proxy := strings.TrimSpace(*b.RecheckDiscoveryProxy) - if proxy != "" { - u, err := url.Parse(proxy) - if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { - return nil, fmt.Errorf("runs spektacular recheck discovery_proxy must be empty or the HTTP(S) relay proxy without credentials, path, query or fragment") - } - } - // With exact sources configured the proxy is mandatory; reuse the - // config validator so the dialog cannot save a policy boot rejects. - recheck := cur.Runs.Spektacular.Recheck - recheck.DiscoveryProxy = proxy - if err := recheck.ValidateDiscovery(); err != nil { - return nil, err - } - steps = append(steps, func(c *config.Config) { c.Runs.Spektacular.Recheck.DiscoveryProxy = proxy }) - } - if b.ExtFlueEndpoint != nil { v := strings.TrimRight(strings.TrimSpace(*b.ExtFlueEndpoint), "/") if v != "" { @@ -300,14 +258,6 @@ func featuresRunsResponse(cfg *config.Config) map[string]interface{} { "runsTriagePriorArtMaxParksPerCycle": r.Triage.PriorArt.MaxParksPerCycle, "runsTriagePriorArtBotCloseTtl": settingsDurationString(r.Triage.PriorArt.BotCloseTTL), - "spektacularRecheckEnabled": r.Spektacular.Recheck.Enabled, - "spektacularRecheckDefaultInterval": settingsDurationString(r.Spektacular.Recheck.DefaultInterval), - "spektacularRecheckMaxDeltaTasks": r.Spektacular.Recheck.MaxDeltaTasks, - "spektacularRecheckDiscoveryProxy": r.Spektacular.Recheck.DiscoveryProxy, - "spektacularDiscoveryEnabled": r.Spektacular.Recheck.Discovery.Enabled, - "spektacularDiscoveryTimeout": settingsDurationString(r.Spektacular.Recheck.Discovery.Timeout), - "spektacularDiscoveryMaxTotalItems": r.Spektacular.Recheck.Discovery.MaxTotalItems, - "extFlueModeSetting": r.External.Flue.Mode, "extFlueEndpoint": r.External.Flue.Endpoint, "extFlueWorkflowVersion": r.External.Flue.WorkflowVersion, @@ -332,10 +282,6 @@ func featuresRunsResponse(cfg *config.Config) map[string]interface{} { "runsTriagePriorArtMaxFindings": config.DefaultPriorArtGateMaxFindings, "runsTriagePriorArtMaxParksPerCycle": config.DefaultPriorArtGateMaxParksPerCycle, "runsTriagePriorArtBotCloseTtl": config.DefaultPriorArtGateBotCloseTTL.String(), - "spektacularRecheckDefaultInterval": config.DefaultSpektacularRecheckInterval.String(), - "spektacularRecheckMaxDeltaTasks": config.DefaultSpektacularMaxDeltaTasks, - "spektacularDiscoveryTimeout": fmt.Sprintf("%ds", config.DefaultSpektacularDiscoveryTimeoutS), - "spektacularDiscoveryMaxTotalItems": config.DefaultSpektacularDiscoveryMaxTotalItems, "extFlueMode": config.DefaultFlueBindingMode, "implementCheckpointMinAcmm": config.RunImplementCheckpointMinACMM, }, diff --git a/src/pkg/dashboard/campaign_discovery.go b/src/pkg/dashboard/campaign_discovery.go deleted file mode 100644 index 5ae61acd0e..0000000000 --- a/src/pkg/dashboard/campaign_discovery.go +++ /dev/null @@ -1,93 +0,0 @@ -package dashboard - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "net/http" - "net/url" - "time" - "unicode/utf8" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -const discoveryMaxBytes = 32 * 1024 - -func (s *Server) discoverRecheckSources(ctx context.Context) []knowledge.CampaignDriftSource { - if s == nil || s.deps == nil || s.deps.Config == nil { - return nil - } - cfg := s.deps.Config.Runs.Spektacular.Recheck - if len(cfg.Sources) == 0 { - return nil - } - // Revalidate at use as well as at load: configuration overlays must not - // introduce an unvalidated destination or enable a direct fallback. - if err := cfg.ValidateDiscovery(); err != nil { - return []knowledge.CampaignDriftSource{{Error: err.Error()}} - } - proxy, _ := url.Parse(cfg.DiscoveryProxy) - transport := http.DefaultTransport.(*http.Transport).Clone() - // Explicit ProxyURL deliberately ignores NO_PROXY and environment fallbacks. - transport.Proxy = http.ProxyURL(proxy) - defer transport.CloseIdleConnections() - client := &http.Client{ - Transport: transport, - Timeout: 10 * time.Second, - CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, - } - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - return collectDiscovery(ctx, cfg.Sources, client) -} - -// collectDiscovery makes exactly one read per declaration. It never follows -// links or executes source content, and errors are retained as evidence rather -// than silently claiming an unchanged source. Spec/plan approval is unchanged. -func collectDiscovery(ctx context.Context, sources []config.SpektacularDiscoverySource, client *http.Client) []knowledge.CampaignDriftSource { - out := make([]knowledge.CampaignDriftSource, 0, len(sources)) - for _, source := range sources { - item := knowledge.CampaignDriftSource{Name: source.Name, Kind: source.Kind, URL: source.URL} - body, err := readDiscovery(ctx, client, source.URL) - if err != nil { - item.Error = err.Error() - } else { - sum := sha256.Sum256(body) - item.SHA256 = hex.EncodeToString(sum[:]) - item.Evidence = string(body) - } - out = append(out, item) - } - return out -} - -func readDiscovery(ctx context.Context, client *http.Client, address string) ([]byte, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) - if err != nil { - return nil, fmt.Errorf("invalid discovery request") - } - req.Header.Set("Accept", "text/plain, text/markdown, application/json") - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("discovery request failed") - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("discovery returned HTTP %d", resp.StatusCode) - } - body, err := io.ReadAll(io.LimitReader(resp.Body, discoveryMaxBytes+1)) - if err != nil { - return nil, fmt.Errorf("discovery body read failed") - } - if len(body) > discoveryMaxBytes { - return nil, fmt.Errorf("discovery exceeds %d bytes", discoveryMaxBytes) - } - if !utf8.Valid(body) { - return nil, fmt.Errorf("discovery is not UTF-8 text") - } - return body, nil -} diff --git a/src/pkg/dashboard/campaign_discovery_test.go b/src/pkg/dashboard/campaign_discovery_test.go deleted file mode 100644 index 3250662a3b..0000000000 --- a/src/pkg/dashboard/campaign_discovery_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package dashboard - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func TestDiscoverySnapshotsAndFailures(t *testing.T) { - var requests atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requests.Add(1) - if r.Method != http.MethodGet { - t.Errorf("method = %s", r.Method) - } - switch r.URL.Path { - case "/release": - _, _ = w.Write([]byte("v2 adds a capability")) - case "/large": - _, _ = w.Write([]byte(strings.Repeat("x", discoveryMaxBytes+1))) - case "/redirect": - http.Redirect(w, r, "/release", http.StatusFound) - default: - http.Error(w, "unavailable", http.StatusServiceUnavailable) - } - })) - defer server.Close() - client := server.Client() - client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - var sources []config.SpektacularDiscoverySource - for _, path := range []string{"/release", "/large", "/redirect", "/error"} { - sources = append(sources, config.SpektacularDiscoverySource{Name: path, Kind: "release", URL: server.URL + path}) - } - evidence := collectDiscovery(context.Background(), sources, client) - if requests.Load() != 4 || len(evidence) != 4 { - t.Fatalf("requests=%d evidence=%v", requests.Load(), evidence) - } - if evidence[0].Evidence != "v2 adds a capability" || len(evidence[0].SHA256) != 64 || evidence[0].URL != sources[0].URL { - t.Fatalf("lost source evidence: %+v", evidence[0]) - } - for _, item := range evidence[1:] { - if item.Error == "" || item.Evidence != "" { - t.Fatalf("failure treated as evidence: %+v", item) - } - } - // Round-trip the evidence through the revision store before projecting JSON. - s := newMinimalServer(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - revision, err := s.deps.Inception.ReviseExternalCampaign("prior", "Research", "prior", "Spektacular", "spektacular", "owner", nil, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil { - t.Fatal(err) - } - if _, err := s.deps.Inception.SetCampaignDrift(revision.ID, &knowledge.CampaignDrift{DriftSource: evidence}); err != nil { - t.Fatal(err) - } - archive, err := s.deps.Inception.LoadCampaignArchive(revision.ID) - if err != nil { - t.Fatal(err) - } - drift := campaignDriftFromArchive(*archive) - body, err := json.Marshal(Campaign{Drift: drift}) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(body), `"drift_source"`) || !strings.Contains(string(body), "v2 adds a capability") { - t.Fatalf("missing evidence: %s", body) - } -} - -func TestDiscoveryUsesOnlyConfiguredProxy(t *testing.T) { - var requests atomic.Int32 - relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requests.Add(1) - if r.Method != http.MethodConnect || r.Host != "source.invalid:443" { - t.Errorf("unexpected relay request %s %s", r.Method, r.Host) - } - http.Error(w, "denied", http.StatusForbidden) - })) - defer relay.Close() - // NO_PROXY must never let a declaration bypass the relay. - t.Setenv("NO_PROXY", "*") - s := &Server{deps: &Dependencies{Config: &config.Config{}}} - cfg := &s.deps.Config.Runs.Spektacular.Recheck - cfg.DiscoveryProxy = relay.URL - cfg.EgressAllowlist = []string{"source.invalid"} - if got := s.discoverRecheckSources(context.Background()); len(got) != 0 || requests.Load() != 0 { - t.Fatal("empty sources performed discovery") - } - cfg.Sources = []config.SpektacularDiscoverySource{{Name: "source", Kind: "standards", URL: "https://source.invalid/news"}} - got := s.discoverRecheckSources(context.Background()) - if requests.Load() != 1 || len(got) != 1 || got[0].Error == "" { - t.Fatalf("relay not enforced: requests=%d evidence=%+v", requests.Load(), got) - } - cfg.Sources[0].URL = "https://outside.invalid/news" - got = s.discoverRecheckSources(context.Background()) - if requests.Load() != 1 || len(got) != 1 || !strings.Contains(got[0].Error, "allow-list") { - t.Fatalf("invalid source reached network: %+v", got) - } -} - -func TestRecheckAttachesDiscoveryToRevision(t *testing.T) { - relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "denied", http.StatusForbidden) - })) - defer relay.Close() - hub, s := covK2Hub(t) - s.contributeHub = hub - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - s.deps.Config.Runs.Spektacular.Recheck = config.SpektacularRecheckConfig{ - DiscoveryProxy: relay.URL, EgressAllowlist: []string{"source.invalid"}, - Sources: []config.SpektacularDiscoverySource{{Name: "upstream", Kind: "release", URL: "https://source.invalid/news"}}, - } - now := time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC) - base, err := s.deps.Inception.UpsertExternalCampaign("discovery-base", "Research", "discovery-base", "Spektacular", "spektacular", []string{"acme/tool"}, now) - if err != nil { - t.Fatal(err) - } - revision, err := s.triggerCampaignRecheck(context.Background(), base.ID, "owner", recheckReasonManual, true, now) - if err != nil { - t.Fatal(err) - } - if revision.RevisionOf != base.ID || revision.Drift == nil || len(revision.Drift.DriftSource) != 1 || revision.Drift.DriftSource[0].Name != "upstream" || revision.Drift.DriftSource[0].Error == "" { - t.Fatalf("missing revision evidence: %+v", revision) - } - stored, err := s.deps.Inception.LoadCampaignArchive(revision.ID) - if err != nil { - t.Fatal(err) - } - if stored.Drift == nil || len(stored.Drift.DriftSource) != 1 { - t.Fatalf("evidence not retained: %+v", stored) - } - original, err := s.deps.Inception.LoadCampaignArchive(base.ID) - if err != nil { - t.Fatal(err) - } - if original.Drift != nil { - t.Fatal("discovery overwrote prior campaign") - } -} diff --git a/src/pkg/dashboard/campaign_recheck.go b/src/pkg/dashboard/campaign_recheck.go deleted file mode 100644 index 15227f4f5e..0000000000 --- a/src/pkg/dashboard/campaign_recheck.go +++ /dev/null @@ -1,468 +0,0 @@ -package dashboard - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "net/http" - "os/exec" - "strconv" - "strings" - "time" - - "github.com/hivecommons/hive/crux/agentparse" - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" - "github.com/hivecommons/hive/pkg/planning" -) - -const ( - recheckReasonCadence = "cadence" - recheckReasonManual = "manual" - recheckTaskPrefix = "spek-recheck-" - gitHeadTimeout = 2 * time.Second -) - -// RecheckEvidenceSource is the extension point for evidence gathered before a -// recheck revision starts. Discovery snapshots remain evidence only. -type RecheckEvidenceSource interface { - Evidence(ctx context.Context, campaign Campaign, priorHead string) (CampaignDrift, error) -} - -type codebaseHeadEvidenceSource struct{} - -func (codebaseHeadEvidenceSource) Evidence(ctx context.Context, _ Campaign, priorHead string) (CampaignDrift, error) { - current := currentGitHead(ctx) - return CampaignDrift{ - CodebaseChanged: priorHead != "" && current != "" && priorHead != current, - PriorHeadSHA: priorHead, - CurrentHeadSHA: current, - }, nil -} - -type campaignRecheckResponse struct { - OK bool `json:"ok"` - Campaign Campaign `json:"campaign"` - Message string `json:"message,omitempty"` -} - -func (s *Server) handleCampaignRecheck(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - id := campaignIDFromRequest(r) - if id == "" { - jsonError(w, "campaign id required", http.StatusBadRequest) - return - } - campaign, err := s.triggerCampaignRecheck(r.Context(), id, requestUser(r), recheckReasonManual, r.URL.Query().Get("force") == "true", time.Now()) - if err != nil { - status := http.StatusInternalServerError - if errors.Is(err, errRecheckDisabled) { - status = http.StatusNotFound - } else if errors.Is(err, errRecheckInFlight) { - status = http.StatusConflict - } else if errors.Is(err, errRecheckNotFound) { - status = http.StatusNotFound - } - jsonError(w, err.Error(), status) - return - } - jsonResponse(w, campaignRecheckResponse{OK: true, Campaign: campaign, Message: "Spektacular recheck revision created"}) -} - -var ( - errRecheckDisabled = errors.New("campaign recheck is not enabled") - errRecheckInFlight = errors.New("campaign recheck revision already in flight") - errRecheckNotFound = errors.New("campaign not found") -) - -func (s *Server) TickCampaignRechecks(ctx context.Context, now time.Time) { - if s == nil || s.deps == nil || s.deps.Config == nil || !s.deps.Config.Runs.Spektacular.Recheck.Enabled { - return - } - campaigns, err := s.allCampaigns(nil) - if err != nil { - return - } - for _, campaign := range campaigns { - if campaign.CurrentStage != "completed" && campaign.Status != "shipped" { - continue - } - recheck := campaign.Recheck - if recheck == nil || !recheck.Enabled || recheck.InFlight || recheck.NextAt == "" { - continue - } - next, err := time.Parse(time.RFC3339, recheck.NextAt) - if err != nil || now.Before(next) { - continue - } - if _, err := s.triggerCampaignRecheck(ctx, campaign.ID, "system", recheckReasonCadence, false, now); err != nil && s.logger != nil { - s.logger.Warn("[spektacular] campaign recheck skipped", "campaign", campaign.ID, "error", err) - } - } -} - -func (s *Server) triggerCampaignRecheck(ctx context.Context, id, actor, reason string, force bool, now time.Time) (Campaign, error) { - if s == nil || s.deps == nil || s.deps.Inception == nil || s.contributeHub == nil { - return Campaign{}, errors.New("campaign store unavailable") - } - if now.IsZero() { - now = time.Now() - } - campaigns, err := s.allCampaigns(nil) - if err != nil { - return Campaign{}, err - } - var base Campaign - for _, campaign := range campaigns { - if campaign.ID == id || campaign.RunKey == id { - base = campaign - break - } - } - if base.ID == "" { - return Campaign{}, errRecheckNotFound - } - enabled := force || (base.Recheck != nil && base.Recheck.Enabled) - if !enabled { - return Campaign{}, errRecheckDisabled - } - if base.Recheck != nil && base.Recheck.InFlight { - return Campaign{}, errRecheckInFlight - } - source := firstRunNonEmpty(base.RunKey, base.Source, base.ID) - baseArchive, err := s.deps.Inception.UpsertExternalCampaign(base.ID, base.Title, source, base.Engine, base.Type, base.Repos, now) - if err != nil { - return Campaign{}, err - } - revision, err := s.deps.Inception.ReviseExternalCampaign(baseArchive.ID, base.Title, source, base.Engine, base.Type, actor, base.Repos, now) - if err != nil { - return Campaign{}, err - } - interval := s.recheckInterval(base) - revision.Recheck = &knowledge.CampaignRecheck{Enabled: true, Interval: interval} - evidence, _ := (codebaseHeadEvidenceSource{}).Evidence(ctx, base, priorCampaignHead(base)) - evidence.PriorRevision = firstRunNonEmpty(base.RevisionOf, base.ID) - evidence.RecheckReason = reason - external, failures := s.collectRecheckDiscovery(ctx, base, parseCampaignTime(base.LastActivity)) - revision.Drift = &knowledge.CampaignDrift{ - DriftSource: s.discoverRecheckSources(ctx), - CodebaseChanged: evidence.CodebaseChanged, - PriorHeadSHA: evidence.PriorHeadSHA, - CurrentHeadSHA: evidence.CurrentHeadSHA, - PriorRevision: evidence.PriorRevision, - DeltaCount: evidence.DeltaCount, - RecheckReason: evidence.RecheckReason, - External: external, - ExternalCount: len(external), - SourcesFailed: failures, - } - if _, err := s.deps.Inception.SetCampaignRecheck(revision.ID, revision.Recheck); err != nil { - return Campaign{}, err - } - if _, err := s.deps.Inception.SetCampaignDrift(revision.ID, revision.Drift); err != nil { - return Campaign{}, err - } - baseMeta := &knowledge.CampaignRecheck{Enabled: true, Interval: interval, LastAt: now, LastDeltaCount: recheckLastDelta(base)} - if _, err := s.deps.Inception.SetCampaignRecheck(baseArchive.ID, baseMeta); err == nil { - base.Recheck = campaignRecheckFromKnowledge(baseMeta, false, now) - } - repo := firstCampaignRepo(base) - leaseKey := revision.ID + ":" + StageSpec - if repo != "" { - leaseKey = repo + "!" + leaseKey - } - taskID := recheckTaskPrefix + sanitizeReceiptSegment(revision.ID) - if err := s.contributeHub.recordLeaseForKeyStage(runAdmissionIdentity, taskID, repo, 0, leaseKey, "triage", StageSpec, 1, now); err != nil { - return Campaign{}, err - } - if s.audit != nil { - s.audit.Log(actor, "campaign_recheck", auditDetail("campaign", base.ID, "revision", revision.ID, "reason", reason), "") - } - return campaignFromInceptionArchive(*revision), nil -} - -func (s *Server) recheckInterval(c Campaign) time.Duration { - if c.Recheck != nil && c.Recheck.Interval != "" { - if d, err := time.ParseDuration(c.Recheck.Interval); err == nil && d > 0 { - return d - } - } - if s != nil && s.deps != nil && s.deps.Config != nil { - return s.deps.Config.Runs.Spektacular.DefaultRecheckInterval() - } - return config.DefaultSpektacularRecheckInterval -} - -func (s *Server) decorateCampaignRechecks(campaigns map[string]Campaign) { - if s == nil || s.deps == nil || s.deps.Config == nil { - return - } - defaultEnabled := s.deps.Config.Runs.Spektacular.Recheck.Enabled - now := time.Now() - inFlight := map[string]bool{} - for _, c := range campaigns { - if c.RevisionOf != "" && c.CurrentStage != "completed" && c.Status != "shipped" { - inFlight[c.RevisionOf] = true - } - } - for id, c := range campaigns { - if c.Recheck == nil { - interval := s.deps.Config.Runs.Spektacular.DefaultRecheckInterval() - c.Recheck = &CampaignRecheck{Enabled: defaultEnabled, Interval: interval.String()} - } - c.Recheck.InFlight = c.Recheck.InFlight || inFlight[id] - if c.Recheck.Enabled && c.Recheck.NextAt == "" { - last := parseCampaignTime(c.LastActivity) - if last.IsZero() { - last = now - } - if c.Recheck.LastAt != "" { - if t, err := time.Parse(time.RFC3339, c.Recheck.LastAt); err == nil { - last = t - } - } - if d, err := time.ParseDuration(c.Recheck.Interval); err == nil && d > 0 { - c.Recheck.NextAt = last.Add(d).Format(time.RFC3339) - } - } - campaigns[id] = c - } -} - -func campaignRecheckFromArchive(archive knowledge.InceptionCampaignArchive, inFlight bool) *CampaignRecheck { - if archive.Recheck == nil && archive.RecheckInterval > 0 { - return campaignRecheckFromKnowledge(&knowledge.CampaignRecheck{Enabled: true, Interval: archive.RecheckInterval}, inFlight, archive.ArchivedAt) - } - return campaignRecheckFromKnowledge(archive.Recheck, inFlight, archive.ArchivedAt) -} - -func campaignRecheckFromKnowledge(recheck *knowledge.CampaignRecheck, inFlight bool, basis time.Time) *CampaignRecheck { - if recheck == nil { - return nil - } - out := &CampaignRecheck{ - Enabled: recheck.Enabled, - Interval: recheck.Interval.String(), - LastAt: formatRunTime(recheck.LastAt), - InFlight: inFlight, - LastDeltaCount: recheck.LastDeltaCount, - } - if recheck.Enabled && recheck.Interval > 0 { - last := recheck.LastAt - if last.IsZero() { - last = basis - } - if !last.IsZero() { - out.NextAt = last.Add(recheck.Interval).Format(time.RFC3339) - } - } - return out -} - -func parseCampaignTime(value string) time.Time { - value = strings.TrimSpace(value) - if value == "" { - return time.Time{} - } - if t, err := time.Parse(time.RFC3339, value); err == nil { - return t - } - return time.Time{} -} - -func campaignDriftFromArchive(archive knowledge.InceptionCampaignArchive) *CampaignDrift { - if archive.Drift == nil { - return nil - } - return &CampaignDrift{ - DriftSource: archive.Drift.DriftSource, - CodebaseChanged: archive.Drift.CodebaseChanged, - PriorHeadSHA: archive.Drift.PriorHeadSHA, - CurrentHeadSHA: archive.Drift.CurrentHeadSHA, - PriorRevision: archive.Drift.PriorRevision, - DeltaCount: archive.Drift.DeltaCount, - RecheckReason: archive.Drift.RecheckReason, - External: campaignExternalEvidenceFromKnowledge(archive.Drift.External), - ExternalCount: archive.Drift.ExternalCount, - SourcesFailed: campaignSourceFailuresFromKnowledge(archive.Drift.SourcesFailed), - } -} - -func campaignExternalEvidenceFromKnowledge(in []knowledge.CampaignExternalEvidence) []CampaignExternalEvidence { - if len(in) == 0 { - return nil - } - out := make([]CampaignExternalEvidence, 0, len(in)) - for _, ev := range in { - out = append(out, CampaignExternalEvidence{ - Source: ev.Source, - Kind: ev.Kind, - Title: ev.Title, - URL: ev.URL, - PublishedAt: formatRunTime(ev.PublishedAt), - Summary: ev.Summary, - }) - } - return out -} - -func campaignSourceFailuresFromKnowledge(in []knowledge.CampaignSourceFailure) []CampaignSourceFailure { - if len(in) == 0 { - return nil - } - out := make([]CampaignSourceFailure, 0, len(in)) - for _, fail := range in { - out = append(out, CampaignSourceFailure{Name: fail.Name, Reason: fail.Reason}) - } - return out -} - -func (s *Server) importRecheckDelta(runKey, repo, taskList, source string) (bool, error) { - if s == nil || s.deps == nil || s.deps.Inception == nil { - return false, nil - } - archive, err := s.deps.Inception.LoadCampaignArchive(runKey) - if err != nil || archive == nil || archive.RevisionOf == "" || archive.Drift == nil { - return false, nil - } - filtered, delta, capped := s.deltaTaskList(archive.RevisionOf, taskList) - archive.Drift.DeltaCount = delta - _, _ = s.deps.Inception.SetCampaignDrift(runKey, archive.Drift) - if capped && s.audit != nil { - s.audit.Log("system", "campaign_recheck_delta_capped", auditDetail("campaign", archive.RevisionOf, "revision", runKey, "delta", strconv.Itoa(delta)), "") - } - if strings.TrimSpace(filtered) == "" { - if s.audit != nil { - s.audit.Log("system", "campaign_recheck_delta_empty", auditDetail("campaign", archive.RevisionOf, "revision", runKey), "") - } - return true, nil - } - return true, s.importRunPlanDirect(runKey, repo, filtered, source) -} - -func (s *Server) deltaTaskList(priorRunKey, taskList string) (string, int, bool) { - tasks := agentparse.ParseTaskList(agentparse.SplitLines(taskList)) - if len(tasks) == 0 { - return "", 0, false - } - seen := s.priorTaskHashes(priorRunKey) - max := config.DefaultSpektacularMaxDeltaTasks - if s != nil && s.deps != nil && s.deps.Config != nil { - max = s.deps.Config.Runs.Spektacular.MaxDeltaTasks() - } - var out strings.Builder - delta := 0 - capped := false - for _, task := range tasks { - hash := taskContentHash(task) - if seen[hash] { - continue - } - delta++ - if delta > max { - capped = true - continue - } - fmt.Fprintf(&out, "%d. [%s] %s", delta, firstRunNonEmpty(task.Ref, fmt.Sprintf("T%d", delta)), task.Title) - if len(task.DependsOn) > 0 { - fmt.Fprintf(&out, " (depends: %s)", strings.Join(task.DependsOn, ", ")) - } - if task.Execution != "" { - fmt.Fprintf(&out, " [%s]", task.Execution) - } - out.WriteByte('\n') - } - return out.String(), minInt(delta, max), capped -} - -func (s *Server) priorTaskHashes(runKey string) map[string]bool { - out := map[string]bool{} - if s == nil || s.deps == nil { - return out - } - for _, store := range s.deps.BeadStores { - if store == nil { - continue - } - for _, b := range store.List(beads.ListFilter{}) { - if b.Type != beads.TypeEpic || b.Meta(planning.MetaRunKey) != runKey { - continue - } - tree, err := planning.GetPlanTree(store, b.ID) - if err != nil || tree == nil { - continue - } - for _, child := range tree.Children { - out[taskHashFromTitle(child.Title)] = true - } - return out - } - } - return out -} - -func taskContentHash(task agentparse.Task) string { - return taskHashFromTitle(task.Title) -} - -func taskHashFromTitle(title string) string { - sum := sha256.Sum256([]byte(strings.ToLower(strings.Join(strings.Fields(title), " ")))) - return hex.EncodeToString(sum[:]) -} - -func firstCampaignRepo(c Campaign) string { - if len(c.Repos) > 0 && strings.TrimSpace(c.Repos[0]) != "" { - return strings.TrimSpace(c.Repos[0]) - } - if c.RunKey != "" { - if ref, ok := splitRunRepo(c.RunKey); ok { - return ref - } - } - return "" -} - -func splitRunRepo(key string) (string, bool) { - if i := strings.Index(key, "#"); i > 0 { - return key[:i], true - } - if i := strings.Index(key, "!"); i > 0 { - return key[:i], true - } - return "", false -} - -func priorCampaignHead(c Campaign) string { - if c.Drift != nil && c.Drift.CurrentHeadSHA != "" { - return c.Drift.CurrentHeadSHA - } - return "" -} - -func recheckLastDelta(c Campaign) int { - if c.Recheck != nil { - return c.Recheck.LastDeltaCount - } - if c.Drift != nil { - return c.Drift.DeltaCount - } - return 0 -} - -func currentGitHead(ctx context.Context) string { - if ctx == nil { - ctx = context.Background() - } - runCtx, cancel := context.WithTimeout(ctx, gitHeadTimeout) - defer cancel() - out, err := exec.CommandContext(runCtx, "git", "rev-parse", "HEAD").Output() - if err != nil { - return "" - } - return strings.TrimSpace(string(out)) -} diff --git a/src/pkg/dashboard/campaign_recheck_test.go b/src/pkg/dashboard/campaign_recheck_test.go deleted file mode 100644 index 0b12c714eb..0000000000 --- a/src/pkg/dashboard/campaign_recheck_test.go +++ /dev/null @@ -1,740 +0,0 @@ -package dashboard - -import ( - "context" - "encoding/json" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/hivecommons/hive/crux/agentparse" - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" - "github.com/hivecommons/hive/pkg/planning" -) - -// writeCampaignArchiveFixture persists an archive exactly where the inception -// engine reads it, so tests can shape fields (State, Recheck) that the -// external-campaign API never sets. -func writeCampaignArchiveFixture(t *testing.T, dataDir string, archive knowledge.InceptionCampaignArchive) { - t.Helper() - dir := filepath.Join(dataDir, "inception", "campaigns", archive.ID) - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - data, err := json.Marshal(archive) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "state.json"), data, 0o644); err != nil { - t.Fatal(err) - } -} - -func shippedCampaignArchive(id string, now time.Time, recheck *knowledge.CampaignRecheck) knowledge.InceptionCampaignArchive { - started := now.Add(-48 * time.Hour) - return knowledge.InceptionCampaignArchive{ - ID: id, Title: "Shipped idea", Engine: "Spec Kit", Type: "inception", - Repos: []string{"acme/tool"}, - ArchivedAt: now.Add(-24 * time.Hour), - Recheck: recheck, - State: &knowledge.InceptionState{ - Phase: knowledge.PhaseComplete, IdeaText: "Ship it", IdeaSlug: id, - StartedAt: started, Answers: map[string]string{}, Questions: []knowledge.Question{}, - }, - } -} - -func campaignRecheckAuditActions(s *Server) []string { - var out []string - for _, e := range s.audit.Recent(0) { - if strings.HasPrefix(e.Action, "campaign_recheck") { - out = append(out, e.Action) - } - } - return out -} - -func TestCampaignRecheckPureHelpers(t *testing.T) { - for _, tc := range []struct { - key string - want string - ok bool - }{ - {"acme/tool#42", "acme/tool", true}, - {"acme/tool!spec-1", "acme/tool", true}, - {"#42", "", false}, - {"!spec", "", false}, - {"plain-key", "", false}, - } { - got, ok := splitRunRepo(tc.key) - if got != tc.want || ok != tc.ok { - t.Errorf("splitRunRepo(%q) = %q,%v want %q,%v", tc.key, got, ok, tc.want, tc.ok) - } - } - - if got := firstCampaignRepo(Campaign{Repos: []string{" acme/one ", "acme/two"}}); got != "acme/one" { - t.Errorf("firstCampaignRepo repos = %q", got) - } - if got := firstCampaignRepo(Campaign{Repos: []string{" "}, RunKey: "acme/run!key"}); got != "acme/run" { - t.Errorf("firstCampaignRepo blank repo should fall back to run key, got %q", got) - } - if got := firstCampaignRepo(Campaign{RunKey: "no-repo-key"}); got != "" { - t.Errorf("firstCampaignRepo unparseable run key = %q", got) - } - if got := firstCampaignRepo(Campaign{}); got != "" { - t.Errorf("firstCampaignRepo empty = %q", got) - } - - if got := priorCampaignHead(Campaign{}); got != "" { - t.Errorf("priorCampaignHead without drift = %q", got) - } - if got := priorCampaignHead(Campaign{Drift: &CampaignDrift{CurrentHeadSHA: "abc123"}}); got != "abc123" { - t.Errorf("priorCampaignHead = %q", got) - } - - if got := recheckLastDelta(Campaign{}); got != 0 { - t.Errorf("recheckLastDelta empty = %d", got) - } - if got := recheckLastDelta(Campaign{Drift: &CampaignDrift{DeltaCount: 4}}); got != 4 { - t.Errorf("recheckLastDelta drift = %d", got) - } - if got := recheckLastDelta(Campaign{Recheck: &CampaignRecheck{LastDeltaCount: 7}, Drift: &CampaignDrift{DeltaCount: 4}}); got != 7 { - t.Errorf("recheckLastDelta should prefer recheck meta, got %d", got) - } - - if !parseCampaignTime(" ").IsZero() || !parseCampaignTime("yesterday").IsZero() { - t.Error("parseCampaignTime accepted invalid input") - } - if got := parseCampaignTime("2026-10-05T00:00:00Z"); !got.Equal(time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) { - t.Errorf("parseCampaignTime = %v", got) - } - - // Task identity is whitespace- and case-insensitive so a re-wrapped plan - // line is not reimported as a new delta. - a := taskContentHash(agentparse.Task{Title: "Add Helpers\tfor encoding"}) - b := taskHashFromTitle("add helpers for ENCODING") - if a != b || len(a) != 64 { - t.Errorf("task hashes differ: %s vs %s", a, b) - } - if taskHashFromTitle("add helpers") == taskHashFromTitle("add helper") { - t.Error("distinct titles collided") - } -} - -func TestCampaignRecheckProjectionsFromArchive(t *testing.T) { - basis := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) - - if got := campaignRecheckFromKnowledge(nil, true, basis); got != nil { - t.Fatalf("nil recheck projected: %+v", got) - } - // Enabled with a zero basis and no LastAt has no schedule. - got := campaignRecheckFromKnowledge(&knowledge.CampaignRecheck{Enabled: true, Interval: time.Hour}, false, time.Time{}) - if got == nil || got.NextAt != "" || got.Interval != "1h0m0s" || got.LastAt != "" { - t.Fatalf("zero-basis recheck = %+v", got) - } - // Disabled rechecks never schedule, even with an interval. - got = campaignRecheckFromKnowledge(&knowledge.CampaignRecheck{Enabled: false, Interval: time.Hour}, true, basis) - if got == nil || got.NextAt != "" || !got.InFlight || got.Enabled { - t.Fatalf("disabled recheck = %+v", got) - } - // LastAt wins over the archive basis. - last := basis.Add(6 * time.Hour) - got = campaignRecheckFromKnowledge(&knowledge.CampaignRecheck{Enabled: true, Interval: time.Hour, LastAt: last, LastDeltaCount: 3}, false, basis) - if got == nil || got.NextAt != last.Add(time.Hour).Format(time.RFC3339) || got.LastAt != formatRunTime(last) || got.LastDeltaCount != 3 { - t.Fatalf("recheck with last_at = %+v", got) - } - - // Legacy archives carry only RecheckInterval; it still projects as enabled. - legacy := campaignRecheckFromArchive(knowledge.InceptionCampaignArchive{RecheckInterval: 2 * time.Hour, ArchivedAt: basis}, false) - if legacy == nil || !legacy.Enabled || legacy.Interval != "2h0m0s" || legacy.NextAt != basis.Add(2*time.Hour).Format(time.RFC3339) { - t.Fatalf("legacy interval projection = %+v", legacy) - } - if got := campaignRecheckFromArchive(knowledge.InceptionCampaignArchive{ArchivedAt: basis}, false); got != nil { - t.Fatalf("archive without recheck projected: %+v", got) - } - - if got := campaignDriftFromArchive(knowledge.InceptionCampaignArchive{}); got != nil { - t.Fatalf("nil drift projected: %+v", got) - } - published := basis.Add(time.Minute) - drift := campaignDriftFromArchive(knowledge.InceptionCampaignArchive{Drift: &knowledge.CampaignDrift{ - CodebaseChanged: true, PriorHeadSHA: "aaa", CurrentHeadSHA: "bbb", PriorRevision: "base", DeltaCount: 2, RecheckReason: recheckReasonCadence, - External: []knowledge.CampaignExternalEvidence{{Source: "upstream", Kind: "release", Title: "v2", URL: "https://example.invalid/v2", PublishedAt: published, Summary: "adds a thing"}}, - ExternalCount: 1, - SourcesFailed: []knowledge.CampaignSourceFailure{{Name: "feed", Reason: "timeout"}}, - }}) - if drift == nil || !drift.CodebaseChanged || drift.PriorHeadSHA != "aaa" || drift.CurrentHeadSHA != "bbb" || drift.PriorRevision != "base" || drift.DeltaCount != 2 || drift.RecheckReason != recheckReasonCadence || drift.ExternalCount != 1 { - t.Fatalf("drift projection = %+v", drift) - } - if len(drift.External) != 1 || drift.External[0].Source != "upstream" || drift.External[0].Kind != "release" || drift.External[0].Title != "v2" || drift.External[0].URL != "https://example.invalid/v2" || drift.External[0].PublishedAt != formatRunTime(published) || drift.External[0].Summary != "adds a thing" { - t.Fatalf("external evidence projection = %+v", drift.External) - } - if len(drift.SourcesFailed) != 1 || drift.SourcesFailed[0].Name != "feed" || drift.SourcesFailed[0].Reason != "timeout" { - t.Fatalf("source failures projection = %+v", drift.SourcesFailed) - } - if campaignExternalEvidenceFromKnowledge(nil) != nil || campaignSourceFailuresFromKnowledge(nil) != nil { - t.Fatal("empty knowledge slices should project as nil") - } -} - -func TestDecorateCampaignRechecksFillsDefaultsAndSchedule(t *testing.T) { - var nilServer *Server - nilServer.decorateCampaignRechecks(map[string]Campaign{"x": {}}) // nil receiver is a no-op - - s := &Server{deps: &Dependencies{Config: &config.Config{}}} - s.deps.Config.Runs.Spektacular.Recheck.Enabled = true - s.deps.Config.Runs.Spektacular.Recheck.DefaultInterval = 3 * time.Hour - lastActivity := time.Date(2026, 10, 2, 0, 0, 0, 0, time.UTC) - lastAt := time.Date(2026, 10, 3, 0, 0, 0, 0, time.UTC) - campaigns := map[string]Campaign{ - // No recheck meta: inherits the default cadence and schedules from LastActivity. - "base": {ID: "base", LastActivity: formatRunTime(lastActivity), CurrentStage: "completed"}, - // Explicit LastAt beats LastActivity. - "explicit": {ID: "explicit", LastActivity: formatRunTime(lastActivity), Recheck: &CampaignRecheck{Enabled: true, Interval: "2h", LastAt: formatRunTime(lastAt)}}, - // No activity at all schedules from "now". - "fresh": {ID: "fresh", Recheck: &CampaignRecheck{Enabled: true, Interval: "1h"}}, - // Invalid interval leaves NextAt empty. - "broken": {ID: "broken", Recheck: &CampaignRecheck{Enabled: true, Interval: "soon"}}, - // Disabled rechecks are left unscheduled. - "off": {ID: "off", Recheck: &CampaignRecheck{Enabled: false, Interval: "1h"}}, - // A live revision of "base" marks the base in flight. - "base-rev-2": {ID: "base-rev-2", RevisionOf: "base", CurrentStage: StageSpec, Status: "parked", Recheck: &CampaignRecheck{Enabled: true, Interval: "1h", NextAt: "keep"}}, - // A completed revision does not. - "explicit-rev-2": {ID: "explicit-rev-2", RevisionOf: "explicit", CurrentStage: "completed", Status: "shipped", Recheck: &CampaignRecheck{Enabled: false}}, - } - before := time.Now() - s.decorateCampaignRechecks(campaigns) - - base := campaigns["base"] - if base.Recheck == nil || !base.Recheck.Enabled || base.Recheck.Interval != "3h0m0s" || !base.Recheck.InFlight { - t.Fatalf("base recheck defaults = %+v", base.Recheck) - } - if base.Recheck.NextAt != lastActivity.Add(3*time.Hour).Format(time.RFC3339) { - t.Fatalf("base next_at = %q", base.Recheck.NextAt) - } - explicit := campaigns["explicit"] - if explicit.Recheck.InFlight || explicit.Recheck.NextAt != lastAt.Add(2*time.Hour).Format(time.RFC3339) { - t.Fatalf("explicit recheck = %+v", explicit.Recheck) - } - fresh := campaigns["fresh"] - next, err := time.Parse(time.RFC3339, fresh.Recheck.NextAt) - if err != nil || next.Before(before.Add(time.Hour).Truncate(time.Second)) { - t.Fatalf("fresh next_at = %q (err %v)", fresh.Recheck.NextAt, err) - } - if campaigns["broken"].Recheck.NextAt != "" || campaigns["off"].Recheck.NextAt != "" { - t.Fatalf("unschedulable rechecks got a next_at: broken=%+v off=%+v", campaigns["broken"].Recheck, campaigns["off"].Recheck) - } - if campaigns["base-rev-2"].Recheck.NextAt != "keep" { - t.Fatal("existing next_at was overwritten") - } - - // A disabled default leaves campaigns without meta opted out. - s.deps.Config.Runs.Spektacular.Recheck.Enabled = false - opted := map[string]Campaign{"quiet": {ID: "quiet"}} - s.decorateCampaignRechecks(opted) - if r := opted["quiet"].Recheck; r == nil || r.Enabled || r.NextAt != "" { - t.Fatalf("default-off recheck = %+v", r) - } -} - -func TestRecheckIntervalPrecedence(t *testing.T) { - var nilServer *Server - if got := nilServer.recheckInterval(Campaign{}); got != config.DefaultSpektacularRecheckInterval { - t.Fatalf("nil server interval = %v", got) - } - if got := nilServer.recheckInterval(Campaign{Recheck: &CampaignRecheck{Interval: "45m"}}); got != 45*time.Minute { - t.Fatalf("campaign interval = %v", got) - } - s := &Server{deps: &Dependencies{Config: &config.Config{}}} - s.deps.Config.Runs.Spektacular.Recheck.DefaultInterval = 5 * time.Hour - if got := s.recheckInterval(Campaign{Recheck: &CampaignRecheck{Interval: "-1h"}}); got != 5*time.Hour { - t.Fatalf("non-positive campaign interval should fall back to config, got %v", got) - } - if got := s.recheckInterval(Campaign{Recheck: &CampaignRecheck{Interval: "later"}}); got != 5*time.Hour { - t.Fatalf("invalid campaign interval should fall back to config, got %v", got) - } -} - -func TestCampaignRecheckHandlerRejections(t *testing.T) { - s, deps := runsTestServer(t) - deps.Config.Runs.Spektacular = config.SpektacularConfig{Enabled: true} - - // Owner gate first: an anonymous caller never reaches the campaign store. - rec := httptest.NewRecorder() - s.mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/campaigns/anything/recheck?force=true", nil)) - if rec.Code != http.StatusForbidden { - t.Fatalf("anonymous recheck = %d body=%s, want 403", rec.Code, rec.Body.String()) - } - - // A blank path value (after unescaping) is a 400, not a lookup. - rec = httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/campaigns/%20/recheck", nil) - req.SetPathValue("id", "%20") - markOwnerRequest(req) - s.handleCampaignRecheck(rec, req) - if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "campaign id required") { - t.Fatalf("blank id recheck = %d body=%s, want 400", rec.Code, rec.Body.String()) - } - - // No inception engine: the store is unavailable and surfaces as a 500. - s.deps.Inception = nil - rec = doOwnerPostAsUser(s, "/api/campaigns/stable-spec-8665/recheck?force=true", "bob", map[string]string{}) - if rec.Code != http.StatusInternalServerError || !strings.Contains(rec.Body.String(), "campaign store unavailable") { - t.Fatalf("storeless recheck = %d body=%s, want 500", rec.Code, rec.Body.String()) - } - - // Unknown campaign is a 404 distinct from "disabled". - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - rec = doOwnerPostAsUser(s, "/api/campaigns/no-such-campaign/recheck?force=true", "bob", map[string]string{}) - if rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), "campaign not found") { - t.Fatalf("unknown recheck = %d body=%s, want 404", rec.Code, rec.Body.String()) - } -} - -func TestTriggerCampaignRecheckRequiresStore(t *testing.T) { - var nilServer *Server - if _, err := nilServer.triggerCampaignRecheck(context.Background(), "x", "owner", recheckReasonManual, true, time.Time{}); err == nil { - t.Fatal("nil server accepted a recheck") - } - s := &Server{deps: &Dependencies{Config: &config.Config{}, Inception: knowledge.NewInceptionEngine(t.TempDir(), nil, slog.Default())}} - if _, err := s.triggerCampaignRecheck(context.Background(), "x", "owner", recheckReasonManual, true, time.Time{}); err == nil || !strings.Contains(err.Error(), "campaign store unavailable") { - t.Fatalf("hub-less recheck err = %v", err) - } -} - -func TestTriggerCampaignRecheckByRunKeyAndMetadata(t *testing.T) { - s, deps := runsTestServer(t) - deps.Config.Runs.Spektacular = config.SpektacularConfig{Enabled: true} - deps.Config.Runs.Spektacular.Recheck.DefaultInterval = 9 * time.Hour - dataDir := t.TempDir() - s.deps.Inception = knowledge.NewInceptionEngine(dataDir, nil, s.logger) - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - base, err := s.deps.Inception.UpsertExternalCampaign("run-base", "Research", "acme/tool!run-base", "Spektacular", "spektacular", nil, now.Add(-time.Hour)) - if err != nil { - t.Fatal(err) - } - if _, err := s.deps.Inception.SetCampaignDrift(base.ID, &knowledge.CampaignDrift{CurrentHeadSHA: "deadbeef", DeltaCount: 5}); err != nil { - t.Fatal(err) - } - // The campaign's own cadence (4h) must beat the configured default (9h), - // and its last delta count must carry forward onto the base metadata. - if _, err := s.deps.Inception.SetCampaignRecheck(base.ID, &knowledge.CampaignRecheck{Enabled: false, Interval: 4 * time.Hour, LastDeltaCount: 5}); err != nil { - t.Fatal(err) - } - - // Lookup by RunKey (the archive's Source) rather than ID, with a zero - // "now" that the trigger must fill in itself. - revision, err := s.triggerCampaignRecheck(context.Background(), "acme/tool!run-base", "bob", recheckReasonManual, true, time.Time{}) - if err != nil { - t.Fatal(err) - } - if revision.RevisionOf != base.ID || revision.Revision != 2 || revision.CurrentStage != StageSpec { - t.Fatalf("revision = %+v", revision) - } - if revision.Recheck == nil || !revision.Recheck.Enabled || revision.Recheck.Interval != "4h0m0s" { - t.Fatalf("revision recheck meta = %+v", revision.Recheck) - } - if revision.Drift == nil || revision.Drift.PriorHeadSHA != "deadbeef" || revision.Drift.PriorRevision != base.ID || revision.Drift.RecheckReason != recheckReasonManual { - t.Fatalf("revision drift = %+v", revision.Drift) - } - // Repo derived from the run key prefixes the stage lease key. - if _, held := s.contributeHub.runLeaseHolder("acme/tool!"+revision.ID+":"+StageSpec, time.Now()); !held { - t.Fatalf("stage lease for revision %s not recorded", revision.ID) - } - - stored, err := s.deps.Inception.LoadCampaignArchive(base.ID) - if err != nil { - t.Fatal(err) - } - if stored.Recheck == nil || !stored.Recheck.Enabled || stored.Recheck.LastAt.IsZero() || stored.Recheck.LastDeltaCount != 5 || stored.Recheck.Interval != 4*time.Hour { - t.Fatalf("base recheck meta after trigger = %+v", stored.Recheck) - } - if stored.Drift == nil || stored.Drift.CurrentHeadSHA != "deadbeef" { - t.Fatalf("base drift was rewritten: %+v", stored.Drift) - } - if actions := campaignRecheckAuditActions(s); len(actions) != 1 || actions[0] != "campaign_recheck" { - t.Fatalf("audit actions = %v", actions) - } - - // A second manual trigger finds the live revision and refuses. - if _, err := s.triggerCampaignRecheck(context.Background(), base.ID, "bob", recheckReasonManual, true, now); err != errRecheckInFlight { - t.Fatalf("in-flight trigger err = %v", err) - } -} - -func TestTriggerCampaignRecheckSurfacesStoreWriteFailure(t *testing.T) { - if os.Geteuid() == 0 { - t.Skip("directory modes do not stop root; cannot inject a write failure") - } - s, deps := runsTestServer(t) - deps.Config.Runs.Spektacular = config.SpektacularConfig{Enabled: true} - dataDir := t.TempDir() - s.deps.Inception = knowledge.NewInceptionEngine(dataDir, nil, s.logger) - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - if _, err := s.deps.Inception.UpsertExternalCampaign("sealed", "Research", "sealed", "Spektacular", "spektacular", nil, now); err != nil { - t.Fatal(err) - } - campaignDir := filepath.Join(dataDir, "inception", "campaigns", "sealed") - if err := os.Chmod(campaignDir, 0o500); err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = os.Chmod(campaignDir, 0o700) }) - - if _, err := s.triggerCampaignRecheck(context.Background(), "sealed", "bob", recheckReasonManual, true, now); err == nil { - t.Fatal("unwritable archive accepted a recheck") - } - archives, err := s.deps.Inception.ListCampaignArchives() - if err != nil || len(archives) != 1 { - t.Fatalf("failed trigger left archives = %+v (err %v)", archives, err) - } - if actions := campaignRecheckAuditActions(s); len(actions) != 0 { - t.Fatalf("failed trigger was audited: %v", actions) - } -} - -func TestTickCampaignRechecksCadence(t *testing.T) { - var nilServer *Server - nilServer.TickCampaignRechecks(context.Background(), time.Now()) // nil receiver is a no-op - - s, deps := runsTestServer(t) - dataDir := t.TempDir() - s.deps.Inception = knowledge.NewInceptionEngine(dataDir, nil, s.logger) - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - due := &knowledge.CampaignRecheck{Enabled: true, Interval: time.Hour, LastAt: now.Add(-2 * time.Hour)} - writeCampaignArchiveFixture(t, dataDir, shippedCampaignArchive("shipped-due", now, due)) - writeCampaignArchiveFixture(t, dataDir, shippedCampaignArchive("shipped-later", now, &knowledge.CampaignRecheck{Enabled: true, Interval: time.Hour, LastAt: now})) - writeCampaignArchiveFixture(t, dataDir, shippedCampaignArchive("shipped-opted-out", now, &knowledge.CampaignRecheck{Enabled: false, Interval: time.Hour, LastAt: now.Add(-2 * time.Hour)})) - inProgress := shippedCampaignArchive("still-drafting", now, due) - inProgress.State.Phase = knowledge.PhaseClarify - writeCampaignArchiveFixture(t, dataDir, inProgress) - if _, err := s.deps.Inception.UpsertExternalCampaign("external-plan", "Research", "acme/tool!plan", "Spektacular", "spektacular", []string{"acme/tool"}, now.Add(-48*time.Hour)); err != nil { - t.Fatal(err) - } - - countArchives := func() int { - t.Helper() - archives, err := s.deps.Inception.ListCampaignArchives() - if err != nil { - t.Fatal(err) - } - return len(archives) - } - - // Cadence is scheduler-owned: with the feature off nothing moves. - deps.Config.Runs.Spektacular.Recheck.Enabled = false - s.TickCampaignRechecks(context.Background(), now) - if got := countArchives(); got != 5 { - t.Fatalf("disabled tick changed archives: %d", got) - } - - deps.Config.Runs.Spektacular.Recheck.Enabled = true - s.TickCampaignRechecks(context.Background(), now) - if got := countArchives(); got != 6 { - t.Fatalf("archives after due tick = %d, want exactly one new revision", got) - } - revision, err := s.deps.Inception.LoadCampaignArchive("shipped-due-rev-2") - if err != nil { - t.Fatalf("due campaign was not revised: %v", err) - } - if revision.RevisionOf != "shipped-due" || revision.Drift == nil || revision.Drift.RecheckReason != recheckReasonCadence || revision.Drift.PriorRevision != "shipped-due" { - t.Fatalf("cadence revision = %+v drift=%+v", revision, revision.Drift) - } - if revision.Recheck == nil || !revision.Recheck.Enabled || revision.Recheck.Interval != time.Hour { - t.Fatalf("cadence revision inherits interval: %+v", revision.Recheck) - } - base, err := s.deps.Inception.LoadCampaignArchive("shipped-due") - if err != nil { - t.Fatal(err) - } - if base.Recheck == nil || !base.Recheck.LastAt.Equal(now) { - t.Fatalf("base last_at not advanced: %+v", base.Recheck) - } - entries := s.audit.Recent(0) - var cadenceAudit int - for _, e := range entries { - if e.Action == "campaign_recheck" && e.User == "system" && strings.Contains(e.Detail, "shipped-due") { - cadenceAudit++ - } - } - if cadenceAudit != 1 { - t.Fatalf("cadence audit entries = %d in %+v", cadenceAudit, entries) - } - - // Same instant again: the live revision marks the base in flight and the - // revision itself is not completed, so neither is rechecked. - s.TickCampaignRechecks(context.Background(), now) - if got := countArchives(); got != 6 { - t.Fatalf("repeat tick created archives: %d", got) - } - // Advancing past the next cadence still waits on the in-flight revision: - // shipped-later (last_at=now, 1h) becomes due and is revised, but - // shipped-due gets no rev-3 while shipped-due-rev-2 is open. - s.TickCampaignRechecks(context.Background(), now.Add(3*time.Hour)) - if got := countArchives(); got != 7 { - t.Fatalf("archives after later tick = %d, want shipped-later revised once", got) - } - if _, err := s.deps.Inception.LoadCampaignArchive("shipped-later-rev-2"); err != nil { - t.Fatalf("shipped-later was not revised once due: %v", err) - } - if _, err := s.deps.Inception.LoadCampaignArchive("shipped-due-rev-3"); err == nil { - t.Fatal("in-flight base was rechecked again") - } -} - -func TestTickCampaignRechecksLogsTriggerFailure(t *testing.T) { - dataDir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - cfg := &config.Config{} - cfg.Runs.Spektacular.Recheck.Enabled = true - s := &Server{deps: &Dependencies{Config: cfg, Inception: knowledge.NewInceptionEngine(dataDir, nil, logger)}, logger: logger} - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - writeCampaignArchiveFixture(t, dataDir, shippedCampaignArchive("shipped-due", now, &knowledge.CampaignRecheck{Enabled: true, Interval: time.Hour, LastAt: now.Add(-2 * time.Hour)})) - - // Without a contribute hub the trigger cannot record the stage lease; the - // tick must swallow and log the error rather than panic or loop. - s.TickCampaignRechecks(context.Background(), now) - archives, err := s.deps.Inception.ListCampaignArchives() - if err != nil || len(archives) != 1 { - t.Fatalf("failed cadence trigger left archives = %+v (err %v)", archives, err) - } - - // An unreadable campaign root makes the listing fail; the tick returns quietly. - if os.Geteuid() != 0 { - root := filepath.Join(dataDir, "inception", "campaigns") - if err := os.Chmod(root, 0o000); err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = os.Chmod(root, 0o755) }) - s.TickCampaignRechecks(context.Background(), now) - } -} - -func TestImportRunPlanRecheckDeltaOnlyImportsNewTasks(t *testing.T) { - _, s, store, _ := spekHub(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - - // Plans for a run that is not a recheck revision take the direct path. - if err := s.ImportRunPlan(spekRunKey, spekRepo, "1. [T1] Add helpers [agent_suitable]\n2. [T2] Write docs [agent_suitable]"); err != nil { - t.Fatal(err) - } - _, baseEpic := s.findRunEpic(spekRunKey) - if baseEpic == nil { - t.Fatal("base epic missing") - } - // A retained campaign that is not a revision also takes the direct path. - if _, err := s.deps.Inception.UpsertExternalCampaign(spekRunKey, "Research", spekRunKey, "Spektacular", "spektacular", []string{spekRepo}, now); err != nil { - t.Fatal(err) - } - if handled, err := s.importRecheckDelta(spekRunKey, spekRepo, "1. [T9] Anything", runPlanSource); handled || err != nil { - t.Fatalf("non-revision archive handled=%v err=%v", handled, err) - } - - revision, err := s.deps.Inception.ReviseExternalCampaign(spekRunKey, "Research", spekRunKey, "Spektacular", "spektacular", "owner", []string{spekRepo}, now) - if err != nil { - t.Fatal(err) - } - // A revision without drift evidence is not a recheck either. - if handled, _ := s.importRecheckDelta(revision.ID, spekRepo, "1. [T9] Anything", runPlanSource); handled { - t.Fatal("revision without drift was treated as a recheck") - } - if _, err := s.deps.Inception.SetCampaignDrift(revision.ID, &knowledge.CampaignDrift{RecheckReason: recheckReasonManual}); err != nil { - t.Fatal(err) - } - - plan := strings.Join([]string{ - "1. [T1] Add helpers [agent_suitable]", // same task, re-wrapped: not a delta - "2. [T3] Migrate storage (depends: T1) [agent_suitable]", - "3. [T4] Get legal sign-off (human_required)", - }, "\n") - if err := s.ImportRunPlan(revision.ID, spekRepo, plan); err != nil { - t.Fatal(err) - } - _, revEpic := s.findRunEpic(revision.ID) - if revEpic == nil { - t.Fatal("revision epic missing") - } - tree, err := planning.GetPlanTree(store, revEpic.ID) - if err != nil { - t.Fatal(err) - } - var titles []string - for _, child := range tree.Children { - titles = append(titles, child.Title) - } - if len(titles) != 2 || strings.Contains(strings.Join(titles, "|"), "helpers") { - t.Fatalf("delta plan children = %v, want only the two new tasks", titles) - } - stored, err := s.deps.Inception.LoadCampaignArchive(revision.ID) - if err != nil { - t.Fatal(err) - } - if stored.Drift == nil || stored.Drift.DeltaCount != 2 || stored.Drift.RecheckReason != recheckReasonManual { - t.Fatalf("delta count not recorded: %+v", stored.Drift) - } - baseTree, err := planning.GetPlanTree(store, baseEpic.ID) - if err != nil || len(baseTree.Children) != 2 { - t.Fatalf("base plan changed: %+v err=%v", baseTree, err) - } - if actions := campaignRecheckAuditActions(s); len(actions) != 0 { - t.Fatalf("plain delta import was audited: %v", actions) - } -} - -func TestImportRunPlanRecheckDeltaEmptyAndCapped(t *testing.T) { - _, s, store, _ := spekHub(t) - s.deps.Inception = knowledge.NewInceptionEngine(t.TempDir(), nil, s.logger) - s.deps.Config.Runs.Spektacular.Recheck.MaxDeltaTasks = 1 - now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) - if err := s.ImportRunPlan(spekRunKey, spekRepo, "1. [T1] Add helpers [agent_suitable]"); err != nil { - t.Fatal(err) - } - if _, err := s.deps.Inception.UpsertExternalCampaign(spekRunKey, "Research", spekRunKey, "Spektacular", "spektacular", []string{spekRepo}, now); err != nil { - t.Fatal(err) - } - newRevision := func() string { - t.Helper() - revision, err := s.deps.Inception.ReviseExternalCampaign(spekRunKey, "Research", spekRunKey, "Spektacular", "spektacular", "owner", []string{spekRepo}, now) - if err != nil { - t.Fatal(err) - } - if _, err := s.deps.Inception.SetCampaignDrift(revision.ID, &knowledge.CampaignDrift{}); err != nil { - t.Fatal(err) - } - return revision.ID - } - - // Nothing new: no epic is minted for the revision and the empty delta is audited. - empty := newRevision() - if err := s.ImportRunPlan(empty, spekRepo, "1. [T1] add helpers [agent_suitable]"); err != nil { - t.Fatal(err) - } - if _, epic := s.findRunEpic(empty); epic != nil { - t.Fatalf("empty delta minted an epic: %+v", epic) - } - stored, err := s.deps.Inception.LoadCampaignArchive(empty) - if err != nil || stored.Drift == nil || stored.Drift.DeltaCount != 0 { - t.Fatalf("empty delta drift = %+v err=%v", stored.Drift, err) - } - // Not a task list at all is also empty. - if err := s.ImportRunPlan(empty, spekRepo, "prose without tasks"); err != nil { - t.Fatal(err) - } - - // Three new tasks against a cap of one: only the first is imported, the - // recorded delta is the cap, and the truncation is audited. - capped := newRevision() - if err := s.ImportRunPlan(capped, spekRepo, "1. [T2] Second\n2. [T3] Third\n3. [T4] Fourth"); err != nil { - t.Fatal(err) - } - _, epic := s.findRunEpic(capped) - if epic == nil { - t.Fatal("capped delta minted no epic") - } - tree, err := planning.GetPlanTree(store, epic.ID) - if err != nil || len(tree.Children) != 1 || tree.Children[0].Title != "Second" { - t.Fatalf("capped plan tree = %+v err=%v", tree, err) - } - stored, err = s.deps.Inception.LoadCampaignArchive(capped) - if err != nil || stored.Drift == nil || stored.Drift.DeltaCount != 1 { - t.Fatalf("capped delta drift = %+v err=%v", stored.Drift, err) - } - // Recent is newest-first. - actions := campaignRecheckAuditActions(s) - if len(actions) != 3 || actions[0] != "campaign_recheck_delta_capped" || actions[1] != "campaign_recheck_delta_empty" || actions[2] != "campaign_recheck_delta_empty" { - t.Fatalf("audit actions = %v", actions) - } -} - -func TestDeltaTaskListAndPriorHashes(t *testing.T) { - var nilServer *Server - if got := nilServer.priorTaskHashes("any"); len(got) != 0 { - t.Fatalf("nil server hashes = %v", got) - } - if out, delta, capped := nilServer.deltaTaskList("prior", "1. [T1] Solo task"); delta != 1 || capped || !strings.Contains(out, "1. [T1] Solo task") { - t.Fatalf("nil server delta = %q,%d,%v", out, delta, capped) - } - if _, delta, capped := nilServer.deltaTaskList("prior", "no tasks here"); delta != 0 || capped { - t.Fatalf("no-task delta = %d,%v", delta, capped) - } - - _, s, store, _ := spekHub(t) - // A nil store entry is skipped; the real store holds the prior plan. - s.deps.BeadStores["empty"] = nil - // An unrelated epic (different run key) must not contribute hashes. - other, err := store.Create("Other run", beads.TypeEpic, beads.PriorityMedium, planning.ArchitectAgentName, "other-run") - if err != nil { - t.Fatal(err) - } - if err := store.SetMetadata(other.ID, planning.MetaRunKey, "other-run"); err != nil { - t.Fatal(err) - } - other, _ = store.Get(other.ID) - if _, err := planning.DecomposeFromOutput(store, other, "1. [T1] Unrelated task", planning.Options{}); err != nil { - t.Fatal(err) - } - if err := s.ImportRunPlan(spekRunKey, spekRepo, "1. [T1] Add helpers\n2. [T2] Write docs"); err != nil { - t.Fatal(err) - } - seen := s.priorTaskHashes(spekRunKey) - if len(seen) != 2 || !seen[taskHashFromTitle("Add helpers")] || !seen[taskHashFromTitle("write DOCS")] || seen[taskHashFromTitle("Unrelated task")] { - t.Fatalf("prior hashes = %v", seen) - } - if got := s.priorTaskHashes("missing-run"); len(got) != 0 { - t.Fatalf("unknown run hashes = %v", got) - } - - plan := "1. [T1] Add helpers\n2. Migrate storage (depends: T1, T2) [agent_suitable]\n3. [T4] Legal (human_required)" - out, delta, capped := s.deltaTaskList(spekRunKey, plan) - if delta != 2 || capped { - t.Fatalf("delta = %d capped=%v out=%q", delta, capped, out) - } - lines := strings.Split(strings.TrimSpace(out), "\n") - if len(lines) != 2 { - t.Fatalf("delta list = %q", out) - } - // Renumbered from 1; a missing ref is synthesised; depends and execution tags survive. - if lines[0] != "1. [T1] Migrate storage (depends: T1, T2) [agent_suitable]" { - t.Fatalf("first delta line = %q", lines[0]) - } - if !strings.HasPrefix(lines[1], "2. [T4] Legal") || !strings.HasSuffix(lines[1], "[human_required]") { - t.Fatalf("second delta line = %q", lines[1]) - } - - s.deps.Config.Runs.Spektacular.Recheck.MaxDeltaTasks = 1 - out, delta, capped = s.deltaTaskList(spekRunKey, plan) - if delta != 1 || !capped || strings.Count(out, "\n") != 1 { - t.Fatalf("capped delta = %d capped=%v out=%q", delta, capped, out) - } -} - -func TestCurrentGitHeadAndEvidence(t *testing.T) { - dir := t.TempDir() - t.Chdir(dir) - // Point git at a repository that does not exist so the probe fails even - // when the temp directory happens to live inside a checkout. - t.Setenv("GIT_DIR", filepath.Join(dir, "no-such-repo")) - // Outside a repository the head is unknown and never reported as drift. - //nolint:staticcheck // SA1012: the nil-ctx fallback branch is the subject under test. - if head := currentGitHead(nil); head != "" { - t.Fatalf("head outside repo = %q", head) - } - evidence, err := (codebaseHeadEvidenceSource{}).Evidence(context.Background(), Campaign{}, "prior") - if err != nil || evidence.CodebaseChanged || evidence.PriorHeadSHA != "prior" || evidence.CurrentHeadSHA != "" { - t.Fatalf("evidence outside repo = %+v err=%v", evidence, err) - } - // A cancelled context short-circuits the git call. - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if head := currentGitHead(ctx); head != "" { - t.Fatalf("head with cancelled ctx = %q", head) - } -} diff --git a/src/pkg/dashboard/recheck_discovery.go b/src/pkg/dashboard/recheck_discovery.go deleted file mode 100644 index dff754cb15..0000000000 --- a/src/pkg/dashboard/recheck_discovery.go +++ /dev/null @@ -1,354 +0,0 @@ -package dashboard - -import ( - "context" - "encoding/xml" - "fmt" - "io" - "net/http" - "net/url" - "os" - "regexp" - "sort" - "strings" - "time" - "unicode/utf8" - - gh "github.com/google/go-github/v72/github" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -const ( - externalSummaryMaxRunes = 280 - discoveryFeedReadLimit = 1 << 20 -) - -type recheckDiscoveryCollector struct { - cfg config.SpektacularConfig - gh *gh.Client - client *http.Client -} - -func (s *Server) collectRecheckDiscovery(ctx context.Context, base Campaign, since time.Time) ([]knowledge.CampaignExternalEvidence, []knowledge.CampaignSourceFailure) { - if s == nil || s.deps == nil || s.deps.Config == nil { - return nil, nil - } - cfg := s.deps.Config.Runs.Spektacular - if !cfg.Recheck.Discovery.Enabled || len(cfg.Recheck.Discovery.Sources) == 0 { - return nil, nil - } - timeout := cfg.DiscoveryTimeout() - if timeout > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - } - var ghc *gh.Client - if s.deps.GHClient != nil { - ghc = s.deps.GHClient.GoGitHub() - } - collector := recheckDiscoveryCollector{cfg: cfg, gh: ghc, client: http.DefaultClient} - return collector.collect(ctx, base, since) -} - -func (c recheckDiscoveryCollector) collect(ctx context.Context, base Campaign, since time.Time) ([]knowledge.CampaignExternalEvidence, []knowledge.CampaignSourceFailure) { - maxTotal := c.cfg.DiscoveryMaxTotalItems() - out := []knowledge.CampaignExternalEvidence{} - failures := []knowledge.CampaignSourceFailure{} - for _, src := range c.cfg.Recheck.Discovery.Sources { - if len(out) >= maxTotal { - break - } - items, err := c.collectSource(ctx, src, base, since) - if err != nil { - failures = append(failures, knowledge.CampaignSourceFailure{Name: src.Name, Reason: discoveryFailureReason(err)}) - continue - } - remaining := maxTotal - len(out) - if len(items) > remaining { - items = items[:remaining] - } - out = append(out, items...) - } - return out, failures -} - -func (c recheckDiscoveryCollector) collectSource(ctx context.Context, src config.SpektacularRecheckDiscoverySource, base Campaign, since time.Time) ([]knowledge.CampaignExternalEvidence, error) { - switch strings.TrimSpace(src.Kind) { - case "upstream_release": - return c.githubReleases(ctx, src, since) - case "repo_activity": - return c.githubActivity(ctx, src, since) - case "standards_feed": - return c.feedItems(ctx, src, since) - case "landscape": - return c.landscape(ctx, src, base, since) - default: - return nil, fmt.Errorf("bad_kind") - } -} - -func (c recheckDiscoveryCollector) githubReleases(ctx context.Context, src config.SpektacularRecheckDiscoverySource, since time.Time) ([]knowledge.CampaignExternalEvidence, error) { - if c.gh == nil { - return nil, fmt.Errorf("github_unavailable") - } - owner, repo, ok := splitRepoSlug(src.URLOrRepo) - if !ok { - return nil, fmt.Errorf("bad_repo") - } - opt := &gh.ListOptions{PerPage: src.EffectiveMaxItems()} - releases, _, err := c.gh.Repositories.ListReleases(ctx, owner, repo, opt) - if err != nil { - return nil, err - } - out := []knowledge.CampaignExternalEvidence{} - for _, rel := range releases { - if rel.GetDraft() || (rel.GetPrerelease() && !src.AllowPrerelease) { - continue - } - published := rel.GetPublishedAt().Time - if !since.IsZero() && !published.After(since) { - continue - } - out = append(out, knowledge.CampaignExternalEvidence{ - Source: src.Name, - Kind: "upstream_release", - Title: rel.GetName(), - URL: rel.GetHTMLURL(), - PublishedAt: published, - Summary: truncateDiscoveryRunes(rel.GetBody(), externalSummaryMaxRunes), - }) - if len(out) >= src.EffectiveMaxItems() { - break - } - } - return out, nil -} - -func (c recheckDiscoveryCollector) githubActivity(ctx context.Context, src config.SpektacularRecheckDiscoverySource, since time.Time) ([]knowledge.CampaignExternalEvidence, error) { - releases, err := c.githubReleases(ctx, src, since) - if err != nil { - return nil, err - } - if c.gh == nil { - return nil, fmt.Errorf("github_unavailable") - } - owner, repo, ok := splitRepoSlug(src.URLOrRepo) - if !ok { - return nil, fmt.Errorf("bad_repo") - } - prs, _, err := c.gh.PullRequests.List(ctx, owner, repo, &gh.PullRequestListOptions{ - State: "closed", Sort: "updated", Direction: "desc", ListOptions: gh.ListOptions{PerPage: src.EffectiveMaxItems()}, - }) - if err != nil { - return nil, err - } - out := releases - for _, pr := range prs { - if pr.MergedAt == nil { - continue - } - merged := pr.GetMergedAt().Time - if !since.IsZero() && !merged.After(since) { - continue - } - out = append(out, knowledge.CampaignExternalEvidence{ - Source: src.Name, - Kind: "repo_activity", - Title: pr.GetTitle(), - URL: pr.GetHTMLURL(), - PublishedAt: merged, - Summary: truncateDiscoveryRunes(pr.GetBody(), externalSummaryMaxRunes), - }) - if len(out) >= src.EffectiveMaxItems() { - break - } - } - sortEvidence(out) - if len(out) > src.EffectiveMaxItems() { - out = out[:src.EffectiveMaxItems()] - } - return out, nil -} - -func (c recheckDiscoveryCollector) feedItems(ctx context.Context, src config.SpektacularRecheckDiscoverySource, since time.Time) ([]knowledge.CampaignExternalEvidence, error) { - u, err := url.Parse(strings.TrimSpace(src.URLOrRepo)) - if err != nil || u.Scheme == "" || u.Host == "" { - return nil, fmt.Errorf("bad_feed_url") - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - client := c.client - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { - return nil, fmt.Errorf("http_%d", resp.StatusCode) - } - body, err := io.ReadAll(io.LimitReader(resp.Body, discoveryFeedReadLimit)) - if err != nil { - return nil, err - } - items := parseFeedEvidence(src.Name, body) - out := []knowledge.CampaignExternalEvidence{} - for _, item := range items { - if !since.IsZero() && !item.PublishedAt.IsZero() && !item.PublishedAt.After(since) { - continue - } - out = append(out, item) - if len(out) >= src.EffectiveMaxItems() { - break - } - } - return out, nil -} - -func (c recheckDiscoveryCollector) landscape(ctx context.Context, src config.SpektacularRecheckDiscoverySource, _ Campaign, since time.Time) ([]knowledge.CampaignExternalEvidence, error) { - raw, err := readLandscape() - if err != nil { - return nil, err - } - repos := githubReposFromMarkdown(string(raw)) - out := []knowledge.CampaignExternalEvidence{} - for _, repo := range repos { - child := src - child.URLOrRepo = repo - child.Name = firstRunNonEmpty(src.Name, "landscape") + ":" + repo - items, err := c.githubReleases(ctx, child, since) - if err != nil { - continue - } - for _, item := range items { - item.Source = src.Name - item.Kind = "landscape" - out = append(out, item) - if len(out) >= src.EffectiveMaxItems() { - sortEvidence(out) - return out, nil - } - } - } - sortEvidence(out) - return out, nil -} - -func parseFeedEvidence(source string, body []byte) []knowledge.CampaignExternalEvidence { - type atomEntry struct { - Title string `xml:"title"` - Summary string `xml:"summary"` - Content string `xml:"content"` - Updated string `xml:"updated"` - Link []struct { - Href string `xml:"href,attr"` - } `xml:"link"` - } - type atomFeed struct { - Entries []atomEntry `xml:"entry"` - } - var atom atomFeed - if err := xml.Unmarshal(body, &atom); err == nil && len(atom.Entries) > 0 { - out := make([]knowledge.CampaignExternalEvidence, 0, len(atom.Entries)) - for _, e := range atom.Entries { - link := "" - if len(e.Link) > 0 { - link = e.Link[0].Href - } - out = append(out, knowledge.CampaignExternalEvidence{Source: source, Kind: "standards_feed", Title: strings.TrimSpace(e.Title), URL: link, PublishedAt: parseFeedTime(e.Updated), Summary: truncateDiscoveryRunes(firstRunNonEmpty(e.Summary, e.Content), externalSummaryMaxRunes)}) - } - return out - } - type rssItem struct { - Title string `xml:"title"` - Link string `xml:"link"` - Description string `xml:"description"` - PubDate string `xml:"pubDate"` - } - type rss struct { - Items []rssItem `xml:"channel>item"` - } - var r rss - _ = xml.Unmarshal(body, &r) - out := make([]knowledge.CampaignExternalEvidence, 0, len(r.Items)) - for _, item := range r.Items { - out = append(out, knowledge.CampaignExternalEvidence{Source: source, Kind: "standards_feed", Title: strings.TrimSpace(item.Title), URL: strings.TrimSpace(item.Link), PublishedAt: parseFeedTime(item.PubDate), Summary: truncateDiscoveryRunes(item.Description, externalSummaryMaxRunes)}) - } - return out -} - -func parseFeedTime(value string) time.Time { - value = strings.TrimSpace(value) - for _, layout := range []string{time.RFC3339, time.RFC3339Nano, time.RFC1123Z, time.RFC1123} { - if t, err := time.Parse(layout, value); err == nil { - return t - } - } - return time.Time{} -} - -func splitRepoSlug(value string) (string, string, bool) { - value = strings.TrimSpace(value) - if u, err := url.Parse(value); err == nil && u.Hostname() != "" { - parts := strings.Split(strings.Trim(u.Path, "/"), "/") - if len(parts) >= 2 { - return parts[0], strings.TrimSuffix(parts[1], ".git"), true - } - } - owner, repo, ok := strings.Cut(value, "/") - return strings.TrimSpace(owner), strings.TrimSpace(repo), ok && strings.TrimSpace(owner) != "" && strings.TrimSpace(repo) != "" -} - -func truncateDiscoveryRunes(value string, maxRunes int) string { - value = strings.TrimSpace(value) - if maxRunes <= 0 || utf8.RuneCountInString(value) <= maxRunes { - return value - } - runes := []rune(value) - return string(runes[:maxRunes]) -} - -func discoveryFailureReason(err error) string { - if err == nil { - return "" - } - if err == context.DeadlineExceeded { - return "timeout" - } - return strings.ReplaceAll(strings.TrimSpace(err.Error()), "\n", " ") -} - -func sortEvidence(items []knowledge.CampaignExternalEvidence) { - sort.SliceStable(items, func(i, j int) bool { - return items[i].PublishedAt.After(items[j].PublishedAt) - }) -} - -func readLandscape() ([]byte, error) { - for _, path := range []string{"docs/landscape.md", "src/docs/landscape.md"} { - if raw, err := os.ReadFile(path); err == nil { - return raw, nil - } - } - return nil, fmt.Errorf("landscape_unavailable") -} - -func githubReposFromMarkdown(markdown string) []string { - re := regexp.MustCompile(`https://github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)`) - seen := map[string]bool{} - out := []string{} - for _, match := range re.FindAllStringSubmatch(markdown, -1) { - repo := strings.TrimSuffix(match[1], ".git") - if !seen[repo] { - seen[repo] = true - out = append(out, repo) - } - } - return out -} diff --git a/src/pkg/dashboard/recheck_discovery_branches_test.go b/src/pkg/dashboard/recheck_discovery_branches_test.go deleted file mode 100644 index d2f43e6414..0000000000 --- a/src/pkg/dashboard/recheck_discovery_branches_test.go +++ /dev/null @@ -1,400 +0,0 @@ -package dashboard - -import ( - "context" - "errors" - "log/slog" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - gh "github.com/google/go-github/v72/github" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/github" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func TestCollectRecheckDiscoverySkipsWhenUnconfigured(t *testing.T) { - ctx := context.Background() - var nilServer *Server - if items, failures := nilServer.collectRecheckDiscovery(ctx, Campaign{}, time.Time{}); items != nil || failures != nil { - t.Fatalf("nil server = %#v / %#v, want nil, nil", items, failures) - } - noDeps := &Server{} - if items, failures := noDeps.collectRecheckDiscovery(ctx, Campaign{}, time.Time{}); items != nil || failures != nil { - t.Fatalf("nil deps = %#v / %#v, want nil, nil", items, failures) - } - noConfig := &Server{deps: &Dependencies{}} - if items, failures := noConfig.collectRecheckDiscovery(ctx, Campaign{}, time.Time{}); items != nil || failures != nil { - t.Fatalf("nil config = %#v / %#v, want nil, nil", items, failures) - } - - cfg := &config.Config{} - cfg.Runs.Spektacular.Recheck.Discovery.Enabled = true - disabledSources := &Server{deps: &Dependencies{Config: cfg}} - if items, failures := disabledSources.collectRecheckDiscovery(ctx, Campaign{}, time.Time{}); items != nil || failures != nil { - t.Fatalf("enabled without sources = %#v / %#v, want nil, nil", items, failures) - } - - cfg2 := &config.Config{} - cfg2.Runs.Spektacular.Recheck.Discovery.Sources = []config.SpektacularRecheckDiscoverySource{{Kind: "standards_feed", Name: "x", URLOrRepo: "https://example.com/feed"}} - disabledFlag := &Server{deps: &Dependencies{Config: cfg2}} - if items, failures := disabledFlag.collectRecheckDiscovery(ctx, Campaign{}, time.Time{}); items != nil || failures != nil { - t.Fatalf("sources without enabled = %#v / %#v, want nil, nil", items, failures) - } -} - -func TestCollectRecheckDiscoveryRunsConfiguredSources(t *testing.T) { - feed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`signalhttps://example.com/sMon, 05 Oct 2026 12:00:00 +0000d`)) - })) - defer feed.Close() - ghSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/repos/owner/repo/releases" { - t.Errorf("unexpected GitHub path %s", r.URL.Path) - http.NotFound(w, r) - return - } - _, _ = w.Write([]byte(`[{"name":"v9","html_url":"https://github.com/owner/repo/releases/tag/v9","published_at":"2026-10-06T00:00:00Z","body":"b"}]`)) - })) - defer ghSrv.Close() - - cfg := &config.Config{} - disc := &cfg.Runs.Spektacular.Recheck.Discovery - disc.Enabled = true - disc.Timeout = 5 * time.Second - disc.Sources = []config.SpektacularRecheckDiscoverySource{ - {Kind: "standards_feed", Name: "feed", URLOrRepo: feed.URL}, - {Kind: "upstream_release", Name: "up", URLOrRepo: "owner/repo"}, - {Kind: "unknown_kind", Name: "weird", URLOrRepo: "x"}, - } - s := &Server{deps: &Dependencies{ - Config: cfg, - GHClient: github.NewClientForTest(ghSrv.URL, "owner", []string{"repo"}, slog.Default()), - }} - items, failures := s.collectRecheckDiscovery(context.Background(), Campaign{}, time.Time{}) - if len(items) != 2 { - t.Fatalf("items = %#v, want feed item and release", items) - } - if items[0].Kind != "standards_feed" || items[1].Kind != "upstream_release" { - t.Fatalf("kinds = %q/%q, want source order preserved", items[0].Kind, items[1].Kind) - } - if len(failures) != 1 || failures[0].Name != "weird" || failures[0].Reason != "bad_kind" { - t.Fatalf("failures = %#v, want bad_kind for unknown source", failures) - } -} - -func TestRecheckDiscoveryCollectSourceDispatch(t *testing.T) { - c := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}} - ctx := context.Background() - cases := map[string]string{ - "upstream_release": "github_unavailable", - " repo_activity ": "github_unavailable", - "standards_feed": "bad_feed_url", - "": "bad_kind", - "nope": "bad_kind", - } - for kind, want := range cases { - _, err := c.collectSource(ctx, config.SpektacularRecheckDiscoverySource{Kind: kind, URLOrRepo: "owner/repo"}, Campaign{}, time.Time{}) - if err == nil || err.Error() != want { - t.Errorf("collectSource(%q) err = %v, want %s", kind, err, want) - } - } -} - -func TestRecheckDiscoveryCollectStopsAtMaxTotal(t *testing.T) { - calls := 0 - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - calls++ - _, _ = w.Write([]byte(`ab`)) - })) - defer srv.Close() - cfg := config.SpektacularConfig{} - cfg.Recheck.Discovery.MaxTotalItems = 1 - cfg.Recheck.Discovery.Sources = []config.SpektacularRecheckDiscoverySource{ - {Kind: "standards_feed", Name: "one", URLOrRepo: srv.URL}, - {Kind: "standards_feed", Name: "two", URLOrRepo: srv.URL}, - } - c := recheckDiscoveryCollector{cfg: cfg, client: srv.Client()} - items, failures := c.collect(context.Background(), Campaign{}, time.Time{}) - if len(items) != 1 || items[0].Title != "a" { - t.Fatalf("items = %#v, want first item only (per-source overflow trimmed)", items) - } - if len(failures) != 0 { - t.Fatalf("failures = %#v, want none", failures) - } - if calls != 1 { - t.Fatalf("feed fetched %d times, want 1: second source must be skipped once the total cap is reached", calls) - } -} - -func TestRecheckDiscoveryLandscapeReadsDocsAndCollectsReleases(t *testing.T) { - dir := t.TempDir() - t.Chdir(dir) - - if _, err := readLandscape(); err == nil || err.Error() != "landscape_unavailable" { - t.Fatalf("readLandscape without docs err = %v, want landscape_unavailable", err) - } - c := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}} - if _, err := c.landscape(context.Background(), config.SpektacularRecheckDiscoverySource{Kind: "landscape"}, Campaign{}, time.Time{}); err == nil { - t.Fatal("landscape without docs: want error") - } - - // The src/ fallback location is honoured when docs/landscape.md is absent. - if err := os.MkdirAll(filepath.Join(dir, "src", "docs"), 0o755); err != nil { - t.Fatal(err) - } - fallback := "see https://github.com/fb/only" - if err := os.WriteFile(filepath.Join(dir, "src", "docs", "landscape.md"), []byte(fallback), 0o644); err != nil { - t.Fatal(err) - } - raw, err := readLandscape() - if err != nil || string(raw) != fallback { - t.Fatalf("readLandscape fallback = %q, %v", raw, err) - } - - if err := os.MkdirAll(filepath.Join(dir, "docs"), 0o755); err != nil { - t.Fatal(err) - } - markdown := "- https://github.com/alpha/one.git\n- https://github.com/beta/two\n- https://github.com/gamma/missing\n" - if err := os.WriteFile(filepath.Join(dir, "docs", "landscape.md"), []byte(markdown), 0o644); err != nil { - t.Fatal(err) - } - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/repos/alpha/one/releases": - _, _ = w.Write([]byte(`[{"name":"one-old","html_url":"https://github.com/alpha/one/releases/tag/v1","published_at":"2026-10-01T00:00:00Z"}]`)) - case "/repos/beta/two/releases": - _, _ = w.Write([]byte(`[{"name":"two-new","html_url":"https://github.com/beta/two/releases/tag/v2","published_at":"2026-10-07T00:00:00Z"}]`)) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - client := gh.NewClient(srv.Client()) - client.BaseURL = mustURL(t, srv.URL+"/") - c = recheckDiscoveryCollector{cfg: config.SpektacularConfig{}, gh: client} - - items, err := c.landscape(context.Background(), config.SpektacularRecheckDiscoverySource{Kind: "landscape", Name: "cncf"}, Campaign{}, time.Time{}) - if err != nil { - t.Fatalf("landscape: %v", err) - } - if len(items) != 2 { - t.Fatalf("items = %#v, want one release per reachable repo (missing repo skipped)", items) - } - if items[0].Title != "two-new" || items[1].Title != "one-old" { - t.Fatalf("order = %q,%q, want newest first", items[0].Title, items[1].Title) - } - for _, item := range items { - if item.Source != "cncf" || item.Kind != "landscape" { - t.Fatalf("item = %#v, want source/kind rewritten to the landscape source", item) - } - } - - // Per-source cap returns early with the collected subset sorted. - capped, err := c.landscape(context.Background(), config.SpektacularRecheckDiscoverySource{Kind: "landscape", MaxItems: 1}, Campaign{}, time.Time{}) - if err != nil || len(capped) != 1 || capped[0].Title != "one-old" { - t.Fatalf("capped = %#v, %v; want first repo's release only", capped, err) - } - if capped[0].Kind != "landscape" { - t.Fatalf("capped item = %#v, want landscape kind", capped[0]) - } -} - -func TestRecheckDiscoveryGitHubErrorPaths(t *testing.T) { - ctx := context.Background() - noGH := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}} - if _, err := noGH.githubReleases(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: "owner/repo"}, time.Time{}); err == nil || err.Error() != "github_unavailable" { - t.Fatalf("githubReleases without client err = %v", err) - } - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/repos/owner/broken/releases": - http.Error(w, "boom", http.StatusInternalServerError) - case "/repos/owner/repo/releases": - _, _ = w.Write([]byte(`[{"name":"draft","draft":true,"published_at":"2026-10-07T00:00:00Z"}]`)) - case "/repos/owner/repo/pulls": - _, _ = w.Write([]byte(`[ - {"title":"open pr","html_url":"https://github.com/owner/repo/pull/1"}, - {"title":"old merge","html_url":"https://github.com/owner/repo/pull/2","merged_at":"2026-01-01T00:00:00Z"}, - {"title":"new merge","html_url":"https://github.com/owner/repo/pull/3","merged_at":"2026-10-06T00:00:00Z"} - ]`)) - case "/repos/owner/nopulls/releases": - _, _ = w.Write([]byte(`[]`)) - case "/repos/owner/nopulls/pulls": - http.Error(w, "boom", http.StatusBadGateway) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - client := gh.NewClient(srv.Client()) - client.BaseURL = mustURL(t, srv.URL+"/") - c := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}, gh: client} - - if _, err := c.githubReleases(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: "just-a-name"}, time.Time{}); err == nil || err.Error() != "bad_repo" { - t.Fatalf("bad slug err = %v, want bad_repo", err) - } - if _, err := c.githubReleases(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: "owner/broken"}, time.Time{}); err == nil { - t.Fatal("API 500: want error") - } - if _, err := c.githubActivity(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: "owner/broken"}, time.Time{}); err == nil { - t.Fatal("activity with failing releases: want error") - } - if _, err := c.githubActivity(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: "owner/nopulls"}, time.Time{}); err == nil { - t.Fatal("activity with failing pulls: want error") - } - - items, err := c.githubActivity(ctx, config.SpektacularRecheckDiscoverySource{Name: "act", URLOrRepo: "https://github.com/owner/repo.git"}, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil { - t.Fatalf("githubActivity: %v", err) - } - if len(items) != 1 || items[0].Title != "new merge" { - t.Fatalf("items = %#v, want only the merged-after-since PR (draft release, open and old PRs dropped)", items) - } -} - -func TestRecheckDiscoveryFeedItemsErrorPaths(t *testing.T) { - ctx := context.Background() - c := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}} - for _, bad := range []string{"", "not a url", "/relative/only", "mailto:x"} { - if _, err := c.feedItems(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: bad}, time.Time{}); err == nil || err.Error() != "bad_feed_url" { - t.Errorf("feedItems(%q) err = %v, want bad_feed_url", bad, err) - } - } - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/gone" { - w.WriteHeader(http.StatusGone) - return - } - _, _ = w.Write([]byte(`undated`)) - })) - defer srv.Close() - c.client = srv.Client() - if _, err := c.feedItems(ctx, config.SpektacularRecheckDiscoverySource{URLOrRepo: srv.URL + "/gone"}, time.Time{}); err == nil || err.Error() != "http_410" { - t.Fatalf("non-2xx err = %v, want http_410", err) - } - - // Entries without a timestamp are kept even when a since bound is set. - items, err := c.feedItems(ctx, config.SpektacularRecheckDiscoverySource{Name: "f", URLOrRepo: srv.URL + "/ok"}, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil || len(items) != 1 || items[0].Title != "undated" || !items[0].PublishedAt.IsZero() { - t.Fatalf("undated items = %#v, %v", items, err) - } - - cancelled, cancel := context.WithCancel(ctx) - cancel() - if _, err := c.feedItems(cancelled, config.SpektacularRecheckDiscoverySource{URLOrRepo: srv.URL + "/ok"}, time.Time{}); err == nil { - t.Fatal("cancelled context: want transport error") - } -} - -func TestParseFeedEvidenceAtomPrefersSummaryThenContent(t *testing.T) { - items := parseFeedEvidence("src", []byte(` - A 2026-10-05T12:00:00Zcontent only -Bsumcontent -`)) - if len(items) != 2 { - t.Fatalf("items = %#v", items) - } - if items[0].Title != "A" || items[0].Summary != "content only" || items[0].URL != "" || items[0].PublishedAt.IsZero() { - t.Fatalf("entry A = %#v", items[0]) - } - if items[1].Summary != "sum" || items[1].URL != "https://example.com/b" || !items[1].PublishedAt.IsZero() { - t.Fatalf("entry B = %#v", items[1]) - } - if got := parseFeedEvidence("src", []byte(`not xml at all`)); len(got) != 0 { - t.Fatalf("garbage body = %#v, want empty", got) - } - if got := parseFeedEvidence("src", []byte(``)); len(got) != 0 { - t.Fatalf("empty atom = %#v, want empty", got) - } -} - -func TestParseFeedTimeLayouts(t *testing.T) { - want := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC) - for _, in := range []string{ - " 2026-10-05T12:00:00Z ", - "2026-10-05T12:00:00.000Z", - "Mon, 05 Oct 2026 12:00:00 +0000", - "Mon, 05 Oct 2026 12:00:00 UTC", - } { - if got := parseFeedTime(in); !got.Equal(want) { - t.Errorf("parseFeedTime(%q) = %v, want %v", in, got, want) - } - } - for _, in := range []string{"", "yesterday", "2026-10-05"} { - if got := parseFeedTime(in); !got.IsZero() { - t.Errorf("parseFeedTime(%q) = %v, want zero", in, got) - } - } -} - -func TestSplitRepoSlugForms(t *testing.T) { - cases := []struct { - in string - owner, repo string - ok bool - }{ - {"owner/repo", "owner", "repo", true}, - {" owner / repo ", "owner", "repo", true}, - {"https://github.com/owner/repo", "owner", "repo", true}, - {"https://github.com/owner/repo.git", "owner", "repo", true}, - {"https://github.com/owner/repo/releases/tag/v1", "owner", "repo", true}, - {"owner", "", "", false}, - {"/repo", "", "", false}, - {"owner/", "", "", false}, - {"", "", "", false}, - } - for _, tc := range cases { - owner, repo, ok := splitRepoSlug(tc.in) - if ok != tc.ok || (ok && (owner != tc.owner || repo != tc.repo)) { - t.Errorf("splitRepoSlug(%q) = %q,%q,%v; want %q,%q,%v", tc.in, owner, repo, ok, tc.owner, tc.repo, tc.ok) - } - } -} - -func TestTruncateDiscoveryRunes(t *testing.T) { - if got := truncateDiscoveryRunes(" héllo wörld ", 0); got != "héllo wörld" { - t.Fatalf("no cap = %q", got) - } - if got := truncateDiscoveryRunes("héllo", 10); got != "héllo" { - t.Fatalf("under cap = %q", got) - } - if got := truncateDiscoveryRunes("héllo wörld", 5); got != "héllo" { - t.Fatalf("rune cap = %q, want whole runes not bytes", got) - } -} - -func TestDiscoveryFailureReason(t *testing.T) { - if got := discoveryFailureReason(nil); got != "" { - t.Fatalf("nil = %q", got) - } - if got := discoveryFailureReason(context.DeadlineExceeded); got != "timeout" { - t.Fatalf("deadline = %q", got) - } - if got := discoveryFailureReason(errors.New(" multi\nline\n")); got != "multi line" { - t.Fatalf("multiline = %q", got) - } -} - -func TestSortEvidenceNewestFirstStable(t *testing.T) { - ts := func(d int) time.Time { return time.Date(2026, 10, d, 0, 0, 0, 0, time.UTC) } - items := []knowledge.CampaignExternalEvidence{ - {Title: "a", PublishedAt: ts(1)}, - {Title: "b", PublishedAt: ts(3)}, - {Title: "c", PublishedAt: ts(3)}, - {Title: "d"}, - } - sortEvidence(items) - got := []string{items[0].Title, items[1].Title, items[2].Title, items[3].Title} - if strings.Join(got, "") != "bcad" { - t.Fatalf("order = %v, want b c a d (newest first, equal timestamps stable, zero last)", got) - } -} diff --git a/src/pkg/dashboard/recheck_discovery_test.go b/src/pkg/dashboard/recheck_discovery_test.go deleted file mode 100644 index fe27526682..0000000000 --- a/src/pkg/dashboard/recheck_discovery_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package dashboard - -import ( - "context" - "errors" - "io" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - "time" - - gh "github.com/google/go-github/v72/github" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func TestRecheckDiscoveryFeedFiltersSinceAndCaps(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/atom+xml") - _, _ = w.Write([]byte(` -old2026-01-01T00:00:00Zold summary -new one2026-10-05T12:00:00Znew summary -new two2026-10-05T13:00:00Znew summary -`)) - })) - defer srv.Close() - - collector := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}, client: srv.Client()} - items, err := collector.feedItems(context.Background(), config.SpektacularRecheckDiscoverySource{ - Kind: "standards_feed", Name: "standards", URLOrRepo: srv.URL, MaxItems: 1, - }, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil { - t.Fatalf("feedItems: %v", err) - } - if len(items) != 1 || items[0].Title != "new one" || items[0].Kind != "standards_feed" { - t.Fatalf("items = %#v, want first new item only", items) - } -} - -func TestRecheckDiscoveryCollectRecordsFailureNotFatal(t *testing.T) { - cfg := config.SpektacularConfig{} - cfg.Recheck.Discovery.MaxTotalItems = 1 - cfg.Recheck.Discovery.Sources = []config.SpektacularRecheckDiscoverySource{ - {Kind: "standards_feed", Name: "bad", URLOrRepo: "http://127.0.0.1:1/nope"}, - {Kind: "standards_feed", Name: "good", URLOrRepo: "https://example.com/feed.xml"}, - } - - collector := recheckDiscoveryCollector{ - cfg: cfg, - client: recheckRoundTripFunc(func(req *http.Request) (*http.Response, error) { - if req.URL.Host == "127.0.0.1:1" { - return nil, errors.New("dial blocked") - } - return &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(strings.NewReader(`okhttps://example.com/okMon, 05 Oct 2026 12:00:00 +0000ok`)), - Header: make(http.Header), - }, nil - }).Client(), - } - items, failures := collector.collect(context.Background(), Campaign{}, time.Time{}) - if len(items) != 1 || items[0].Title != "ok" { - t.Fatalf("items = %#v, want successful source evidence", items) - } - if len(failures) != 1 || failures[0].Name != "bad" { - t.Fatalf("failures = %#v, want bad source recorded", failures) - } -} - -func TestRecheckDiscoveryGitHubReleasesFiltersSincePrereleaseAndCaps(t *testing.T) { - const releasesPath = "/repos/owner/repo/releases" - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != releasesPath { - t.Fatalf("path = %s, want %s", r.URL.Path, releasesPath) - } - _, _ = w.Write([]byte(`[ - {"name":"old","html_url":"https://github.com/owner/repo/releases/tag/v1","published_at":"2026-01-01T00:00:00Z","body":"old"}, - {"name":"pre","html_url":"https://github.com/owner/repo/releases/tag/v2-rc1","published_at":"2026-10-05T11:00:00Z","prerelease":true,"body":"pre"}, - {"name":"new","html_url":"https://github.com/owner/repo/releases/tag/v2","published_at":"2026-10-05T12:00:00Z","body":"new"} - ]`)) - })) - defer srv.Close() - client := gh.NewClient(srv.Client()) - client.BaseURL = mustURL(t, srv.URL+"/") - collector := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}, gh: client} - items, err := collector.githubReleases(context.Background(), config.SpektacularRecheckDiscoverySource{ - Kind: "upstream_release", Name: "up", URLOrRepo: "owner/repo", MaxItems: 1, - }, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil { - t.Fatalf("githubReleases: %v", err) - } - if len(items) != 1 || items[0].Title != "new" || items[0].Kind != "upstream_release" { - t.Fatalf("items = %#v, want only non-prerelease new release", items) - } -} - -func TestRecheckDiscoveryRepoActivityIncludesMergedPR(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/repos/owner/repo/releases": - _, _ = w.Write([]byte(`[]`)) - case "/repos/owner/repo/pulls": - _, _ = w.Write([]byte(`[{"title":"merged feature","html_url":"https://github.com/owner/repo/pull/7","merged_at":"2026-10-05T12:00:00Z","body":"body"}]`)) - default: - t.Fatalf("unexpected path %s", r.URL.Path) - } - })) - defer srv.Close() - client := gh.NewClient(srv.Client()) - client.BaseURL = mustURL(t, srv.URL+"/") - collector := recheckDiscoveryCollector{cfg: config.SpektacularConfig{}, gh: client} - items, err := collector.githubActivity(context.Background(), config.SpektacularRecheckDiscoverySource{ - Kind: "repo_activity", Name: "activity", URLOrRepo: "owner/repo", - }, time.Date(2026, 10, 5, 0, 0, 0, 0, time.UTC)) - if err != nil { - t.Fatalf("githubActivity: %v", err) - } - if len(items) != 1 || items[0].Title != "merged feature" || items[0].Kind != "repo_activity" { - t.Fatalf("items = %#v, want merged PR activity", items) - } -} - -func TestRecheckDiscoveryLandscapeExtractsGitHubRepos(t *testing.T) { - repos := githubReposFromMarkdown(`[one](https://github.com/owner/repo) and [dup](https://github.com/owner/repo) plus https://github.com/other/project/releases`) - if len(repos) != 2 || repos[0] != "owner/repo" || repos[1] != "other/project" { - t.Fatalf("repos = %#v, want stable unique GitHub repos", repos) - } -} - -func TestRecheckSpecPromptTitleIncludesExternalEvidence(t *testing.T) { - drift := campaignDriftFromArchive(knowledge.InceptionCampaignArchive{Drift: &knowledge.CampaignDrift{ - ExternalCount: 1, - External: []knowledge.CampaignExternalEvidence{{ - Source: "source", - Kind: "standards_feed", - Title: "signal", - URL: "https://example.com/signal", - Summary: "summary", - }}, - }}) - if drift == nil || drift.ExternalCount != 1 || !strings.Contains(drift.External[0].Summary, "summary") { - t.Fatalf("drift = %#v, want external evidence shape", drift) - } -} - -type recheckRoundTripFunc func(*http.Request) (*http.Response, error) - -func (f recheckRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } - -func (f recheckRoundTripFunc) Client() *http.Client { return &http.Client{Transport: f} } - -func mustURL(t *testing.T, value string) *url.URL { - t.Helper() - u, err := url.Parse(value) - if err != nil { - t.Fatalf("url.Parse(%q): %v", value, err) - } - return u -} diff --git a/src/pkg/dashboard/runs_settings_parity_test.go b/src/pkg/dashboard/runs_settings_parity_test.go index 964b7d55a4..4836aadce9 100644 --- a/src/pkg/dashboard/runs_settings_parity_test.go +++ b/src/pkg/dashboard/runs_settings_parity_test.go @@ -30,12 +30,6 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { {"runsTriagePriorArtMaxParksPerCycle": -1}, {"runsTriagePriorArtBotCloseTtl": "-1h"}, {"runsTriagePriorArtBotCloseTtl": "soon"}, - {"spektacularRecheckDefaultInterval": "weekly"}, - {"spektacularRecheckMaxDeltaTasks": -1}, - {"spektacularRecheckDiscoveryProxy": "http://user:pw@relay:18443"}, - {"spektacularRecheckDiscoveryProxy": "socks5://relay:1080"}, - {"spektacularDiscoveryTimeout": "-1s"}, - {"spektacularDiscoveryMaxTotalItems": -1}, {"extFlueEndpoint": "ftp://flue.example"}, {"extFlueEndpoint": "http://user:secret@127.0.0.1:8585"}, {"extFlueWorkflowVersion": "has space"}, @@ -71,14 +65,6 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { "runsTriagePriorArtMaxParksPerCycle": 2, "runsTriagePriorArtBotCloseTtl": "48h", - "spektacularRecheckEnabled": true, - "spektacularRecheckDefaultInterval": "72h", - "spektacularRecheckMaxDeltaTasks": 25, - "spektacularRecheckDiscoveryProxy": "http://relay:18443", - "spektacularDiscoveryEnabled": true, - "spektacularDiscoveryTimeout": "45s", - "spektacularDiscoveryMaxTotalItems": 40, - "extFlueEndpoint": "http://127.0.0.1:8585/", "extFlueWorkflowVersion": "flue-fixture/1.0.0", "extOmpWorkflowVersion": "omp/2", @@ -108,11 +94,6 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { if pa := r.Triage.PriorArt; !slices.Equal(pa.Kinds, []string{"rfc", "epic"}) || pa.MaxFindings != 3 || pa.MaxParksPerCycle != 2 || pa.BotCloseTTL != 48*time.Hour { t.Fatalf("prior-art gate not applied: %+v", pa) } - rc := r.Spektacular.Recheck - if !rc.Enabled || rc.DefaultInterval != 72*time.Hour || rc.MaxDeltaTasks != 25 || rc.DiscoveryProxy != "http://relay:18443" || - !rc.Discovery.Enabled || rc.Discovery.Timeout != 45*time.Second || rc.Discovery.MaxTotalItems != 40 { - t.Fatalf("recheck not applied: %+v", rc) - } if r.External.Flue.Endpoint != "http://127.0.0.1:8585" || r.External.Flue.WorkflowVersion != "flue-fixture/1.0.0" || r.External.OMP.WorkflowVersion != "omp/2" { t.Fatalf("flue/omp not applied: %+v", r.External) } @@ -124,17 +105,14 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { // A partial PUT changes only what it carries; empty values reset to the // default. if rec := doPut(s, opsFeaturesPath, map[string]any{ - "runsWaitSeverity": "", - "spektacularRecheckDefaultInterval": "", - "spektacularRecheckMaxDeltaTasks": 0, - "extFlueEndpoint": "", - "extVibeKanbanStateDir": "", + "runsWaitSeverity": "", + "extFlueEndpoint": "", + "extVibeKanbanStateDir": "", }); rec.Code != http.StatusOK { t.Fatalf("partial PUT: %d — %s", rec.Code, rec.Body.String()) } r = s.deps.Config.Runs - if r.WaitSeverity != "" || r.WaitTimeoutSeconds != 7200 || r.Spektacular.Recheck.DefaultInterval != 0 || - r.Spektacular.Recheck.MaxDeltaTasks != 0 || r.Spektacular.Recheck.Discovery.MaxTotalItems != 40 || + if r.WaitSeverity != "" || r.WaitTimeoutSeconds != 7200 || r.External.Flue.Endpoint != "" || r.External.Flue.WorkflowVersion != "flue-fixture/1.0.0" || r.External.VibeKanban.StateDir != "" || r.External.VibeKanban.ProjectID != "proj-123" { t.Fatalf("partial PUT changed unrelated keys or did not reset: %+v", r) @@ -153,9 +131,6 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { TriageClarify bool `json:"runsTriageClarifyComment"` ClarityGateEnabled bool `json:"runsTriageClarityGateEnabled"` ClarityThreshold int `json:"runsTriageClarityGateThreshold"` - RecheckInterval string `json:"spektacularRecheckDefaultInterval"` - DiscoveryTimeout string `json:"spektacularDiscoveryTimeout"` - DiscoveryProxy string `json:"spektacularRecheckDiscoveryProxy"` FlueWorkflowVersion string `json:"extFlueWorkflowVersion"` VKEnabled bool `json:"extVibeKanbanEnabled"` VKMode string `json:"extVibeKanbanMode"` @@ -175,34 +150,23 @@ func TestGovernorFeaturesRunsSettingsRoundTrip(t *testing.T) { if !f.ClarityGateEnabled || f.ClarityThreshold != 70 || f.Defaults["runsTriageClarityGateThreshold"] != float64(config.DefaultClarityGateThreshold) { t.Fatalf("clarity gate payload = %+v", f) } - if f.RecheckInterval != "" || f.DiscoveryTimeout != "45s" || f.DiscoveryProxy != "http://relay:18443" || f.FlueWorkflowVersion != "flue-fixture/1.0.0" { - t.Fatalf("recheck/flue payload = %+v", f) + if f.FlueWorkflowVersion != "flue-fixture/1.0.0" { + t.Fatalf("flue payload = %+v", f) + } + for _, retired := range []string{"spektacularRecheckEnabled", "spektacularRecheckDefaultInterval", "spektacularDiscoveryEnabled"} { + if strings.Contains(rec.Body.String(), `"`+retired+`"`) { + t.Fatalf("retired recheck key %q still in the governor payload", retired) + } } if !f.VKEnabled || f.VKMode != config.FlueBindingModeReportOnly || f.VKModeSetting != config.FlueBindingModeReportOnly || f.VKMcpCommand != "npx vibe-kanban --mcp" || f.VKLinked == nil { t.Fatalf("vibe-kanban payload = %+v", f) } - if f.Defaults["runsWaitSeverity"] != config.DefaultRunsWaitSeverity || - f.Defaults["spektacularRecheckDefaultInterval"] != config.DefaultSpektacularRecheckInterval.String() { + if f.Defaults["runsWaitSeverity"] != config.DefaultRunsWaitSeverity { t.Fatalf("runsDefaults = %v", f.Defaults) } } -// With exact recheck sources configured the discovery proxy is mandatory, so -// the dialog cannot clear it. -func TestGovernorFeaturesRunsDiscoveryProxyRequiredWithSources(t *testing.T) { - s := covApiServer(t) - s.deps.Config.Runs.Spektacular.Recheck.DiscoveryProxy = "http://relay:18443" - s.deps.Config.Runs.Spektacular.Recheck.EgressAllowlist = []string{"api.github.com"} - s.deps.Config.Runs.Spektacular.Recheck.Sources = []config.SpektacularDiscoverySource{{Name: "release", Kind: "release", URL: "https://api.github.com/repos/example/x/releases/latest"}} - if rec := doPut(s, opsFeaturesPath, map[string]any{"spektacularRecheckDiscoveryProxy": ""}); rec.Code != http.StatusBadRequest { - t.Fatalf("clearing the proxy with sources configured: expected 400, got %d", rec.Code) - } - if s.deps.Config.Runs.Spektacular.Recheck.DiscoveryProxy != "http://relay:18443" { - t.Fatal("rejected PUT cleared the proxy") - } -} - // Every newly exposed runs.* key is rendered on the Features tab with its // YAML-key hint and a control bound to the Features dirty map. func TestRunsSettingsRenderEveryKey(t *testing.T) { @@ -223,13 +187,6 @@ func TestRunsSettingsRenderEveryKey(t *testing.T) { {"runs.triage.prior_art.max_parks_per_cycle", `data-arg0="features" data-arg1="runsTriagePriorArtMaxParksPerCycle" data-arg-types="s,s,N"`}, {"runs.triage.prior_art.bot_close_ttl", `data-arg0="features" data-arg1="runsTriagePriorArtBotCloseTtl" data-arg-types="s,s,w"`}, {"runs.spektacular.binary", `data-arg0="features" data-arg1="spektacularBinary" data-arg-types="s,s,w"`}, - {"runs.spektacular.recheck.enabled", `data-section="features" data-key="spektacularRecheckEnabled"`}, - {"runs.spektacular.recheck.default_interval", `data-arg0="features" data-arg1="spektacularRecheckDefaultInterval" data-arg-types="s,s,w"`}, - {"runs.spektacular.recheck.max_delta_tasks", `data-arg0="features" data-arg1="spektacularRecheckMaxDeltaTasks" data-arg-types="s,s,N"`}, - {"runs.spektacular.recheck.discovery_proxy", `data-arg0="features" data-arg1="spektacularRecheckDiscoveryProxy" data-arg-types="s,s,w"`}, - {"runs.spektacular.recheck.discovery.enabled", `data-section="features" data-key="spektacularDiscoveryEnabled"`}, - {"runs.spektacular.recheck.discovery.timeout", `data-arg0="features" data-arg1="spektacularDiscoveryTimeout" data-arg-types="s,s,w"`}, - {"runs.spektacular.recheck.discovery.max_total_items", `data-arg0="features" data-arg1="spektacularDiscoveryMaxTotalItems" data-arg-types="s,s,N"`}, {"runs.external.flue.mode", `data-arg0="features" data-arg1="extFlueMode" data-arg-types="s,s,v"`}, {"runs.external.flue.endpoint", `data-arg0="features" data-arg1="extFlueEndpoint" data-arg-types="s,s,w"`}, {"runs.external.flue.workflow_version", `data-arg0="features" data-arg1="extFlueWorkflowVersion" data-arg-types="s,s,w"`}, diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 9ee6417fdb..bdb4da9418 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -548,15 +548,6 @@ runs.external.claude_managed_agents.network_policy # prototype hosted backend; y runs.external.claude_managed_agents.state_dir # prototype hosted backend; yaml-only (#14214) runs.external.claude_managed_agents.toolset_version # prototype hosted backend; yaml-only (#14214) runs.external.claude_managed_agents.workflow_version # prototype hosted backend; yaml-only (#14214) -runs.spektacular.recheck.discovery.sources[].allow_prerelease # TODO #11854 -runs.spektacular.recheck.discovery.sources[].kind # TODO #11854 -runs.spektacular.recheck.discovery.sources[].max_items # TODO #11854 -runs.spektacular.recheck.discovery.sources[].name # TODO #11854 -runs.spektacular.recheck.discovery.sources[].url_or_repo # TODO #11854 -runs.spektacular.recheck.egress_allowlist[] # TODO #11854 -runs.spektacular.recheck.sources[].kind # TODO #11854 -runs.spektacular.recheck.sources[].name # TODO #11854 -runs.spektacular.recheck.sources[].url # TODO #11854 runs.triage.fix_labels[] # TODO #11854 runs.triage.spec_labels[] # TODO #11854 forgestate.drift_threshold # yaml-only until readers migrate (#13373) diff --git a/src/pkg/dashboard/stage_leases.go b/src/pkg/dashboard/stage_leases.go index e10d01955f..b8fb957723 100644 --- a/src/pkg/dashboard/stage_leases.go +++ b/src/pkg/dashboard/stage_leases.go @@ -496,9 +496,6 @@ func (s *Server) ImportRunPlan(runKey, repo, taskList string, engineName ...stri return errors.New("planning engine name is required") } } - if handled, err := s.importRecheckDelta(runKey, repo, taskList, source); handled { - return err - } return s.importRunPlanDirect(runKey, repo, taskList, source) } @@ -884,41 +881,11 @@ func (a *runStageAccessor) PendingRunStages(_ context.Context) ([]worksource.Run if l.stage == StageImplement && l.identity != runFanoutIdentity && s.runPlanHasWaves(l.runKey) { continue } - title := l.runKey - if l.stage == StageSpec { - title = s.recheckSpecStageTitle(l.runKey, title) - } - out = append(out, worksource.RunStage{RunKey: l.runKey, Stage: l.stage, Repo: l.repo, Title: title}) + out = append(out, worksource.RunStage{RunKey: l.runKey, Stage: l.stage, Repo: l.repo, Title: l.runKey}) } return out, nil } -func (s *Server) recheckSpecStageTitle(runKey, fallback string) string { - if s == nil || s.deps == nil || s.deps.Inception == nil { - return fallback - } - archive, err := s.deps.Inception.LoadCampaignArchive(runKey) - if err != nil || archive == nil || archive.Drift == nil || len(archive.Drift.External) == 0 { - return fallback - } - var b strings.Builder - b.WriteString(fallback) - b.WriteString(" — recheck external evidence for spec input: ") - for i, ev := range archive.Drift.External { - if i > 0 { - b.WriteString("; ") - } - b.WriteString(ev.Source) - b.WriteString(": ") - b.WriteString(ev.Title) - if ev.URL != "" { - b.WriteString(" ") - b.WriteString(ev.URL) - } - } - return b.String() -} - // StageHasLiveLease reports whether a connection is currently working that // exact run stage, in which case it must not be offered again. func (a *runStageAccessor) StageHasLiveLease(_ context.Context, runKey, stage string) (bool, error) { diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 82a2912536..5b352b83f2 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -1206,25 +1206,7 @@
-
Spek recheck ${settingHelpMark('spektacular', '', 'Spek recheck', `Continuous convergence: re-runs the spec for opted-in campaigns on a cadence and imports changed or new plan tasks. The source lists (runs.spektacular.recheck.sources, runs.spektacular.recheck.discovery.sources) and runs.spektacular.recheck.egress_allowlist are yaml-only.`)}
-
-
- Recheck cadence enabled ${yamlHint('runs.spektacular.recheck.enabled')} ${settingHelpMark('spektacular', '', 'Recheck cadence enabled', `Lets the scheduler start rechecks on cadence. A manual recheck also needs this unless it is forced.`)} -
-
-
-
-
-
-
-
- Outward discovery ${yamlHint('runs.spektacular.recheck.discovery.enabled')} ${settingHelpMark('spektacular', '', 'Outward discovery', `Gathers bounded evidence from the declared discovery sources before a recheck spec. Does nothing without sources.`)} -
-
-
-
-
-
Checkpoint, triage and recheck settings are applied live; no restart is needed.
+
Checkpoint and triage settings are applied live; no restart is needed.
Integration orchestration
diff --git a/src/pkg/dashboard/static-src/js/config-state.js b/src/pkg/dashboard/static-src/js/config-state.js index cc04ecc4d7..fdb3bcd78d 100644 --- a/src/pkg/dashboard/static-src/js/config-state.js +++ b/src/pkg/dashboard/static-src/js/config-state.js @@ -125,7 +125,7 @@ { tab: 'Features', section: 'Agents & tooling', label: 'Tool approval inbox path', key: 'tool_approval.inbox_path', text: 'tool approval inbox pending approvals path tool_approval.inbox_path' }, { tab: 'Features', section: 'Auto-merge', label: 'Merge train', key: 'auto_merge.merge_train.enabled', text: 'merge train conflict overlap rebase attempts stall warning after seconds governor.merge_train_stall_warn_s auto_merge.merge_train.max_rebase_attempts' }, { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled' }, - { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints, triage and Spek recheck', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular recheck cadence interval delta tasks discovery proxy timeout runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary runs.spektacular.recheck.enabled runs.spektacular.recheck.default_interval runs.spektacular.recheck.max_delta_tasks runs.spektacular.recheck.discovery_proxy runs.spektacular.recheck.discovery.enabled runs.spektacular.recheck.discovery.timeout runs.spektacular.recheck.discovery.max_total_items' }, + { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints and triage', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary' }, { tab: 'Features', section: 'Experimental', label: 'External execution: Flue, OMP and vibe-kanban', key: 'runs.external.flue.mode', text: 'external execution flue omp vibe kanban workbench report-only shadow endpoint workflow version project state dir mcp command runs.external.flue.mode runs.external.flue.endpoint runs.external.flue.workflow_version runs.external.omp.mode runs.external.omp.workflow_version runs.external.vibe_kanban.enabled runs.external.vibe_kanban.mode runs.external.vibe_kanban.project_id runs.external.vibe_kanban.state_dir runs.external.vibe_kanban.workflow_version runs.external.vibe_kanban.mcp_command' }, { tab: 'Features', section: 'Integrations & observability', label: 'OpenTelemetry export', key: 'otel.enabled', text: 'otel opentelemetry export endpoint headers insecure sample ratio service name otel.enabled otel.endpoint otel.headers. otel.insecure otel.sample_ratio otel.service_name' }, { tab: 'Thresholds', section: 'Thresholds', label: 'Restart thresholds', key: 'governor.modes', text: 'restart thresholds quiet busy surge pressure backoff governor.modes.quiet.threshold governor.modes.busy.threshold governor.modes.surge.threshold' }, diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 9cd769f2b8..4f6acd070b 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -58050,7 +58050,7 @@

Configure LiteLLM

{ tab: 'Features', section: 'Agents & tooling', label: 'Tool approval inbox path', key: 'tool_approval.inbox_path', text: 'tool approval inbox pending approvals path tool_approval.inbox_path' }, { tab: 'Features', section: 'Auto-merge', label: 'Merge train', key: 'auto_merge.merge_train.enabled', text: 'merge train conflict overlap rebase attempts stall warning after seconds governor.merge_train_stall_warn_s auto_merge.merge_train.max_rebase_attempts' }, { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled' }, - { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints, triage and Spek recheck', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular recheck cadence interval delta tasks discovery proxy timeout runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary runs.spektacular.recheck.enabled runs.spektacular.recheck.default_interval runs.spektacular.recheck.max_delta_tasks runs.spektacular.recheck.discovery_proxy runs.spektacular.recheck.discovery.enabled runs.spektacular.recheck.discovery.timeout runs.spektacular.recheck.discovery.max_total_items' }, + { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints and triage', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary' }, { tab: 'Features', section: 'Experimental', label: 'External execution: Flue, OMP and vibe-kanban', key: 'runs.external.flue.mode', text: 'external execution flue omp vibe kanban workbench report-only shadow endpoint workflow version project state dir mcp command runs.external.flue.mode runs.external.flue.endpoint runs.external.flue.workflow_version runs.external.omp.mode runs.external.omp.workflow_version runs.external.vibe_kanban.enabled runs.external.vibe_kanban.mode runs.external.vibe_kanban.project_id runs.external.vibe_kanban.state_dir runs.external.vibe_kanban.workflow_version runs.external.vibe_kanban.mcp_command' }, { tab: 'Features', section: 'Integrations & observability', label: 'OpenTelemetry export', key: 'otel.enabled', text: 'otel opentelemetry export endpoint headers insecure sample ratio service name otel.enabled otel.endpoint otel.headers. otel.insecure otel.sample_ratio otel.service_name' }, { tab: 'Thresholds', section: 'Thresholds', label: 'Restart thresholds', key: 'governor.modes', text: 'restart thresholds quiet busy surge pressure backoff governor.modes.quiet.threshold governor.modes.busy.threshold governor.modes.surge.threshold' }, @@ -72513,25 +72513,7 @@

${esc(s.title)}

-
Spek recheck ${settingHelpMark('spektacular', '', 'Spek recheck', `Continuous convergence: re-runs the spec for opted-in campaigns on a cadence and imports changed or new plan tasks. The source lists (runs.spektacular.recheck.sources, runs.spektacular.recheck.discovery.sources) and runs.spektacular.recheck.egress_allowlist are yaml-only.`)}
-
-
- Recheck cadence enabled ${yamlHint('runs.spektacular.recheck.enabled')} ${settingHelpMark('spektacular', '', 'Recheck cadence enabled', `Lets the scheduler start rechecks on cadence. A manual recheck also needs this unless it is forced.`)} -
-
-
-
-
-
-
-
- Outward discovery ${yamlHint('runs.spektacular.recheck.discovery.enabled')} ${settingHelpMark('spektacular', '', 'Outward discovery', `Gathers bounded evidence from the declared discovery sources before a recheck spec. Does nothing without sources.`)} -
-
-
-
-
-
Checkpoint, triage and recheck settings are applied live; no restart is needed.
+
Checkpoint and triage settings are applied live; no restart is needed.
Integration orchestration
diff --git a/src/pkg/spektacular/adapter.go b/src/pkg/spektacular/adapter.go index 03507968fd..10a437e899 100644 --- a/src/pkg/spektacular/adapter.go +++ b/src/pkg/spektacular/adapter.go @@ -55,10 +55,6 @@ type LeaseRegistry interface { ImportRunPlan(runKey, repo, taskList string, engineName ...string) error } -type recheckTicker interface { - TickCampaignRechecks(context.Context, time.Time) -} - // leaseAdapter implements Registry over a LeaseRegistry. type leaseAdapter struct { reg LeaseRegistry @@ -185,11 +181,6 @@ func (h *HubRunner) Tick(ctx context.Context, now time.Time) { return } h.runner.Tick(ctx, now) - if ticker, ok := h.runner.Registry.(*leaseAdapter); ok { - if rechecks, ok := ticker.reg.(recheckTicker); ok { - rechecks.TickCampaignRechecks(ctx, now) - } - } } // Runner exposes the underlying poll loop (tests and diagnostics).