diff --git a/changelog.d/added-workflowmodel-compiler.md b/changelog.d/added-workflowmodel-compiler.md new file mode 100644 index 0000000000..84df9ed9d8 --- /dev/null +++ b/changelog.d/added-workflowmodel-compiler.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 1 ([#17620](https://github.com/hivecommons/hive/issues/17620)): the `workflow.hivecommons.dev/v1alpha1` schema gains the lifecycle half of the RFC — `columns`, `derivation`, `events`, `gates`, `roles`, `agents`, `checks`, `bookkeeping`, `labels`, `meta` and per-state `lifecycle` (column, stage number, item kinds, replies) — and `workflowmodel.Compile` turns a model into a `Profile` or refuses it with coded diagnostics (a non-terminal state with no exit, a gate with no releasing role, an agent-granted state with no human-released gate before a terminal outcome, two events bound to one fact, a state in no or two columns, duplicate stage numbers, an unknown fact or operator). `pkg/workflowmodel/hivedefault` generates the `hive-default` model from the live stage table and the engine's expected-edge table, so the monitor's seven columns and the stage numbers are now a compiled model rather than constants. `stageengine.DeriveFromModel` derives under a compiled profile: `hive-default` declares `derivation: builtin` and delegates to the existing derivers (the whole PR stage-golden corpus and the issue sweep derive identically), custom models declare `derivation: rules` (ordered first-match predicates over the fact vocabulary, uncovered items abstain `workflow: not covered`). New `workflow.enabled` config flag, default false; nothing changes for any hive until a repository is bound (phase 2). diff --git a/changelog.d/added-workflowmodel-ingest-lifecycle.md b/changelog.d/added-workflowmodel-ingest-lifecycle.md new file mode 100644 index 0000000000..7906f340b3 --- /dev/null +++ b/changelog.d/added-workflowmodel-ingest-lifecycle.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 3a ([#17620](https://github.com/hivecommons/hive/issues/17620)): an ingested repository now yields a model that compiles. `ingest.Lifecycle` composes the hive-default lifecycle (states, columns, builtin derivation, roles, gates, events) with the repository's pipelines — PR-verify pipelines bound to the CI / Review states with file citations, the post-merge chain (main CI, release, per-environment deploys, done) as new columns after Merged — every ingested element marked inferred and the model's provenance `ingested-unreviewed`. New fact `pipeline.status` names the post-merge run the chain waits on (the engine reports `unknown` until it observes post-merge runs, so nothing moves on it yet). New owner-gated `POST /api/workflows/ingest` takes `{repo}` (default branch fetched read-only through the hive's GitHub client, CI files selected by `ingest.ReadTree`) or pasted `{files}`, returns the model, compile result and diagnostics, and with `save: true` stores it at the next integer version. `cmd/workflow-survey` compiles every repository's lifecycle model and reports pass/refusal counts by code; over the 317-repository CNCF corpus 317/317 compile with 1,117 inferred-element warnings and no refusals. diff --git a/changelog.d/added-workflowmodel-store-bindings.md b/changelog.d/added-workflowmodel-store-bindings.md new file mode 100644 index 0000000000..c369578e87 --- /dev/null +++ b/changelog.d/added-workflowmodel-store-bindings.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 2 ([#17620](https://github.com/hivecommons/hive/issues/17620)): models now have a home and a way to reach the engine. `pkg/workflowmodel/store` keeps versioned models under `/workflows//.json` (plus `index.json`); `hive-default` is virtual and read-only, drafts save but do not compile, every entry reserves `adoption`/`ratings`/`benchmarks` fields for the marketplace and carries them verbatim across saves. New owner-gated, audited `/api/workflows` routes list, save, read, delete and compile models; `project.workflow_bindings: [{repo, name, version}]` binds a repository to a compiling model (the binding is refused for a draft, and a bound model cannot be deleted). When `workflow.enabled` is on, the stage reconciler derives bound repositories through the bound model and everything else through the built-in derivers exactly as before. Settings → Repos gains a per-repo Workflow select, and the Activity Monitor response gains a `workflows` block (default columns plus per-repo columns and stage numbers) that the tracker uses to label the model column and to render a per-row column strip, with an amber "Not covered" chevron when a bound model abstains. Nothing changes for unbound repositories. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 2df0be2818..22f41fe5fb 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -83,6 +83,10 @@ { "name": "Swarm", "description": "Repo swarm mode status, lifecycle, and history" + }, + { + "name": "Workflows", + "description": "Workflow models (RFC hivecommons/hive#17620): the spoke-local library of ingested/authored workflow definitions, per-repository bindings, and compilation. Writes are owner-gated and audited (workflow_save, workflow_delete, workflow_bind, workflow_unbind). Every route answers 503 when the hive has no workflow store." } ], "paths": { @@ -38109,22 +38113,59 @@ }, "/api/repos/{owner}/{repo}/items/{number}/blocker/handoff": { "post": { - "tags": ["Status"], + "tags": [ + "Status" + ], "summary": "Hand a workflows-blocked issue to a capable lane", "description": "Requires a signed-in repository writer, an open parked issue without a hold, a workflows permission blocker, and an eligible lane with installation permission. Records the decision and routes the issue to that lane.", "parameters": [ - {"name": "owner", "in": "path", "required": true, "schema": {"type": "string"}}, - {"name": "repo", "in": "path", "required": true, "schema": {"type": "string"}}, - {"name": "number", "in": "path", "required": true, "schema": {"type": "integer"}} + { + "name": "owner", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "number", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } ], "responses": { - "200": {"description": "Handoff recorded"}, - "401": {"description": "GitHub user session required"}, - "403": {"description": "Repository write access required"}, - "404": {"description": "No blocker is recorded"}, - "409": {"description": "Issue is held, not parked, or no capable lane is available"}, - "502": {"description": "GitHub operation failed"}, - "503": {"description": "GitHub client unavailable"} + "200": { + "description": "Handoff recorded" + }, + "401": { + "description": "GitHub user session required" + }, + "403": { + "description": "Repository write access required" + }, + "404": { + "description": "No blocker is recorded" + }, + "409": { + "description": "Issue is held, not parked, or no capable lane is available" + }, + "502": { + "description": "GitHub operation failed" + }, + "503": { + "description": "GitHub client unavailable" + } } } }, @@ -38923,6 +38964,471 @@ } } } + }, + "/api/workflows": { + "get": { + "tags": [ + "Workflows" + ], + "summary": "List workflow models", + "description": "Every stored model version plus the virtual read-only hive-default, the current repository bindings, and whether model-driven derivation (workflow.enabled) is on.", + "responses": { + "200": { + "description": "Library", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "workflows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowEntry" + } + }, + "bindings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowBinding" + } + }, + "enabled": { + "type": "boolean" + } + } + } + } + } + }, + "503": { + "description": "No workflow store" + } + } + }, + "post": { + "tags": [ + "Workflows" + ], + "summary": "Save a workflow model", + "description": "Owner only. Compiles the model; a draft that fails compilation is still stored (compiled=false) so it can be edited, but cannot be bound. Audited as workflow_save.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowModel" + } + } + } + }, + "responses": { + "201": { + "description": "Stored", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entry": { + "$ref": "#/components/schemas/WorkflowEntry" + } + } + } + } + } + }, + "400": { + "description": "Bad name/version or invalid model" + }, + "403": { + "description": "Not an owner, or the version is read-only (hive-default)" + }, + "503": { + "description": "No workflow store" + } + } + } + }, + "/api/workflows/compile": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Compile a workflow model without storing it", + "description": "Returns the compiler diagnostics and, when it compiles, the profile. Used by the editor and by ingest previews.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowModel" + } + } + } + }, + "responses": { + "200": { + "description": "Compilation result", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "compiled": { + "type": "boolean" + }, + "diagnostics": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowDiagnostic" + } + }, + "profile": { + "$ref": "#/components/schemas/WorkflowProfile" + } + } + } + } + } + }, + "400": { + "description": "Malformed body" + }, + "503": { + "description": "No workflow store" + } + } + } + }, + "/api/workflows/bindings": { + "get": { + "tags": [ + "Workflows" + ], + "summary": "List repository → workflow bindings", + "description": "project.workflow_bindings from hive.yaml plus the live workflow.enabled flag. Unbound repositories derive with hive-default.", + "responses": { + "200": { + "description": "Bindings", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "bindings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowBinding" + } + }, + "enabled": { + "type": "boolean" + } + } + } + } + } + }, + "503": { + "description": "No workflow store or config" + } + } + }, + "put": { + "tags": [ + "Workflows" + ], + "summary": "Bind or unbind a repository", + "description": "Owner only. Body {repo, name, version}; an empty name unbinds. The model must exist and compile. Persists hive.yaml and takes effect on the next derivation pass. Audited as workflow_bind / workflow_unbind.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowBinding" + } + } + } + }, + "responses": { + "200": { + "description": "Bindings after the change", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "changed": { + "type": "boolean" + }, + "bindings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowBinding" + } + } + } + } + } + } + }, + "400": { + "description": "Missing repo, or the model does not compile" + }, + "403": { + "description": "Not an owner" + }, + "404": { + "description": "Model not found" + }, + "503": { + "description": "No workflow store or config" + } + } + } + }, + "/api/workflows/{name}/{version}": { + "get": { + "tags": [ + "Workflows" + ], + "summary": "Fetch one workflow model version", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Model", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entry": { + "$ref": "#/components/schemas/WorkflowEntry" + }, + "model": { + "$ref": "#/components/schemas/WorkflowModel" + }, + "profile": { + "$ref": "#/components/schemas/WorkflowProfile" + } + } + } + } + } + }, + "404": { + "description": "Not found" + }, + "503": { + "description": "No workflow store" + } + } + }, + "put": { + "tags": [ + "Workflows" + ], + "summary": "Save a workflow model at an explicit name@version", + "description": "Owner only. Same as POST /api/workflows but the path must agree with the body name/version. Audited as workflow_save.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowModel" + } + } + } + }, + "responses": { + "201": { + "description": "Stored", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entry": { + "$ref": "#/components/schemas/WorkflowEntry" + } + } + } + } + } + }, + "400": { + "description": "Path and body disagree, or invalid model" + }, + "403": { + "description": "Not an owner, or read-only" + }, + "503": { + "description": "No workflow store" + } + } + }, + "delete": { + "tags": [ + "Workflows" + ], + "summary": "Delete a workflow model version", + "description": "Owner only. Refused with 409 while any repository is bound to it; hive-default cannot be deleted. Audited as workflow_delete.", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deleted", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "403": { + "description": "Not an owner, or read-only" + }, + "404": { + "description": "Not found" + }, + "409": { + "description": "Still bound" + }, + "503": { + "description": "No workflow store" + } + } + } + }, + "/api/workflows/ingest": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Ingest a repository's CI definitions into a lifecycle workflow model", + "description": "Reads the repository's default-branch GitHub Actions workflows and Tekton resources (or pasted files) and returns the hive-default lifecycle with the repository's pipelines bound: PR-verify pipelines on the CI / Review states, the post-merge chain as new columns. Provenance ingested-unreviewed. With save=true the model is stored as the next integer version under name. Owner role required.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "repo": { + "type": "string", + "description": "owner/name to fetch through the forge client; exactly one of repo or files" + }, + "files": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "repo-relative path to file contents, for pasted or uploaded definitions" + }, + "save": { + "type": "boolean" + }, + "name": { + "type": "string", + "description": "store name (default: slug of the repository)" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Ingested (not saved)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowIngestResult" + } + } + } + }, + "201": { + "description": "Ingested and saved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowIngestResult" + } + } + } + }, + "400": { + "description": "Bad request" + }, + "403": { + "description": "Owner role required" + }, + "502": { + "description": "Repository fetch failed" + }, + "503": { + "description": "No forge client or no workflow store" + } + } + } } }, "components": { @@ -39227,6 +39733,137 @@ } } } + }, + "WorkflowEntry": { + "type": "object", + "description": "Index row for one stored model version.", + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "hash": { + "type": "string", + "description": "sha256 of the stored model document" + }, + "title": { + "type": "string" + }, + "provenance": { + "type": "string", + "enum": [ + "builtin", + "local", + "ingested", + "imported" + ] + }, + "compiled": { + "type": "boolean", + "description": "false for a draft that does not compile; drafts can be stored but not bound" + }, + "builtin": { + "type": "boolean", + "description": "true for the read-only hive-default model" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "ratings": { + "description": "Reserved for the marketplace (benchmarks, votes); preserved verbatim across saves.", + "nullable": true + } + } + }, + "WorkflowBinding": { + "type": "object", + "properties": { + "repo": { + "type": "string", + "description": "owner/repo or bare repo name" + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + } + }, + "required": [ + "repo", + "name", + "version" + ] + }, + "WorkflowDiagnostic": { + "type": "object", + "properties": { + "severity": { + "type": "string", + "enum": [ + "error", + "warning" + ] + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + } + }, + "WorkflowModel": { + "type": "object", + "description": "A workflow.hivecommons.dev/v1alpha1 model document (states, transitions, columns, derivation, events, gates, roles, agents, checks, bookkeeping, labels, meta).", + "additionalProperties": true + }, + "WorkflowProfile": { + "type": "object", + "description": "Compiled, derivation-ready form of a model (hash, states, columns, ordered rules). Never trusted from the wire: the spoke recompiles on save and on bind.", + "additionalProperties": true + }, + "WorkflowIngestResult": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/WorkflowModel" + }, + "compiled": { + "type": "boolean" + }, + "diagnostics": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowDiagnostic" + } + }, + "profile": { + "type": "object" + }, + "ref": { + "type": "string" + }, + "files": { + "type": "integer" + }, + "pipelines": { + "type": "integer" + }, + "entry": { + "$ref": "#/components/schemas/WorkflowEntry" + } + } } } } diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 74055b4905..1fdb6a04d7 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "encoding/json" "fmt" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" "io" "log/slog" "net/url" @@ -1085,6 +1086,8 @@ func (b *boot) wireBootClosures() { } return &dashboard.Dependencies{ Config: b.cfg, + WorkflowStore: wfstore.Open(wfstore.Root(b.cfg.Data.WorkflowsDir)), + WorkflowRepoFiles: workflowRepoFiles(func() *github.Client { return b.ghClient }), AgentMgr: b.agentMgr, CruxRuntimeHealth: cruxRuntimeHealthFunc(b.cruxSupervision), // Provider gateways (#5565 slice 3): concrete openrouter/watsonx/ diff --git a/src/cmd/hive/stage_engine.go b/src/cmd/hive/stage_engine.go index 58b5ae5e5d..72d5f41066 100644 --- a/src/cmd/hive/stage_engine.go +++ b/src/cmd/hive/stage_engine.go @@ -8,6 +8,8 @@ import ( "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stageengine" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" ) // The central stage engine (ADR-0025, hivecommons/hive#12999) is built once @@ -38,17 +40,52 @@ func stageEngineOptions(cfg *config.Config, logger *slog.Logger) *stageengine.Op logger = slog.Default() } stageEngine.opts = &stageengine.Options{ - Mode: stageEngineConfiguredMode(cfg), - Store: stagelabels.Shared(), - Issue: github.IssueDeriver(), - PR: stageengine.PRDeriver(), - Logger: logger, - Metrics: stageengine.DefaultCounters(), + Mode: stageEngineConfiguredMode(cfg), + Store: stagelabels.Shared(), + Issue: github.IssueDeriver(), + PR: stageengine.PRDeriver(), + Logger: logger, + Metrics: stageengine.DefaultCounters(), + WorkflowFor: stageEngineWorkflowFor(cfg, wfstore.Open(wfstore.Root(cfg.Data.WorkflowsDir)), logger), } }) return stageEngine.opts } +// stageEngineWorkflowFor resolves the workflow model bound to a repository +// (hivecommons/hive#17620). cfg is read on every call — hive.yaml reloads +// and dashboard binding edits mutate it in place — so a binding or the +// workflow.enabled flag takes effect on the next derivation. A bound model +// that is missing or no longer compiles is logged once per key and the +// repository falls back to hive-default rather than going unlabelled. +func stageEngineWorkflowFor(cfg *config.Config, st *wfstore.Store, logger *slog.Logger) func(owner, repo string) *workflowmodel.Profile { + if cfg == nil || st == nil { + return nil + } + var warned sync.Map + return func(owner, repo string) *workflowmodel.Profile { + if !cfg.Workflow.Enabled { + return nil + } + full := repo + if owner != "" { + full = owner + "/" + repo + } + b, ok := cfg.WorkflowBindingFor(full) + if !ok { + return nil + } + p, err := st.Profile(b.Name, b.Version) + if err != nil { + if _, dup := warned.LoadOrStore(b.Key()+"|"+err.Error(), true); !dup && logger != nil { + logger.Warn("workflow binding unusable; repository falls back to hive-default", "repo", full, "workflow", b.Key(), "err", err) + } + return nil + } + return p + } +} + func stageEngineConfiguredMode(cfg *config.Config) stageengine.Mode { if cfg == nil { return config.DefaultStageEngineMode diff --git a/src/cmd/hive/stage_engine_workflow_test.go b/src/cmd/hive/stage_engine_workflow_test.go new file mode 100644 index 0000000000..a41bc124de --- /dev/null +++ b/src/cmd/hive/stage_engine_workflow_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "encoding/json" + "os" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/workflowmodel" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +func TestStageEngineWorkflowFor(t *testing.T) { + if stageEngineWorkflowFor(nil, nil, nil) != nil { + t.Fatal("nil inputs") + } + st := wfstore.Open(t.TempDir()) + b, err := os.ReadFile("../../pkg/workflowmodel/testdata/models/techdocs.json") + if err != nil { + t.Fatal(err) + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + if _, err := st.Save(&m, "test", time.Now()); err != nil { + t.Fatal(err) + } + cfg := &config.Config{Project: config.ProjectConfig{Org: "cncf"}} + if _, err := cfg.SetWorkflowBinding("techdocs", "cncf-techdocs", "1"); err != nil { + t.Fatal(err) + } + if _, err := cfg.SetWorkflowBinding("ghost", "nope", "1"); err != nil { + t.Fatal(err) + } + lookup := stageEngineWorkflowFor(cfg, st, discardLogger()) + + if lookup("cncf", "techdocs") != nil { + t.Fatal("flag off must resolve nothing") + } + cfg.Workflow.Enabled = true + if p := lookup("cncf", "techdocs"); p == nil || p.Name != "cncf-techdocs" { + t.Fatalf("%+v", p) + } + if lookup("", "techdocs") == nil { + t.Fatal("bare repo should qualify with the org") + } + if lookup("cncf", "other") != nil { + t.Fatal("unbound repo resolved a model") + } + // Twice: the second call exercises the warn-once path. + for i := 0; i < 2; i++ { + if lookup("cncf", "ghost") != nil { + t.Fatal("missing model must fall back") + } + } + if _, err := cfg.SetWorkflowBinding("techdocs", "", ""); err != nil { + t.Fatal(err) + } + if lookup("cncf", "techdocs") != nil { + t.Fatal("unbinding must take effect live") + } +} diff --git a/src/cmd/hive/workflow_ingest.go b/src/cmd/hive/workflow_ingest.go new file mode 100644 index 0000000000..00f80f6d45 --- /dev/null +++ b/src/cmd/hive/workflow_ingest.go @@ -0,0 +1,37 @@ +package main + +import ( + "context" + "errors" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/workflowmodel/ingest" +) + +// errNoForgeClient is returned by the workflow ingest fetcher before a +// GitHub client exists. +var errNoForgeClient = errors.New("no GitHub client") + +// workflowRepoFiles is the dashboard's WorkflowRepoFiles dependency +// (POST /api/workflows/ingest, RFC #17620 P3): it downloads the repo's +// default branch read-only, keeps only the CI definition files and +// removes the checkout. client is read per call so a credential rebuild is +// followed. +func workflowRepoFiles(client func() *github.Client) func(ctx context.Context, repo string) (map[string][]byte, string, error) { + return func(ctx context.Context, repo string) (map[string][]byte, string, error) { + c := client() + if c == nil { + return nil, "", errNoForgeClient + } + co, err := c.FetchDefaultBranchTree(ctx, repo) + if err != nil { + return nil, "", err + } + defer co.Cleanup() + files, err := ingest.ReadTree(co.Dir) + if err != nil { + return nil, "", err + } + return files, co.Ref, nil + } +} diff --git a/src/cmd/hive/workflow_ingest_test.go b/src/cmd/hive/workflow_ingest_test.go new file mode 100644 index 0000000000..b10e3e219c --- /dev/null +++ b/src/cmd/hive/workflow_ingest_test.go @@ -0,0 +1,16 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/hivecommons/hive/pkg/github" +) + +func TestWorkflowRepoFilesWithoutClient(t *testing.T) { + fetch := workflowRepoFiles(func() *github.Client { return nil }) + if _, _, err := fetch(context.Background(), "acme/widgets"); !errors.Is(err, errNoForgeClient) { + t.Fatalf("err = %v", err) + } +} diff --git a/src/cmd/workflow-survey/main.go b/src/cmd/workflow-survey/main.go index 45f352b3b9..31ad3e2752 100644 --- a/src/cmd/workflow-survey/main.go +++ b/src/cmd/workflow-survey/main.go @@ -68,6 +68,12 @@ type repoResult struct { ValidateError string `json:"validateError,omitempty"` Hash string `json:"hash"` Severities map[workflowmodel.Severity]int `json:"severities,omitempty"` + // Compiled says whether the lifecycle model (ingest.Lifecycle) compiles; + // CompileCodes counts its diagnostics by code, errors and warnings. + Compiled bool `json:"compiled"` + CompileError string `json:"compileError,omitempty"` + CompileCodes map[string]int `json:"compileCodes,omitempty"` + LifecycleCols int `json:"lifecycleColumns"` } type summary struct { @@ -78,6 +84,8 @@ type summary struct { Parsed int `json:"parsed"` Pipelines int `json:"pipelines"` Valid int `json:"valid"` + Compiled int `json:"compiled"` + CompileCodes map[string]int `json:"compileCodes"` Roles map[workflowmodel.Role]int `json:"roles"` Constructs map[string]int `json:"constructs"` FindingCodes map[string]int `json:"findingCodes"` @@ -160,7 +168,7 @@ func run(corpus, out string, filter map[string]bool, stdout, stderr io.Writer) e return err } maturity := loadProjects(corpus) - sum := &summary{Roles: map[workflowmodel.Role]int{}, Constructs: map[string]int{}, FindingCodes: map[string]int{}, Severities: map[workflowmodel.Severity]int{}, ColumnSets: map[string]int{}, ByProject: map[string]*projectStats{}} + sum := &summary{Roles: map[workflowmodel.Role]int{}, Constructs: map[string]int{}, FindingCodes: map[string]int{}, Severities: map[workflowmodel.Severity]int{}, CompileCodes: map[string]int{}, ColumnSets: map[string]int{}, ByProject: map[string]*projectStats{}} for _, d := range dirs { if !d.IsDir() { continue @@ -252,9 +260,25 @@ func surveyRepo(dir, repo, outDir string) (repoResult, error) { } res.ColumnDiff = render.Diff(m) + lm := ingest.Lifecycle(workflowmodel.Scope{Forge: defaultForge, Repository: repo}, files) + res.LifecycleCols = len(lm.Spec.Columns) + res.CompileCodes = map[string]int{} + _, diags, cerr := workflowmodel.Compile(lm) + for _, d := range diags { + res.CompileCodes[d.Code]++ + } + if cerr != nil { + res.CompileError = cerr.Error() + } else { + res.Compiled = true + } + if err := os.MkdirAll(outDir, 0o755); err != nil { return res, err } + if err := writeJSON(filepath.Join(outDir, "lifecycle.json"), lm); err != nil { + return res, err + } if err := writeJSON(filepath.Join(outDir, "model.json"), m); err != nil { return res, err } @@ -324,6 +348,12 @@ func accumulate(s *summary, r repoResult) { if r.Valid { s.Valid++ } + if r.Compiled { + s.Compiled++ + } + for k, v := range r.CompileCodes { + s.CompileCodes[k] += v + } if len(r.ColumnDiff) > 0 { s.ReposChangedCols++ } @@ -375,7 +405,12 @@ func markdown(s *summary) string { fmt.Fprintf(&b, "# Workflow model survey\n\n") fmt.Fprintf(&b, "| | |\n|---|---|\n") fmt.Fprintf(&b, "| Repositories | %d |\n| with GitHub Actions pipelines | %d |\n| with Tekton pipelines | %d |\n", s.Repos, s.ReposWithGHA, s.ReposWithTekton) - fmt.Fprintf(&b, "| Files read | %d |\n| Files parsed | %d (%.1f%%) |\n| Pipelines | %d |\n| Models valid | %d / %d |\n| Repos whose columns change | %d |\n\n", s.Files, s.Parsed, pct(s.Parsed, s.Files), s.Pipelines, s.Valid, s.Repos, s.ReposChangedCols) + fmt.Fprintf(&b, "| Files read | %d |\n| Files parsed | %d (%.1f%%) |\n| Pipelines | %d |\n| Models valid | %d / %d |\n| Lifecycle models compiled | %d / %d |\n| Repos whose columns change | %d |\n\n", s.Files, s.Parsed, pct(s.Parsed, s.Files), s.Pipelines, s.Valid, s.Repos, s.Compiled, s.Repos, s.ReposChangedCols) + b.WriteString("## Lifecycle compile diagnostics\n\n| Code | Count |\n|---|---|\n") + for _, k := range sortedKeys(s.CompileCodes) { + fmt.Fprintf(&b, "| %s | %d |\n", k, s.CompileCodes[k]) + } + b.WriteString("\n") b.WriteString("## Pipeline roles\n\n| Role | Pipelines |\n|---|---|\n") for _, k := range sortedKeys(s.Roles) { fmt.Fprintf(&b, "| %s | %d |\n", k, s.Roles[workflowmodel.Role(k)]) diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 5eae755888..aa50320e49 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -30,9 +30,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)); also `hub_build` (the hub's short SHA) and, once a stdio `hive-admin-mcp` client has called `/api/version`, `/api/status` or `/api/status/summary` with its `hive-admin-mcp/+` User-Agent, `last_seen_stdio_build` and `last_seen_stdio_at` (RFC3339) so the dashboard can flag build skew ([#12318](https://github.com/hivecommons/hive/issues/12318)) | `pkg/dashboard/api.go:45` | -| `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | -| `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:76` | +| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)); also `hub_build` (the hub's short SHA) and, once a stdio `hive-admin-mcp` client has called `/api/version`, `/api/status` or `/api/status/summary` with its `hive-admin-mcp/+` User-Agent, `last_seen_stdio_build` and `last_seen_stdio_at` (RFC3339) so the dashboard can flag build skew ([#12318](https://github.com/hivecommons/hive/issues/12318)) | `pkg/dashboard/api.go:46` | +| `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:47` | +| `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:77` | | `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1827` | | `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1828` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1829` | @@ -53,55 +53,55 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `PUT` | `/api/swarm/themes` | Owner only | Set a per-repo swarm theme (`event_name`, `call_to_arms`, `leaderboard_title`). | `pkg/dashboard/swarm.go:316` | | `PATCH` | `/api/swarm/objectives` | Owner only | Update the active swarm SDLC objective checklist completion state. | `pkg/dashboard/swarm.go:317` | | `GET` | `/api/leaderboard/swarm` | Public | Stable public JSON record of swarm history, leaderboard, top players, and achievements. | `pkg/dashboard/swarm.go:318` | -| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:98` | -| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:99` | -| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:100` | -| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:104` | -| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:105` | -| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:108` | -| `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:110` | -| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:111` | -| `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:112` | -| `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:113` | -| `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:114` | -| `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:115` | -| `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:116` | -| `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:117` | -| `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:118` | -| `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:119` | -| `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:120` | -| `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:121` | -| `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:122` | -| `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:123` | -| `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:124` | -| `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:125` | -| `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:126` | -| `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:127` | -| `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:128` | -| `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:129` | -| `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:101` | +| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:99` | +| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:100` | +| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:101` | +| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:105` | +| `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:106` | +| `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:109` | +| `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:111` | +| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:112` | +| `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:113` | +| `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:114` | +| `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:115` | +| `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:116` | +| `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:117` | +| `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:118` | +| `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:119` | +| `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:120` | +| `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:121` | +| `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:122` | +| `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:123` | +| `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:124` | +| `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:125` | +| `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:126` | +| `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:127` | +| `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:128` | +| `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:129` | +| `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:130` | +| `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:102` | ## Snapshots and style | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | +| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:48` | | `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1922` | -| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | -| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | -| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | +| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:91` | +| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:92` | +| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:93` | ## Auth and external accounts | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:192` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:193` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:194` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:195` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:196` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:197` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:198` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:193` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:194` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:195` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:196` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:197` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:198` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:199` | | `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` | @@ -122,169 +122,169 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:48` | -| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:49` | -| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:50` | -| `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:278` | -| `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:279` | +| `GET` | `/api/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:49` | +| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:50` | +| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:51` | +| `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:60` | +| `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:61` | +| `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:52` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:279` | +| `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:280` | | `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` | -| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:58` | -| `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:207` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:208` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:209` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:210` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:211` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:212` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:213` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:214` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:216` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:217` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:218` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:219` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:220` | +| `GET` | `/api/config/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:55` | +| `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:56` | +| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:59` | +| `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:62` | +| `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:63` | + +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get | `pkg/dashboard/api.go:208` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General | `pkg/dashboard/api.go:209` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:211` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:212` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:213` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:214` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:215` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:216` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:217` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:218` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:219` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:220` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:221` | | `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:221` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:223` | -| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:227` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:228` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:235` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:236` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:240` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:241` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:257` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:258` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:259` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:260` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:261` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:222` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:224` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:228` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:229` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:236` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:237` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:241` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:242` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:258` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:259` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:260` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:261` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:262` | | `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:308` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:309` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:310` | - -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:229` | -| `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:230` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:312` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:313` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:316` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:317` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:318` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:319` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:320` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:325` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:326` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:327` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:331` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:332` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:335` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:395` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:396` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:397` | -| `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:387` | -| `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:388` | -| `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:389` | -| `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:390` | -| `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:391` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:392` | -| `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:393` | -| `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:571` | - -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:232` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:233` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:234` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:237` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:242` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:245` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:246` | -| `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:567` | -| `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:568` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:262` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:269` | -| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:281` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:282` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:283` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:284` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:309` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:310` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:311` | + +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:230` | +| `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:231` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:313` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:314` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:317` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:318` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:319` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:320` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:321` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:326` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:327` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:328` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:332` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:333` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:336` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:396` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:397` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:398` | +| `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:388` | +| `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:389` | +| `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:390` | +| `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:391` | +| `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:392` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:393` | +| `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:394` | +| `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:572` | + +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:233` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:234` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:235` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:238` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:243` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:246` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:247` | +| `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:568` | +| `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:569` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:254` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:257` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:263` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:264` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:265` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:270` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:276` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:278` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:282` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:283` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:284` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:285` | | `GET` | `/api/config/decisions/delegate` | Owner only | "Let hive decide" settings (`decisions.delegate`) with defaults resolved: `enabled` (unset = on), `enabled_set`, `repos` (`{owner/repo: {enabled}}`), `llm` (`{enabled, model, model_masked}`; unset = off), `llm_reviewer_ready` and `llm_model_effective` (the decider turn's model; the endpoint and its key are never returned), `effect_timeout`, `effect_timeout_effective`, `project_repos`. A stored `llm.model` that looks like a key is masked | `pkg/dashboard/api_config_decisions_delegate.go` | | `PUT` | `/api/config/decisions/delegate` | Owner only | Change `decisions.delegate`: `enabled`, `repos` (the full override map when sent; an entry with `enabled: null` is dropped; a new key must be in `project.repos`), `llm.enabled`, `llm.model` (a model name; a key-like value is refused) and `effect_timeout`. Unknown fields and invalid values are 400 with nothing changed. Saved, audited as `config_decisions_delegate` with the actor and each change before and after, and applied without a restart. Starts no decision and merges nothing | `pkg/dashboard/api_config_decisions_delegate.go` | -| `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:294` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:295` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:296` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:298` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:299` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:314` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:315` | -| `GET` | `/api/advisor/records` | Read-write role | Advisor Records — query `?agent=` (filter by agent), `?since=`/`?until=` (RFC3339, either omitted), or `?hours=` (lookback 1..720, alternative to since), optional `?limit=` (capped at 200 by default); returns `{records: [], active?, active_reason?}` where active/reason appear only when filtered to one agent. Records are scrubbed at the boundary. Response shape in [api_advisor.go](../pkg/dashboard/api_advisor.go#L38) | `pkg/dashboard/api.go:64` | -| `GET` | `/api/advisor/spend` | Dashboard auth/session | Advisor Spend — per-agent advisor spend over one window, alongside (not folded into) the agent's own spend. Query presets `?range=hourly|daily|weekly|monthly` (Cost section timeframes) or custom `?since=`/`?until=` (RFC3339) or `?hours=` (lookback 1..720); optionally filter `?agent=`. Returns `{range, since?, until?, total_cost_usd, agents:[]}` where range is the preset or "custom". Response shape in [api_advisor.go](../pkg/dashboard/api_advisor.go#L151) | `pkg/dashboard/api.go:65` | -| `GET` | `/api/config/advisor` | Owner only | Advisor Config Get (fleet block, model roles map, and per-agent overrides; includes effective `fleet.enabled` boolean from IsEnabled()) | `pkg/dashboard/api.go:66` | -| `PUT` | `/api/config/advisor` | Owner only | Advisor Config Set (fleet-wide settings; only fields present in body change) | `pkg/dashboard/api.go:67` | -| `PUT` | `/api/config/advisor/roles` | Owner only | Advisor Model Roles Set (replaces named model_roles map; roles in use cannot be removed) | `pkg/dashboard/api.go:68` | -| `PUT` | `/api/config/advisor/agent/{name}` | Owner only | Advisor Agent Override Set (set or clear one agent's override; null/empty clears it) | `pkg/dashboard/api.go:69` | -| `GET` | `/api/config/channels` | Owner only | Settings → Channels payload (GitHub mention/Actions triggers, chat bots, escalation sinks, read-only dashboard chat status, admin MCP status with the effective `writesEnabled` and its `writesSource` (`config`, `env` or `default`), mention-eligible agents); secrets masked | `pkg/dashboard/api.go:249` | -| `PUT` | `/api/config/channels` | Owner only | Partial update of the same surfaces, plus `adminMcp.writesEnabled` (the `admin_mcp.writes_enabled` switch, which overrides `HIVE_ADMIN_MCP_ENABLE_WRITES` once set) or `adminMcp.writesFollowEnv: true` (clears it so the env or the default decides; sending both is a 400); a change is audited as `config_admin_mcp_writes`; validated against a copy so a 400 applies nothing; masked echo keeps a secret, empty clears it; hot-reloads mention poller and escalation sinks | `pkg/dashboard/api.go:250` | +| `GET` | `/api/config/governor/work-source` | Owner only | Governor Work Source Get (Jira secrets/TLS fields reported as set/unset only) | `pkg/dashboard/api.go:295` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:296` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:297` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:299` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:300` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:315` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:316` | +| `GET` | `/api/advisor/records` | Read-write role | Advisor Records — query `?agent=` (filter by agent), `?since=`/`?until=` (RFC3339, either omitted), or `?hours=` (lookback 1..720, alternative to since), optional `?limit=` (capped at 200 by default); returns `{records: [], active?, active_reason?}` where active/reason appear only when filtered to one agent. Records are scrubbed at the boundary. Response shape in [api_advisor.go](../pkg/dashboard/api_advisor.go#L38) | `pkg/dashboard/api.go:65` | +| `GET` | `/api/advisor/spend` | Dashboard auth/session | Advisor Spend — per-agent advisor spend over one window, alongside (not folded into) the agent's own spend. Query presets `?range=hourly|daily|weekly|monthly` (Cost section timeframes) or custom `?since=`/`?until=` (RFC3339) or `?hours=` (lookback 1..720); optionally filter `?agent=`. Returns `{range, since?, until?, total_cost_usd, agents:[]}` where range is the preset or "custom". Response shape in [api_advisor.go](../pkg/dashboard/api_advisor.go#L151) | `pkg/dashboard/api.go:66` | +| `GET` | `/api/config/advisor` | Owner only | Advisor Config Get (fleet block, model roles map, and per-agent overrides; includes effective `fleet.enabled` boolean from IsEnabled()) | `pkg/dashboard/api.go:67` | +| `PUT` | `/api/config/advisor` | Owner only | Advisor Config Set (fleet-wide settings; only fields present in body change) | `pkg/dashboard/api.go:68` | +| `PUT` | `/api/config/advisor/roles` | Owner only | Advisor Model Roles Set (replaces named model_roles map; roles in use cannot be removed) | `pkg/dashboard/api.go:69` | +| `PUT` | `/api/config/advisor/agent/{name}` | Owner only | Advisor Agent Override Set (set or clear one agent's override; null/empty clears it) | `pkg/dashboard/api.go:70` | +| `GET` | `/api/config/channels` | Owner only | Settings → Channels payload (GitHub mention/Actions triggers, chat bots, escalation sinks, read-only dashboard chat status, admin MCP status with the effective `writesEnabled` and its `writesSource` (`config`, `env` or `default`), mention-eligible agents); secrets masked | `pkg/dashboard/api.go:250` | +| `PUT` | `/api/config/channels` | Owner only | Partial update of the same surfaces, plus `adminMcp.writesEnabled` (the `admin_mcp.writes_enabled` switch, which overrides `HIVE_ADMIN_MCP_ENABLE_WRITES` once set) or `adminMcp.writesFollowEnv: true` (clears it so the env or the default decides; sending both is a 400); a change is audited as `config_admin_mcp_writes`; validated against a copy so a 400 applies nothing; masked echo keeps a secret, empty clears it; hot-reloads mention poller and escalation sinks | `pkg/dashboard/api.go:251` | ## Agents and controls | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:151` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:155` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:156` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:157` | -| `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:158` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:159` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:160` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:161` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:162` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:163` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:164` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:165` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:166` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:170` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:187` | -| `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:188` | -| `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:255` | -| `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:542` | -| `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:545` | -| `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:546` | -| `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:550` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:152` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:156` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:157` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:158` | +| `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:159` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:160` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:161` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:162` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:163` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:164` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:165` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:166` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:167` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:171` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:188` | +| `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:189` | +| `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:256` | +| `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:543` | +| `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:546` | +| `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:547` | +| `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:551` | | `GET` | `/api/review/dispatch/events` | Dashboard auth/session | Webhook review dispatch queue: `enabled`, `webhooks_configured`, `debounce_s`, `pending` (soonest first) and `recent` (newest first) dispatches with repo, number, head SHA, action, timestamps and coalesced count, plus `stats` counters; in memory, never calls GitHub | `pkg/dashboard/api_review_event_dispatch.go:16` | -| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:554` | -| `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:555` | -| `GET` | `/api/search` | Merger or owner | Portfolio search over this spoke's local index (no hub fan-out). Query `q` (full text), `kind` and `repo` (`owner/name`; both repeatable or comma-separated), `from` (inclusive) and `to` (exclusive; a `YYYY-MM-DD` date covers that day) as RFC 3339 or `YYYY-MM-DD`, and `limit` (1–100, default 20); `probe=1` runs no query and is not audited, answering `204` when the index is ready. Returns `total`, highlighted `hits` (snippet plus byte `spans`) and `facets` by `kind`, `repo`, `verdict` and `sentinel.rule`; `coverage` names repos whose index could not be read. Hit text passes through ioscan, so injected text appears only as a visible redaction marker (`redacted: true`). The query string, actor and role are audited as `search_query`; result bodies are not. `404` unless `search.enabled`; `400` for bad parameters and for the reserved `semantic=true`; `503` while the index is not yet available | `pkg/dashboard/api.go:558` | -| `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:560` | -| `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:563` | -| `GET` | `/api/repos/{owner}/{repo}/health` | Dashboard auth/session | Report-only repo health score from the search index (`search.enabled`; `503` when off, `404` until the repo has indexed review evidence, `400` for a bad owner/repo). Recomputed on every index rebuild. Returns `score` (0–100, or `null` when no component is reported), `status`, `window_days` (90), `min_n` (10, the hub `minEvidenceN` rule), `computed_at` and `components[]` in order `ci_pass_rate`, `time_to_merge`, `revert_followup_rate`, `review_verdict_mix`, `stale_issue_ratio`, `signoff_rate`, `dependency_freshness`, `security_doc_rot`, each `{name, status, score (0–1), weight, contribution, n, inputs, reason}`. A component with `n` below `min_n` or without local data is `not_reported` (never zero) and the remaining weights are renormalised; weights and ages come from `search.health`. Spoke-only; never an ACMM input and never read by merge decisions or Governor priority. | `pkg/dashboard/api.go:564` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:337` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:338` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:339` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:340` | - -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:138` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:142` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:145` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:146` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:147` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:169` | +| `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:555` | +| `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:556` | +| `GET` | `/api/search` | Merger or owner | Portfolio search over this spoke's local index (no hub fan-out). Query `q` (full text), `kind` and `repo` (`owner/name`; both repeatable or comma-separated), `from` (inclusive) and `to` (exclusive; a `YYYY-MM-DD` date covers that day) as RFC 3339 or `YYYY-MM-DD`, and `limit` (1–100, default 20); `probe=1` runs no query and is not audited, answering `204` when the index is ready. Returns `total`, highlighted `hits` (snippet plus byte `spans`) and `facets` by `kind`, `repo`, `verdict` and `sentinel.rule`; `coverage` names repos whose index could not be read. Hit text passes through ioscan, so injected text appears only as a visible redaction marker (`redacted: true`). The query string, actor and role are audited as `search_query`; result bodies are not. `404` unless `search.enabled`; `400` for bad parameters and for the reserved `semantic=true`; `503` while the index is not yet available | `pkg/dashboard/api.go:559` | +| `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:561` | +| `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:564` | +| `GET` | `/api/repos/{owner}/{repo}/health` | Dashboard auth/session | Report-only repo health score from the search index (`search.enabled`; `503` when off, `404` until the repo has indexed review evidence, `400` for a bad owner/repo). Recomputed on every index rebuild. Returns `score` (0–100, or `null` when no component is reported), `status`, `window_days` (90), `min_n` (10, the hub `minEvidenceN` rule), `computed_at` and `components[]` in order `ci_pass_rate`, `time_to_merge`, `revert_followup_rate`, `review_verdict_mix`, `stale_issue_ratio`, `signoff_rate`, `dependency_freshness`, `security_doc_rot`, each `{name, status, score (0–1), weight, contribution, n, inputs, reason}`. A component with `n` below `min_n` or without local data is `not_reported` (never zero) and the remaining weights are renormalised; weights and ages come from `search.health`. Spoke-only; never an ACMM input and never read by merge decisions or Governor priority. | `pkg/dashboard/api.go:565` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:338` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:339` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:340` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:341` | + +| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:139` | +| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:143` | +| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:146` | +| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:147` | +| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:148` | +| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:170` | ### Kick is asynchronous @@ -306,80 +306,80 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:342` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:343` | -| `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:344` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:343` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:344` | +| `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:345` | | `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:362`, `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:363`, `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, job_id}` (`job_id` is the let-hive-decide job a record is for); `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:366`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR only (409 otherwise). The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:367`, `pkg/dashboard/api_repo_item_decision.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:367`, `pkg/dashboard/api_repo_hold.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR only (409 otherwise). The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:368`, `pkg/dashboard/api_repo_item_decision.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park}, notes, error}`); 409 with the running job while one is in flight; `GET` reads it, from memory while this process holds the job and otherwise from the operator-action ledger (`from_ledger: true`; status, requester, start, verdict and rule, with the outcome's words in `notes` or `error`), so the last result outlives the 30-minute in-memory eviction and a restart. A job still running when the hive restarts is never resumed: the next process marks its ledger record `failed` (*interrupted by a hive restart before it finished, and not resumed …*) with a `repo_item_decision_delegated_failed` audit entry, and the operator asks again. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:590`, `pkg/dashboard/api_repo_item_accept_triage.go` | -| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:382`, `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:383` | -| `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:384` | -| `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`, and on the needs-human advice `why` (plain-language reasons with counts) and `help`; `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:386`, `pkg/dashboard/api_hive_advice.go` | -| `POST` | `/api/repos/{owner}/{repo}/issues/{number}/release` | Owner or repo write/maintain/admin | Execute the typed `kind=release` owner step the hub proposed on a parked issue, with the same live preconditions as `/hive approve` ([#12635](https://github.com/hivecommons/hive/issues/12635)). Tag and target are resolved from the trusted owner-step, never from the request. Returns 503 when the GitHub client or config is unavailable; 409 when the repository is `label_driven` (the same refusal `/hive approve` gets there), when `release_on_approve` is off, or when a live precondition fails (`error` carries the refusal reason, which is also posted on the issue); 502 when the release write itself fails. Success returns `{ok, repo, number, tag, url, minStatusSeq}` plus `warning` if the follow-up issue comment failed after the release was created. | `pkg/dashboard/api.go:375`, `pkg/dashboard/api_issue_release.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:591`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:383`, `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:384` | +| `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:385` | +| `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`, and on the needs-human advice `why` (plain-language reasons with counts) and `help`; `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:387`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/issues/{number}/release` | Owner or repo write/maintain/admin | Execute the typed `kind=release` owner step the hub proposed on a parked issue, with the same live preconditions as `/hive approve` ([#12635](https://github.com/hivecommons/hive/issues/12635)). Tag and target are resolved from the trusted owner-step, never from the request. Returns 503 when the GitHub client or config is unavailable; 409 when the repository is `label_driven` (the same refusal `/hive approve` gets there), when `release_on_approve` is off, or when a live precondition fails (`error` carries the refusal reason, which is also posted on the issue); 502 when the release write itself fails. Success returns `{ok, repo, number, tag, url, minStatusSeq}` plus `warning` if the follow-up issue comment failed after the release was created. | `pkg/dashboard/api.go:376`, `pkg/dashboard/api_issue_release.go` | ## Cost, tokens, telemetry | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:94` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:173` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:174` | -| `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:175` | +| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:95` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:174` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:175` | +| `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:176` | | `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:181` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History; entries recorded since #13646 carry `yourTurnRootIssues` and `yourTurnRootPrs` | `pkg/dashboard/api.go:184` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:186` | -| `GET` | `/api/providers/headroom` | Dashboard auth/session | Providers Headroom | `pkg/dashboard/api.go:70` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:183` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:182` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History; entries recorded since #13646 carry `yourTurnRootIssues` and `yourTurnRootPrs` | `pkg/dashboard/api.go:185` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:187` | +| `GET` | `/api/providers/headroom` | Dashboard auth/session | Providers Headroom | `pkg/dashboard/api.go:71` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:184` | ## Knowledge | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `tag` (comma-separated; a fact must carry every tag), `state` (comma-separated lifecycle states or `all`; only facts in those states are listed, and any state other than `approved` requires a verified owner and returns 403 otherwise), `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:402` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:403` | -| `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:412` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:404` | -| `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:405` | -| `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:406` | -| `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:407` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:413` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:414` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:415` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:416` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:417` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:418` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:419` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:420` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:426` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:427` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:428` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:429` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:430` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:431` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:432` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:433` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:434` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:435` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:436` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:437` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:438` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:439` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:440` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:441` | +| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `tag` (comma-separated; a fact must carry every tag), `state` (comma-separated lifecycle states or `all`; only facts in those states are listed, and any state other than `approved` requires a verified owner and returns 403 otherwise), `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:403` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:404` | +| `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:413` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:405` | +| `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:406` | +| `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:407` | +| `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:408` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:414` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:418` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:420` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:421` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:427` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:428` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:429` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:430` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:431` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:432` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:433` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:434` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:435` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:436` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:437` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:438` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:439` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:440` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:441` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:442` | | `GET` | `/api/config/knowledge/connectors` | Dashboard auth/session | Knowledge connectors config (name, type, layer, scope, env/file auth reference) and registered types | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/connectors` | Owner only | Replace `knowledge.connectors` after validation; inline secrets rejected | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/connectors/status` | Dashboard auth/session | Per-connector status pill, last sync, pages/facts, last error, plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -387,36 +387,36 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `POST` | `/api/config/knowledge/connectors/{name}/sync` | Owner only | Start an immediate background sync of one connector | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/agent-scopes` | Dashboard auth/session | Per-agent knowledge scopes (`knowledge.agent_scopes`: layers, repos, types, tags, include_states) ([docs](knowledge-toc.md#per-agent-scopes)) | `pkg/dashboard/api.go` | | `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/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:451` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | -| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:456` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:457` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:458` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:459` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:460` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:461` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:462` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:453` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:454` | +| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:459` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:462` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:463` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:425` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:426` | | `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:451` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | -| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:456` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:457` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:458` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:459` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:460` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:461` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:462` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:453` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:454` | +| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:459` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:462` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:463` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:425` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:426` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:23` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/publish/sync` | Owner only | Run a publish mirror batch now (202 with publish status; 503 mirror not running, 409 batch in progress) | `pkg/dashboard/api_knowledge_connectors.go:25` | @@ -527,108 +527,108 @@ always resolved server-side from the validated token. | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:497` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:498` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:499` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:500` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:501` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:503` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:504` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:505` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:506` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:507` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:508` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:509` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:510` | -| `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:511` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:512` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:513` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:514` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:515` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:516` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:517` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:518` | -| `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:521` | -| `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:522` | -| `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:523` | -| `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:524` | -| `POST` | `/api/nous/promote` | Owner only | Nous Promote (manual verdict promotion to an issue or Spektacular run; see [experiment-lab.md](experiment-lab.md#verdict-card-and-manual-promote)) | `pkg/dashboard/api.go:502` | -| `POST` | `/api/nous/artifacts/sync` | Owner only | Nous Artifact Sync | `pkg/dashboard/api.go:519` | -| `POST` | `/api/nous/reset` | Owner only | Nous Reset (wipe baseline snapshots, learned knowledge or everything; see [experiment-lab.md](experiment-lab.md#resetting-data)) | `pkg/dashboard/api.go:520` | +| `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:498` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:499` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:500` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:501` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:502` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:504` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:505` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:506` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:508` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:509` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:510` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:511` | +| `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:512` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:515` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:516` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:517` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:518` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:519` | +| `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:522` | +| `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:523` | +| `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:524` | +| `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:525` | +| `POST` | `/api/nous/promote` | Owner only | Nous Promote (manual verdict promotion to an issue or Spektacular run; see [experiment-lab.md](experiment-lab.md#verdict-card-and-manual-promote)) | `pkg/dashboard/api.go:503` | +| `POST` | `/api/nous/artifacts/sync` | Owner only | Nous Artifact Sync | `pkg/dashboard/api.go:520` | +| `POST` | `/api/nous/reset` | Owner only | Nous Reset (wipe baseline snapshots, learned knowledge or everything; see [experiment-lab.md](experiment-lab.md#resetting-data)) | `pkg/dashboard/api.go:521` | ## Inception | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:467` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:468` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:469` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:470` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:471` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:472` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:473` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:474` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:475` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:476` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:477` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:478` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:479` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:480` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:469` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:470` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:471` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:473` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:474` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:475` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:476` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:477` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:478` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:479` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:480` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:481` | ## Beads | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:526` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:527` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:528` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:529` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:530` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:527` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:528` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:529` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:530` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:531` | ## Dashboard miscellaneous | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](audit-log.md#get-apiaudit) | `pkg/dashboard/api.go: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:537` | -| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:72` | -| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:73` | -| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:74` | -| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:79` | -| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:80` | -| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:81` | -| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:93` | -| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:95` | -| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:96` | -| `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:97` | - - -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:280` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:485` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:488` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:489` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:491` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:492` | +| `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:64` | +| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:538` | +| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:73` | +| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:74` | +| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:75` | +| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:80` | +| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:81` | +| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:82` | +| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:94` | +| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:96` | +| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:97` | +| `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:98` | + + +| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:281` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:486` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:489` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:490` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:492` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:493` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:219` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:220` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:221` | -| `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:323` | -| `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:324` | - -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:130` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:135` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:149` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:171` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:189` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:190` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:202` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `finisher` / `finisher_verb` / `finisher_reason` (who can finish the item, from the your-turn decision: `hive`, `person` when it is the operator's turn, `elsewhere` when it waits on someone else (a hold, a covering PR, a reporter, an open blocker, or its author on a returned PR or a person's draft), absent when the snapshot has no decision; also on each `linked_prs` entry), `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`). Standing meta issues (bot Dependency Dashboards and the Hive Advisory Report) are in `items` with `bucket` `dependency_dashboard` / `hive_advisory`, so `open_issues` equals the Overview tile, but the monitor never draws them as rows; `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; `merged` is the durable merged ledger's summary — `{today, total_7d, total_30d, all_time, recent: [≤20 × {repo, number, title, url, merged_at, merged_by (`hive` or a login), lane, issue}], tz, day_start}`, `today` rolling at midnight in the spoke's zone — behind the monitor's Merged chip. 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:203` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:205` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:400` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:464` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:465` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat. JSON body `{"query": "", "history": [...]}`; `message` is accepted as an alias for `query` (`query` wins when both are set). A missing or blank field returns 400 `query is required`. `!`-prefixed commands go to the chat spine (`{"accepted":true,"seq":N}`, read-write); while an inception is in `clarify` with unanswered questions, an owner's unprefixed reply also goes to the spine, which submits it as the answer to the next unanswered question. | `pkg/dashboard/api.go:494` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:532` | +| `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:324` | +| `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:325` | + +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:131` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:136` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:150` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:172` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:190` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:191` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:203` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `finisher` / `finisher_verb` / `finisher_reason` (who can finish the item, from the your-turn decision: `hive`, `person` when it is the operator's turn, `elsewhere` when it waits on someone else (a hold, a covering PR, a reporter, an open blocker, or its author on a returned PR or a person's draft), absent when the snapshot has no decision; also on each `linked_prs` entry), `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`). Standing meta issues (bot Dependency Dashboards and the Hive Advisory Report) are in `items` with `bucket` `dependency_dashboard` / `hive_advisory`, so `open_issues` equals the Overview tile, but the monitor never draws them as rows; `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; `merged` is the durable merged ledger's summary — `{today, total_7d, total_30d, all_time, recent: [≤20 × {repo, number, title, url, merged_at, merged_by (`hive` or a login), lane, issue}], tz, day_start}`, `today` rolling at midnight in the spoke's zone — behind the monitor's Merged chip. 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:204` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:206` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:401` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:465` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:466` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat. JSON body `{"query": "", "history": [...]}`; `message` is accepted as an alias for `query` (`query` wins when both are set). A missing or blank field returns 400 `query is required`. `!`-prefixed commands go to the chat spine (`{"accepted":true,"seq":N}`, read-write); while an inception is in `clarify` with unanswered questions, an owner's unprefixed reply also goes to the spine, which submits it as the answer to the next unanswered question. | `pkg/dashboard/api.go:495` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:533` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:362` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:363` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:364` | diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index c54d50b27f..b62508d26a 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -6,36 +6,36 @@ 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:151` | -| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:155` | -| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:156` | -| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:157` | -| `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:158` | -| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:159` | -| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:160` | -| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:161` | -| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:162` | -| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:163` | -| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:164` | -| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:165` | -| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:166` | -| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:170` | -| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:187` | -| `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:188` | -| `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:255` | -| `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:542` | -| `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:545` | -| `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:546` | -| `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:550` | +| `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:152` | +| `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:156` | +| `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:157` | +| `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:158` | +| `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:159` | +| `POST` | `/api/pause/{agent}` | Owner only | Pause | `pkg/dashboard/api.go:160` | +| `POST` | `/api/resume/{agent}` | Owner only | Resume | `pkg/dashboard/api.go:161` | +| `GET` | `/api/agent-state/{agent}` | Dashboard auth/session | Agent State | `pkg/dashboard/api.go:162` | +| `GET` | `/api/breaker` | Dashboard auth/session | Breaker State | `pkg/dashboard/api.go:163` | +| `POST` | `/api/breaker/engage` | Owner only | Breaker Engage | `pkg/dashboard/api.go:164` | +| `POST` | `/api/breaker/release` | Owner only | Breaker Release | `pkg/dashboard/api.go:165` | +| `POST` | `/api/pin/{agent}/{dimension}` | Owner only | Pin | `pkg/dashboard/api.go:166` | +| `POST` | `/api/unpin/{agent}/{dimension}` | Owner only | Unpin | `pkg/dashboard/api.go:167` | +| `POST` | `/api/restart/{agent}` | Owner only | Restart | `pkg/dashboard/api.go:171` | +| `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:188` | +| `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:189` | +| `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:256` | +| `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:543` | +| `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:546` | +| `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:547` | +| `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:551` | | `GET` | `/api/review/dispatch/events` | Dashboard auth/session | Webhook review dispatch queue: `enabled`, `webhooks_configured`, `debounce_s`, `pending` (soonest first) and `recent` (newest first) dispatches with repo, number, head SHA, action, timestamps and coalesced count, plus `stats` counters; in memory, never calls GitHub | `pkg/dashboard/api_review_event_dispatch.go:16` | -| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:554` | -| `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:555` | -| `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:560` | -| `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:563` | -| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:337` | -| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:338` | -| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:339` | -| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:340` | +| `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:555` | +| `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:556` | +| `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:561` | +| `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:564` | +| `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:338` | +| `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:339` | +| `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:340` | +| `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:341` | ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index f8773debdf..549ee37564 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:192` | -| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:193` | -| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:194` | -| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:195` | -| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:196` | -| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:197` | -| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:198` | +| `GET` | `/api/gh-auth` | Dashboard auth/session | GitHub Auth | `pkg/dashboard/api.go:193` | +| `GET` | `/api/gh-rate-limits` | Dashboard auth/session | GitHub Rate Limits | `pkg/dashboard/api.go:194` | +| `GET` | `/api/gh-user-auth/status` | Public | GitHub User Auth Status | `pkg/dashboard/api.go:195` | +| `POST` | `/api/gh-user-auth/start` | Public | GitHub User Auth Start | `pkg/dashboard/api.go:196` | +| `POST` | `/api/gh-user-auth/poll` | Public | GitHub User Auth Poll | `pkg/dashboard/api.go:197` | +| `POST` | `/api/gh-user-auth/logout` | Public | GitHub User Auth Logout | `pkg/dashboard/api.go:198` | +| `GET` | `/api/gh-user-auth/session` | Public | GitHub User Auth Session | `pkg/dashboard/api.go:199` | | `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` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index 52364115bd..047ca85b2a 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:526` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:527` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:528` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:529` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:530` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:527` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:528` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:529` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:530` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:531` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index b4fbb5f7fe..889a4091e0 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -6,116 +6,116 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `PUT` | `/api/config/triggers` | Verified owner only | Compile-to-bool and durably compare-and-save `{rules:[{name,agent,expr,priority}],preset?:{index,kind,repo}}` (preset `kind` is `issue.opened`, `pr.opened` or `ci.failed`; the server writes `event.kind == && event.repo == ` into rule `index`); 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/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:48` | -| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:49` | -| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:50` | +| `GET` | `/api/themes` | Dashboard auth/session | Embedded dashboard/contributor theme catalog with swatches for Settings → Appearance; `?scope=contributor` filters profile themes | `pkg/dashboard/api.go:49` | +| `GET` | `/api/theme.css` | Dashboard auth/session | Effective dashboard theme stylesheet with strong ETag / 304 support; `?theme=` previews an embedded preset; `?scope=contributor` emits contributor token aliases and layers hive custom CSS | `pkg/dashboard/api.go:50` | +| `GET` | `/api/config` | Dashboard auth/session | Config | `pkg/dashboard/api.go:51` | | `GET` | `/api/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` | -| `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:278` | -| `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:279` | +| `GET` | `/api/config/dashboard/theme` | Owner only | Dashboard theme selection, overrides, effective theme, and built-in catalog | `pkg/dashboard/api.go:60` | +| `PUT` | `/api/config/dashboard/theme` | Owner only | Persist `dashboard.theme` and `dashboard.theme_overrides` with validation, CSS/background guardrails, and audit logging | `pkg/dashboard/api.go:61` | +| `GET` | `/api/config/download` | Owner only | Config Download | `pkg/dashboard/api.go:52` | +| `GET` | `/api/config/sla` | Owner only | Delivery SLA targets: `{targets:{start_to_pr_h,pr_to_merge_h,open_to_merge_h}, effective_targets:{...}, defaults:{...}}`, hours, from `sla.targets` in `hive.yaml` with defaults 4/24/72 | `pkg/dashboard/api.go:279` | +| `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:280` | | `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` | -| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:58` | -| `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/provenance` | Owner only | Config Provenance | `pkg/dashboard/api.go:55` | +| `GET` | `/api/config/variables` | Dashboard auth/session | Variables List | `pkg/dashboard/api.go:56` | +| `GET` | `/api/config/authorized-users` | Dashboard auth/session | Authorized Users List | `pkg/dashboard/api.go:59` | +| `PUT` | `/api/config/variables/{name}` | Owner only | Variable Upsert | `pkg/dashboard/api.go:62` | +| `DELETE` | `/api/config/variables/{name}` | Owner only | Variable Delete | `pkg/dashboard/api.go:63` | -| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get; `general` carries the API proxy's GitHub API hourly cap: `githubApiHourlyCap` (this agent's `agents..github_api_hourly_cap`, `null` = inherit), `githubApiHourlyCapEffective` (the cap the proxy applies now; 0 = no cap), `githubApiHourlyCapFleet` (the fleet default) and `githubApiHourlyCapBase` (the base agent of a replica or review head, else empty) | `pkg/dashboard/api.go:207` | -| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General; `githubApiHourlyCap` sets `agents..github_api_hourly_cap` (a whole number, 0 = no cap, `null` = inherit the fleet default), applies to the proxy without a restart and to the agent's replicas and review heads; refused (400) on a replica or review head. Audited as `config_agent_general` with the old and new cap | `pkg/dashboard/api.go:208` | -| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:209` | -| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:210` | -| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:211` | -| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:212` | -| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:213` | -| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:214` | -| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:215` | -| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:216` | -| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:217` | -| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:218` | -| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:219` | -| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:220` | +| `GET` | `/api/config/agent/{name}` | Dashboard auth/session | Agent Config Get; `general` carries the API proxy's GitHub API hourly cap: `githubApiHourlyCap` (this agent's `agents..github_api_hourly_cap`, `null` = inherit), `githubApiHourlyCapEffective` (the cap the proxy applies now; 0 = no cap), `githubApiHourlyCapFleet` (the fleet default) and `githubApiHourlyCapBase` (the base agent of a replica or review head, else empty) | `pkg/dashboard/api.go:208` | +| `PUT` | `/api/config/agent/{name}/general` | Owner only | Agent Config General; `githubApiHourlyCap` sets `agents..github_api_hourly_cap` (a whole number, 0 = no cap, `null` = inherit the fleet default), applies to the proxy without a restart and to the agent's replicas and review heads; refused (400) on a replica or review head. Audited as `config_agent_general` with the old and new cap | `pkg/dashboard/api.go:209` | +| `PUT` | `/api/config/agent/{name}/cadences` | Owner only | Agent Config Cadences; each mode sent becomes operator-owned (`governor.cadence_owners`). Wrapped by the admin MCP `agent.cadences` operation | `pkg/dashboard/api.go:210` | +| `PUT` | `/api/config/agent/{name}/models` | Owner only | Agent Config Models | `pkg/dashboard/api.go:211` | +| `PUT` | `/api/config/agent/{name}/pipeline` | Owner only | Agent Config Pipeline | `pkg/dashboard/api.go:212` | +| `PUT` | `/api/config/agent/{name}/hooks` | Owner only | Agent Config Hooks | `pkg/dashboard/api.go:213` | +| `PUT` | `/api/config/agent/{name}/restrictions` | Owner only | Agent Config Restrictions | `pkg/dashboard/api.go:214` | +| `PUT` | `/api/config/agent/{name}/stats` | Owner only | Agent Config Stats | `pkg/dashboard/api.go:215` | +| `GET` | `/api/config/agent/{name}/prompt` | Dashboard auth/session | Agent Prompt | `pkg/dashboard/api.go:216` | +| `PUT` | `/api/config/agent/{name}/prompt` | Owner only | Agent Prompt Save | `pkg/dashboard/api.go:217` | +| `GET` | `/api/config/agent/{name}/export` | Dashboard auth/session | Agent Export | `pkg/dashboard/api.go:218` | +| `PUT` | `/api/config/agent/{name}/channels` | Owner only | Agent Config Channels | `pkg/dashboard/api.go:219` | +| `PUT` | `/api/config/agent/{name}/tools` | Owner only | Agent Config Tools | `pkg/dashboard/api.go:220` | +| `PUT` | `/api/config/agent/{name}/connections` | Owner only | Agent Config Connections | `pkg/dashboard/api.go:221` | | `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:221` | -| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:223` | +| `GET` | `/api/config/stat-sources` | Dashboard auth/session | Stat Sources | `pkg/dashboard/api.go:222` | +| `GET` | `/api/config/governor` | Dashboard auth/session | Governor Config Get | `pkg/dashboard/api.go:224` | | `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:227` | -| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:228` | -| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:235` | -| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:236` | -| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:240` | -| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:241` | -| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:257` | -| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:258` | -| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:259` | -| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:260` | -| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:261` | +| `PUT` | `/api/config/governor/sensing` | Owner only | Governor Sensing | `pkg/dashboard/api.go:228` | +| `PUT` | `/api/config/governor/thresholds` | Owner only | Governor Thresholds | `pkg/dashboard/api.go:229` | +| `PUT` | `/api/config/governor/labels` | Owner only | Governor Labels | `pkg/dashboard/api.go:236` | +| `PUT` | `/api/config/governor/budget` | Owner only | Governor Budget | `pkg/dashboard/api.go:237` | +| `PUT` | `/api/config/governor/notifications` | Owner only | Governor Notifications | `pkg/dashboard/api.go:241` | +| `PUT` | `/api/config/governor/health` | Owner only | Governor Health | `pkg/dashboard/api.go:242` | +| `PUT` | `/api/config/governor/logging` | Owner only | Governor Logging | `pkg/dashboard/api.go:258` | +| `PUT` | `/api/config/governor/attribution` | Owner only | Governor Attribution | `pkg/dashboard/api.go:259` | +| `PUT` | `/api/config/governor/hub` | Owner only | Governor Hub | `pkg/dashboard/api.go:260` | +| `PUT` | `/api/config/governor/litellm` | Owner only | Governor Lite LLM | `pkg/dashboard/api.go:261` | +| `PUT` | `/api/config/governor/trajectory` | Owner only | Governor Trajectory | `pkg/dashboard/api.go:262` | | `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:308` | -| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:309` | -| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:310` | +| `GET` | `/api/config/governor/bob` | Dashboard auth/session | Governor Bob Status | `pkg/dashboard/api.go:309` | +| `PUT` | `/api/config/governor/bob` | Owner only | Governor Bob Key | `pkg/dashboard/api.go:310` | +| `DELETE` | `/api/config/governor/bob` | Owner only | Governor Bob Key Clear | `pkg/dashboard/api.go:311` | -| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:229` | -| `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:230` | -| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:312` | -| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:313` | -| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:316` | -| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:317` | -| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:318` | -| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:319` | -| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:320` | -| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:325` | -| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:326` | -| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:327` | -| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:331` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:332` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:335` | -| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:395` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:396` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:397` | -| `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:387` | -| `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:388` | -| `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:389` | -| `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:390` | -| `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:391` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:392` | -| `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:393` | -| `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:571` | +| `GET` | `/api/config/governor/cadence-scope` | Owner only | Governor Cadence Scope Get (`aggregate` or `per_repo`) | `pkg/dashboard/api.go:230` | +| `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:231` | +| `POST` | `/api/config/governor/bob/test` | Dashboard auth/session | Governor Bob Key Test | `pkg/dashboard/api.go:313` | +| `POST` | `/api/config/governor/litellm/test` | Dashboard auth/session | Governor Lite LLMTest | `pkg/dashboard/api.go:314` | +| `GET` | `/api/config/governor/gateways` | Dashboard auth/session | Governor Gateways List | `pkg/dashboard/api.go:317` | +| `PUT` | `/api/config/governor/gateways` | Owner only | Governor Gateways Upsert | `pkg/dashboard/api.go:318` | +| `DELETE` | `/api/config/governor/gateways/{name}` | Owner only | Governor Gateways Delete | `pkg/dashboard/api.go:319` | +| `POST` | `/api/config/governor/gateways/{name}/test` | Dashboard auth/session | Governor Gateways Test | `pkg/dashboard/api.go:320` | +| `POST` | `/api/config/governor/gateways/discover` | Owner only | Governor Gateways Discover | `pkg/dashboard/api.go:321` | +| `POST` | `/api/config/governor/agents` | Owner only | Governor Add Agent | `pkg/dashboard/api.go:326` | +| `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:327` | +| `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:328` | +| `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:332` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:333` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:336` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:396` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:397` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:398` | +| `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:388` | +| `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:389` | +| `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:390` | +| `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:391` | +| `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:392` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:393` | +| `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:394` | +| `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:572` | -| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:232` | -| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:233` | -| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:234` | -| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:237` | -| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:242` | -| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:245` | -| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:246` | -| `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:567` | -| `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:568` | -| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | -| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:262` | -| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | -| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | -| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:269` | +| `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:233` | +| `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:234` | +| `PUT` | `/api/config/governor/coverage-target` | Owner only | Governor Coverage Target | `pkg/dashboard/api.go:235` | +| `POST` | `/api/config/governor/budget/reset` | Owner only | Governor Budget Reset | `pkg/dashboard/api.go:238` | +| `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:243` | +| `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:246` | +| `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:247` | +| `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:568` | +| `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:569` | +| `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:254` | +| `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:257` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:263` | +| `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:264` | +| `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:265` | +| `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:270` | | `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:275` | -| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | -| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:281` | -| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:282` | -| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:283` | -| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:284` | +| `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:276` | +| `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:278` | +| `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:282` | +| `PUT` | `/api/config/governor/advisory` | Owner only | Governor Advisory Set | `pkg/dashboard/api.go:283` | +| `GET` | `/api/config/governor/replan` | Owner only | Governor Replan Get | `pkg/dashboard/api.go:284` | +| `PUT` | `/api/config/governor/replan` | Owner only | Governor Replan Set | `pkg/dashboard/api.go:285` | | `GET` | `/api/config/decisions/delegate` | Owner only | "Let hive decide" settings (`decisions.delegate`) with defaults resolved: `enabled` (unset = on), `enabled_set`, `repos` (`{owner/repo: {enabled}}`), `llm` (`{enabled, model, model_masked}`; unset = off), `llm_reviewer_ready` and `llm_model_effective` (the decider turn's model; the endpoint and its key are never returned), `effect_timeout`, `effect_timeout_effective`, `project_repos`. A stored `llm.model` that looks like a key is masked | `pkg/dashboard/api_config_decisions_delegate.go` | | `PUT` | `/api/config/decisions/delegate` | Owner only | Change `decisions.delegate`: `enabled`, `repos` (the full override map when sent; an entry with `enabled: null` is dropped; a new key must be in `project.repos`), `llm.enabled`, `llm.model` (a model name; a key-like value is refused) and `effect_timeout`. Unknown fields and invalid values are 400 with nothing changed. Saved, audited as `config_decisions_delegate` with the actor and each change before and after, and applied without a restart. Starts no decision and merges nothing | `pkg/dashboard/api_config_decisions_delegate.go` | -| `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:294` | -| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:295` | -| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:296` | -| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:298` | -| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:299` | -| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:314` | -| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:315` | +| `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:295` | +| `PUT` | `/api/config/governor/work-source` | Owner only | Governor Work Source Set (including Jira Data Center TLS settings) | `pkg/dashboard/api.go:296` | +| `PUT` | `/api/config/governor/security` | Owner only | Governor Security; `sentinel.repoSensitivePaths` (`{owner/repo: [globs] or null}`) sets or clears single repositories' own Sentinel list (`project.repo_policies[].sentinel_sensitive_paths`; `[]` flags no path, `null` returns to the hive-wide list) and leaves repositories it does not name, and the hive-wide `sensitivePaths`, unchanged; a blank or malformed glob or a repository outside `project.repos` is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:297` | +| `GET` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Get | `pkg/dashboard/api.go:299` | +| `PUT` | `/api/config/governor/project-observability` | Owner only | Governor Project Observability Set | `pkg/dashboard/api.go:300` | +| `GET` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Get | `pkg/dashboard/api.go:315` | +| `PUT` | `/api/config/governor/inference-auth` | Owner only | Governor Inference Auth Set | `pkg/dashboard/api.go:316` | diff --git a/src/docs/api-reference/cost-tokens-telemetry.md b/src/docs/api-reference/cost-tokens-telemetry.md index 559cc547eb..76a219d205 100644 --- a/src/docs/api-reference/cost-tokens-telemetry.md +++ b/src/docs/api-reference/cost-tokens-telemetry.md @@ -5,16 +5,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:94` | -| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:173` | -| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:174` | -| `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:175` | +| `GET` | `/api/trends` | Dashboard auth/session | Trends | `pkg/dashboard/api.go:95` | +| `GET` | `/api/token-access` | Dashboard auth/session | Token Access | `pkg/dashboard/api.go:174` | +| `GET` | `/api/tokens` | Dashboard auth/session | Tokens | `pkg/dashboard/api.go:175` | +| `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:176` | | `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:181` | -| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:184` | -| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:186` | -| `GET` | `/api/providers/headroom` | Dashboard auth/session | Providers Headroom | `pkg/dashboard/api.go:70` | -| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:183` | +| `GET` | `/api/cost/history` | Dashboard auth/session | Cost History | `pkg/dashboard/api.go:182` | +| `GET` | `/api/trend/history` | Dashboard auth/session | Trend History | `pkg/dashboard/api.go:185` | +| `GET` | `/api/timeseries` | Dashboard auth/session | Time Series | `pkg/dashboard/api.go:187` | +| `GET` | `/api/providers/headroom` | Dashboard auth/session | Providers Headroom | `pkg/dashboard/api.go:71` | +| `GET` | `/api/budget/history` | Dashboard auth/session | Budget History | `pkg/dashboard/api.go:184` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 0ea1adc9b5..9d9adda891 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -24,49 +24,49 @@ 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:537` | -| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:72` | -| `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:75` | -| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:73` | -| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:74` | -| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:79` | -| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:80` | -| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:81` | -| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:93` | -| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:95` | -| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:96` | -| `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:97` | - - -| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:280` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:485` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:488` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:489` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:491` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:492` | +| `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:64` | +| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:538` | +| `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:73` | +| `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:76` | +| `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:74` | +| `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:75` | +| `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:80` | +| `POST` | `/api/backup` | Owner only | Backup Download — `412` when no encryption key is configured (never an unencrypted archive) | `pkg/dashboard/api.go:81` | +| `POST` | `/api/banner-dismissed` | Dashboard auth/session | Banner Dismissed | `pkg/dashboard/api.go:82` | +| `GET` | `/api/history` | Dashboard auth/session | History | `pkg/dashboard/api.go:94` | +| `GET` | `/api/timeline` | Dashboard auth/session | Timeline | `pkg/dashboard/api.go:96` | +| `GET` | `/api/lifecycle-timeline` | Dashboard auth/session | Issue→PR lifecycle journeys plus derived stage timeline. Each journey keeps the dense `stages` map and adds a backwards-compatible `details` object for expandable rows: chronological stages with durations, current-stage age, agent, classification attrs, issue/PR links, blocked reason, and kick/run identifiers when recorded. | `pkg/dashboard/api.go:97` | +| `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:98` | + + +| `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:281` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:486` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:489` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:490` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:492` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:493` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:219` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:220` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:221` | -| `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:323` | -| `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:324` | - -| `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:581` | -| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:130` | -| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:135` | -| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:149` | -| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:171` | -| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:189` | -| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:190` | -| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:202` | -| `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:203` | -| `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:204` | -| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:205` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:400` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:464` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:465` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:494` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:532` | +| `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:324` | +| `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:325` | + +| `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:582` | +| `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:131` | +| `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:136` | +| `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:150` | +| `POST` | `/api/reset-restarts/{agent}` | Owner only | Reset Restarts | `pkg/dashboard/api.go:172` | +| `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:190` | +| `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:191` | +| `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:203` | +| `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:204` | +| `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:205` | +| `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:206` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:401` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:465` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:466` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:495` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:533` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:362` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:363` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:364` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index b6f2cadf98..5fedb04511 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -21,9 +21,9 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:45` | -| `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | -| `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:76` | +| `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:46` | +| `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:47` | +| `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:77` | | `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1827` | | `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1828` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1829` | @@ -44,30 +44,30 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/swarm/themes` | Owner only | Set a per-repo swarm theme (`event_name`, `call_to_arms`, `leaderboard_title`). | `pkg/dashboard/swarm.go:316` | | `PATCH` | `/api/swarm/objectives` | Owner only | Update the active swarm SDLC objective checklist completion state. | `pkg/dashboard/swarm.go:317` | | `GET` | `/api/leaderboard/swarm` | Public | Stable public JSON record of swarm history, leaderboard, top players, and achievements. | `pkg/dashboard/swarm.go:318` | -| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:98` | -| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:99` | -| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:100` | -| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:104` | -| `POST` | `/api/runs/{key}/checkpoint` | Owner only | Resolve a compact checkpoint decision. Body `{"action":"approve"|"reject","gen":}`; refuses stale generations with 409 and non-owner callers with 403 before mutating the plan. | `pkg/dashboard/api.go:105` | -| `GET` | `/api/runs/{key}` | Dashboard auth/session | One run by URL-escaped canonical run key (`owner/repo%23number`); early lease-shaped keys (`repo!run-key:stage`) and queued Wavefront run-stage keys (`owner/repo!graph:node`) are also accepted. Includes timeline-derived stage history in the same `Run` shape as `/api/runs` when a lease/timeline exists. History entries that came from an owner reset carry the owner's `reason`. When the key belongs to a wired convergence campaign, the detail response also includes an optional `burndown` block with `source`, `satisfied`, `remaining`, `unknown`, and `scope`; the list endpoint omits this block. | `pkg/dashboard/api.go:108` | -| `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:110` | -| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:111` | -| `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:112` | -| `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:113` | -| `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:114` | -| `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:115` | -| `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:116` | -| `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:117` | -| `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:118` | -| `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:119` | -| `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:120` | -| `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:121` | -| `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:122` | -| `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:123` | -| `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:124` | -| `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:125` | -| `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:126` | -| `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:127` | -| `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:128` | -| `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:129` | -| `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:101` | +| `GET` | `/api/runs` | Dashboard auth/session | Active staged runs projected from task leases, plans, and lifecycle timeline. Returns an array of `Run` objects: canonical `key` (`owner/repo#number`), current-stage `lease_key`, `title`, `repo` (`owner/repo`), `stage`, `gen`, `stage_started_at`, `waiting_on` (`agent`, `remote`, `human`, `ci`, `none`), `waiting_since`, `assignee`, `last_receipt`, `plan_epic_id`, and `stages[]` (`name`, `status`, `gen`, `receipt`). | `pkg/dashboard/api.go:99` | +| `GET` | `/api/runs/audit` | Owner only | Read-only cross-repo audit query over existing retained artifacts. Query `repo`, canonical `run` (`owner/repo#number`), RFC3339 `since`/`until`, `kind`, `limit` (default 100, max 500), and `page_token`. Returns `{items,next_page_token,retention}`; each item has `source` (`audit_log`, `timeline`, `lease_receipt`, `plan_epic`), `kind`, `run`, `repo`, `at`, `actor`, `artifact_id`, `attrs`, or an explicit `kind=expired,status=expired,state=Unknown` marker when requested history may have aged out. | `pkg/dashboard/api.go:100` | +| `POST` | `/api/runs/audit` | Owner only | Activate the convergence audit campaign over a scope directory. Body `{"campaign_key":"audit-campaign","scope_dir":"/data/convergence/audit/scope","store":"audit","generation":1,"run_key":"","run_url":""}`; `scope_dir` defaults to `/data/convergence/audit/scope`, `store` defaults to `audit`, `auditor`, `scanner`, `supervisor`, then the first configured bead store. Runs inspection even when `publication.enabled` is false, but then skips the publisher and returns `publication_skipped:true` with reason `publication.disabled`. | `pkg/dashboard/api.go:101` | +| `GET` | `/api/runs/{key}/checkpoint` | Dashboard auth/session | Compact mobile/chat checkpoint review payload for a held run. Returns `run_key`, `stage`, lease `gen`, `repo`, `title`, capped plain-text `summary`, approve/reject `decisions`, dashboard deep link, `lease_gen` staleness fence, and verified-owner approver rule. | `pkg/dashboard/api.go:105` | +| `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:106` | +| `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:109` | +| `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:111` | +| `GET` | `/api/campaigns` | Dashboard auth/session | List resumable campaigns from archived Inception sessions and retained Spektacular (Spek) runs. Query `search`/`q`, `repo`, `stage`, `status`, and `owner`; each campaign is keyed by stable spec/session id and includes title, source, repos, current stage/step, artifact links, linked issues/PRs, contributors, last activity, status, engine, type, run link when applicable, `superseded_by` when a newer Revise revision exists, and recheck status (`enabled`, `interval`, `last_at`, `next_at`, `in_flight`, `last_delta_count`, `external_count`, `sources_failed`). | `pkg/dashboard/api.go:112` | +| `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:113` | +| `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:114` | +| `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:115` | +| `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:116` | +| `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:117` | +| `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:118` | +| `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:119` | +| `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:120` | +| `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:121` | +| `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:122` | +| `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:123` | +| `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:124` | +| `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:125` | +| `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:126` | +| `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:127` | +| `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:128` | +| `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:129` | +| `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:130` | +| `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:102` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index dfd77a32a5..ce9f4ce88e 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:467` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:468` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:469` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:470` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:471` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:472` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:473` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:474` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:475` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:476` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:477` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:478` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:479` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:480` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:469` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:470` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:471` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:473` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:474` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:475` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:476` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:477` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:478` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:479` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:480` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:481` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index 4d7a165173..b315fc8ed5 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:402` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:403` | -| `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:412` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:404` | -| `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:405` | -| `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:406` | -| `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:407` | -| `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:409` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:413` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:414` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:415` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:416` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:417` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:418` | -| `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:419` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:420` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:426` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:427` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:428` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:429` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:430` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:431` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:432` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:433` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:434` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:435` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:436` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:437` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:438` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:439` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:440` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:441` | +| `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:403` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:404` | +| `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:413` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:405` | +| `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:406` | +| `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:407` | +| `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:408` | +| `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:410` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:414` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:418` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:419` | +| `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:420` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:421` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:427` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:428` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:429` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:430` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:431` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:432` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:433` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:434` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:435` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:436` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:437` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:438` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:439` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:440` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:441` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:442` | | `GET` | `/api/config/knowledge/connectors` | Dashboard auth/session | Knowledge connectors config (name, type, layer, scope, env/file auth reference) and registered types | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/connectors` | Owner only | Replace `knowledge.connectors` after validation; inline secrets rejected | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/connectors/status` | Dashboard auth/session | Per-connector status pill, last sync, pages/facts, last error, plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -46,20 +46,20 @@ 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:451` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | -| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:456` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:457` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:458` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:459` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:460` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:461` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:462` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:453` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:454` | +| `PUT` | `/api/knowledge/git-sources` | Owner only | Git Sources Update | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:459` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:462` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:463` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:425` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:426` | | `GET` | `/api/knowledge/connectors` | Dashboard auth/session | Knowledge connector statuses and publish mirror status (`{"connectors": [...], "publish": {...}\|null}`, see [knowledge-connectors.md](../knowledge-connectors.md)) | `pkg/dashboard/api_knowledge_connectors.go:23` | | `POST` | `/api/knowledge/connectors/{name}/sync` | Owner only | Start one connector sync now (202; 404 unknown, 409 running) | `pkg/dashboard/api_knowledge_connectors.go:24` | | `POST` | `/api/knowledge/publish/sync` | Owner only | Run a publish mirror batch now (202 with publish status; 503 mirror not running, 409 batch in progress) | `pkg/dashboard/api_knowledge_connectors.go:25` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index 3fc718959c..ffafe72ff7 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:497` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:498` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:499` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:500` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:501` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:503` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:504` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:505` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:506` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:507` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:508` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:509` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:510` | -| `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:511` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:512` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:513` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:514` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:515` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:516` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:517` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:518` | -| `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:521` | -| `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:522` | -| `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:523` | -| `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:524` | +| `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:498` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:499` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:500` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:501` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:502` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:504` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:505` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:506` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:508` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:509` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:510` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:511` | +| `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:512` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:515` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:516` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:517` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:518` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:519` | +| `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:522` | +| `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:523` | +| `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:524` | +| `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:525` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index e4c37bdf6f..0647f6358c 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:342` | -| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:343` | -| `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:344` | +| `GET` | `/api/packs` | Dashboard auth/session | Packs List | `pkg/dashboard/api.go:343` | +| `POST` | `/api/packs/{level}/apply` | Owner only | Pack Apply | `pkg/dashboard/api.go:344` | +| `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:345` | | `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:362`, `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:363`, `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:366`, `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:367`, `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:371`, `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:372`, `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:373`, `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:367`, `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:368`, `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:372`, `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:373`, `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:374`, `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:377`, `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:378` | -| `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:380` | -| `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:590`, `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:368`, `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:382`, `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:383` | -| `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:384` | -| `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:386`, `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:378`, `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:379` | +| `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:381` | +| `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:591`, `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:369`, `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:383`, `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:384` | +| `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:385` | +| `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:387`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 486d69b0cd..f076a52e02 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | +| `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:48` | | `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1922` | -| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | -| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | -| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | +| `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:91` | +| `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:92` | +| `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:93` | diff --git a/src/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index 60358c542f..c98e896da6 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -34,7 +34,9 @@ state it fills. One workflow serving several triggers binds to each role its tri | Package | Role | |---|---| -| `pkg/workflowmodel` | types, `Validate`, `Hash`, `HiveDefault`, `Bind`, topological `Levels` | +| `pkg/workflowmodel` | types, `Validate`, `Hash`, `HiveDefault`, `Bind`, topological `Levels`, `Compile` → `Profile` | +| `pkg/workflowmodel/hivedefault` | `Generate()` the `hive-default` model from `stagelabels.Table` + `stageengine.DiagramEdges()`; `Profile()` compiled | +| `pkg/stageengine` (`workflow.go`) | `DeriveFromModel(profile, kind)`: builtin delegation or the rules evaluator; `Options.Workflow` | | `pkg/workflowmodel/githubactions` | `.github/workflows/*.y*ml` → pipelines | | `pkg/workflowmodel/tekton` | Pipeline / PipelineRun / Task (+ Pipelines-as-Code annotations) → pipelines | | `pkg/workflowmodel/ingest` | `Repository(scope, files)`: route files to ingesters, compose, bind | @@ -62,6 +64,35 @@ golden summary per repository; `go test ./pkg/workflowmodel/ingest -update` rewr after an intended change. The full 317-repository CNCF-landscape survey and its collector live outside the repository; the results are on #17620. +## Lifecycle half and the compiler (RFC phase 1) + +The RFC (#17620) asks for one engine that derives under any model. The decision that keeps v5/v6 +byte-identical is that **`hive-default` derivation stays in Go**: `hivedefault.Generate()` builds +the model from the stage table, the engine's expected edges and the monitor's column anchors, and +declares `derivation: builtin`. `stageengine.DeriveFromModel` then delegates to `IssueDeriver` / +`PRDeriver` and only checks coverage — a stage the model has no state for abstains with +`workflow: not covered` instead of writing a label the model does not know. The parity test +(`TestDeriveFromModelHiveDefaultParity`) runs every PR stage golden and an issue sweep through both +and requires identical `Decision`s. + +Custom models declare `derivation: rules`: ordered rules, each a conjunction of predicates over the +fact vocabulary in `workflowmodel.Facts` (`open`, `merged`, `draft`, `labels has stage/*`, +`author.kind is human`, `pr.checks is green`, `pr.review is approved`, `issue.covered`, …); the +first rule whose predicates all hold names the state, and an item no rule matches is not covered. +Rules reach only the facts the engine already computes; no LLM is ever in the derivation path. +`testdata/models/techdocs.json` is the hand-written reference model (cncf/techdocs engagement). + +`Compile` refuses (error diagnostics, no profile): `state-no-exit`, `gate-no-owner`, +`agent-no-human-gate` (every path from an agent-granted state to a terminal outcome must cross a +transition gated by a role with `human: true`; closure edges — the item closed unmerged — are +observations and exempt), `duplicate-event-fact`, `state-no-column` / `unknown-column`, +`duplicate-stage-number`, `unknown-fact` / `bad-op`, `no-rules`, `no-version`. Elements marked +`confidence: inferred` compile with an `inferred-element` warning the editor shows. + +Stage numbers in a model are Hive's label numbers (`stagelabels.Table`) for now, so a bound repo's +labels, tracker anchors and replies keep working; a state whose number does not apply to the item +kind is not covered. Models are whole (no inheritance) through phase 4. + ## Known gaps (phase 1) - Prow (`kubernetes/*`) is a third syntax not read; those repos render the default columns. @@ -70,3 +101,57 @@ outside the repository; the results are on #17620. - Pipelines-as-Code `on-cel-expression` triggers are recorded as `cel` events and not classified into roles, so a tag-push expressed in CEL does not add *Release*. - Bare Tekton `Pipeline` library files (catalogs) have no trigger and bind nowhere (`no-trigger`). + +## Store, bindings and engine wiring (RFC phase 2) + +- **Store** (`pkg/workflowmodel/store`): `/workflows//.json` plus an + `index.json` rebuilt on write; names/versions are regex-guarded, writes are atomic. + `hive-default` is virtual and read-only. Drafts (models that do not compile) save but + `Profile()` returns `ErrNotCompiled`. Entries reserve `adoption`, `ratings`, `benchmarks` + (raw JSON, carried verbatim) so the phase-7 marketplace can add them without a migration. +- **Binding** (`pkg/config/workflow_binding.go`): `project.workflow_bindings: [{repo, name, + version}]`, mirroring `repo_policies`. `WorkflowBindingFor` is keyed like repo pauses + (lowercased, org-qualified) and reads the live config, so a PUT takes effect without a + restart. Binding requires the model to compile; deleting a bound model is a 409. +- **API** (`pkg/dashboard/api_workflows.go`): `GET/POST /api/workflows`, `POST + /api/workflows/compile`, `GET/PUT /api/workflows/bindings`, `GET/PUT/DELETE + /api/workflows/{name}/{version}`. Writes need the owner role and are audited; 503 when no + store is configured. +- **Engine**: `stageengine.Options.WorkflowFor(owner, repo) *Profile` and `DeriveForRepo` (a + per-profile, hash-cached deriver) route bound repositories through `DeriveFromModel`; unbound + repositories and `workflow.enabled: false` take the builtin path unchanged. An unusable + binding (missing or non-compiling model) warns once and falls back. +- **Tracker**: the response gains `workflows: {default: {...}, repos: {: {name, version, + columns, numbers, error}}}` (nil when nothing is bound). The JS labels the model column, + renders a per-row column strip by stage number, and shows an amber "Not covered" chevron for + abstentions. Settings → Repos has a per-repo Workflow select that PUTs the binding. + +## Ingest → lifecycle (RFC phase 3a) + +`ingest.Repository` (phase 0) is unchanged and still produces the process half. `ingest.Lifecycle` +composes on top of it: + +1. Start from `hivedefault.Generate()` — the compiled hive-default lifecycle, `derivation: builtin`. +2. Copy the ingested pipelines, sources and coverage; `meta.source` is the system(s) read, + `meta.provenance` is `ingested-unreviewed`, `meta.version` is `1` (the store assigns later + versions). +3. PR-verify pipelines are bound to every state in the CI / Review column, each with a citation to + the file the pipeline came from. +4. Every post-merge state the process half produced (main CI, release, `deploy-`, done) + becomes a state in its own column after Merged, `confidence: inferred`, with the environment + guards carried over. The chain's transitions fire on `pipeline-succeeded` = + `pipeline.status is green`. The engine does not observe post-merge runs yet and reports + `unknown` for that fact, so a bound ingested model derives exactly like hive-default today; + the extra columns render, nothing lands in them until post-merge observation exists. + +The compiler warns once per inferred element; a human confirming them in the editor (phase 4) +is what moves provenance to `local`/`curated`. + +`POST /api/workflows/ingest` is the spoke entry point (owner role): `{repo}` fetches the default +branch through `FetchDefaultBranchTree`, `ingest.ReadTree` keeps GitHub Actions workflows, YAML +under Tekton directories and pipeline-named YAML that looks like Tekton (the survey collector's +rules), and the checkout is removed. `{files}` accepts pasted definitions. `save: true` stores the +result at the next integer version under `name` (default: the repository slug). + +`cmd/workflow-survey` now compiles every corpus repository's lifecycle model (`lifecycle.json` +alongside `model.json`) and reports pass/refusal counts by diagnostic code. diff --git a/src/internal/testutil/dashboard_import_allowlist.txt b/src/internal/testutil/dashboard_import_allowlist.txt index ad84e68b32..0ea7bc5740 100644 --- a/src/internal/testutil/dashboard_import_allowlist.txt +++ b/src/internal/testutil/dashboard_import_allowlist.txt @@ -21,6 +21,7 @@ # crux/logscrub: pkg/logscrub moved into the Crux module with the cut (hivecommons/hive#13950). # search: GET /api/repos/{owner}/{repo}/health serves the report-only repo health score the search indexer computes (search.Health), wired through a setter so the dashboard never builds or walks the index (hivecommons/hive#14638). # search: GET /api/search reads the portfolio search Backend the indexer publishes; pkg/search is a leaf (no dashboard deps) (hivecommons/hive#14637). +# workflowmodel: /api/workflows handlers compile lifecycle models (Compile, Profile diagnostics) and the tracker emits per-repo workflow columns; the store and bindings already route through Dependencies (hivecommons/hive#17620 P2). github.com/hivecommons/hive/crux github.com/hivecommons/hive/crux/agent github.com/hivecommons/hive/crux/agentparse @@ -98,5 +99,6 @@ github.com/hivecommons/hive/pkg/tokens github.com/hivecommons/hive/pkg/turn github.com/hivecommons/hive/pkg/upstreamwatch github.com/hivecommons/hive/pkg/webassets +github.com/hivecommons/hive/pkg/workflowmodel github.com/hivecommons/hive/pkg/worksource github.com/hivecommons/hive/pkg/writeback diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 5229e99df7..1d20038166 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -82,8 +82,13 @@ type Config struct { // Dedupe tunes the dedupe lane's follow-through on its checklists. Dedupe DedupeLaneConfig `yaml:"dedupe,omitempty" json:"dedupe,omitempty"` Contribute ContributeConfig `yaml:"contribute,omitempty" json:"contribute,omitempty"` - HiveID string `yaml:"hive_id"` - ACMMLevel *int `yaml:"acmm_level,omitempty" json:"acmm_level"` + // Workflow gates the workflow-model engine (hivecommons/hive#17620). + // Off by default: every repository derives stages with the built-in + // derivers exactly as before. On, repositories bound to a workflow + // model derive through it; unbound repositories are unchanged. + Workflow WorkflowConfig `yaml:"workflow,omitempty" json:"workflow,omitempty"` + HiveID string `yaml:"hive_id"` + ACMMLevel *int `yaml:"acmm_level,omitempty" json:"acmm_level"` // ModelRoles is the named model-roles map (#9722): a small set of names, // each naming a backend, a model and a reasoning effort, referenced as // "@" wherever hive asks for a model (today: agents' model and the @@ -274,6 +279,11 @@ type Config struct { ReviewerAutoscaleActive int `yaml:"-" json:"-"` } +// WorkflowConfig is the `workflow:` block (hivecommons/hive#17620). +type WorkflowConfig struct { + Enabled bool `yaml:"enabled" json:"enabled"` +} + type DataConfig struct { MetricsDir string `yaml:"metrics_dir"` LogsDir string `yaml:"logs_dir"` @@ -286,6 +296,10 @@ type DataConfig struct { // panel configuration (#11694). Default /data/nous; HIVE_NOUS_DATA_DIR // overrides it at runtime. NousDir string `yaml:"nous_dir,omitempty"` + // WorkflowsDir is the durable root for stored workflow models + // (hivecommons/hive#17620); models live under /workflows. Empty + // means the hive data dir (/data); HIVE_WORKFLOWS_DATA_DIR overrides. + WorkflowsDir string `yaml:"workflows_dir,omitempty"` // SessionRetentionDays is how many days of CLI session-state directories to // keep. Session directories are created per CLI invocation and were never diff --git a/src/pkg/config/project_config.go b/src/pkg/config/project_config.go index fa40be3ef5..c25aed0f66 100644 --- a/src/pkg/config/project_config.go +++ b/src/pkg/config/project_config.go @@ -79,6 +79,9 @@ type ProjectConfig struct { // repo name. project.repos remains the watched-repo identity list; this // sidecar list lets existing string-list configs keep round-tripping. RepoPolicies []RepoPolicy `yaml:"repo_policies,omitempty" json:"repo_policies,omitempty"` + // WorkflowBindings assigns stored workflow models to repositories + // (hivecommons/hive#17620). Unbound repositories use hive-default. + WorkflowBindings []WorkflowBinding `yaml:"workflow_bindings,omitempty" json:"workflow_bindings,omitempty"` // MergeFrontTimeout is the hive-wide front timeout of the serialized merge // lane (hivecommons/hive#12952) as a Go duration ("90m", "2h"); empty // keeps the lane default of 60 minutes. repo_policies[].merge_front_timeout diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index c86ffdb635..9758a5abaa 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -447,8 +447,8 @@ "BaseURL": "", "AppAuthoredPRs": null, "AppSignedCommits": null, - "attention": {}, "notifications": {}, + "attention": {}, "OAuthBaseURLOverride": "", "OAuthAPIURLOverride": "" }, @@ -473,6 +473,7 @@ "Port": 8080, "AuthToken": "", "AgentPollIntervalS": 10, + "matrix": {}, "AuthorizedUsers": null, "AuthorizedUserNames": null, "HubProxied": false, @@ -483,7 +484,6 @@ } }, "issue_bands": {}, - "matrix": {}, "stage_tracker": {} }, "Data": { @@ -494,6 +494,7 @@ "BobSessionsDir": "/data/home/.bob", "AgentsDir": "/data/agent-configs", "NousDir": "/data/nous", + "WorkflowsDir": "", "SessionRetentionDays": null }, "deployment": {}, @@ -686,6 +687,9 @@ "fleet": {}, "dedupe": {}, "contribute": {}, + "workflow": { + "enabled": false + }, "HiveID": "", "acmm_level": null, "advisor": {}, @@ -723,6 +727,13 @@ }, "intent": {}, "sentinel": {}, + "security": {}, + "evidence": { + "complexity": {} + }, + "compliance": { + "posture_checks": {} + }, "escalation": { "email": { "smtp": {}, @@ -734,10 +745,6 @@ "pagerduty": {} } }, - "security": {}, - "evidence": { - "complexity": {} - }, "jev": {}, "runs": { "checkpoints": {}, @@ -776,9 +783,6 @@ "recommendations": {}, "plan_match": {} }, - "compliance": { - "posture_checks": {} - }, "auto_merge": { "bot_takeover": {}, "trusted_authors": {}, diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index 86d7532e6c..2d94665a8e 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -97,6 +97,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := ValidateWritingGuide(c.Project.WritingGuide); err != nil { return err } + if err := validateWorkflowBindings(c.Project.WorkflowBindings); err != nil { + return err + } for _, rp := range c.Project.RepoPolicies { if err := ValidateRepoMergeStrategy(rp.Repo, rp.MergeStrategy); err != nil { return err diff --git a/src/pkg/config/workflow_binding.go b/src/pkg/config/workflow_binding.go new file mode 100644 index 0000000000..f6dcb51c31 --- /dev/null +++ b/src/pkg/config/workflow_binding.go @@ -0,0 +1,95 @@ +package config + +import ( + "fmt" + "strings" +) + +// WorkflowBinding assigns a stored workflow model (name@version) to a +// repository (hivecommons/hive#17620). Repositories without a binding keep +// the built-in hive-default behaviour unchanged. +type WorkflowBinding struct { + Repo string `yaml:"repo" json:"repo"` + Name string `yaml:"name" json:"name"` + Version string `yaml:"version" json:"version"` +} + +// Key returns the name@version identity of the bound model. +func (b WorkflowBinding) Key() string { return b.Name + "@" + b.Version } + +// WorkflowBindingFor returns the binding covering repo, if any. repo may be +// bare or org-qualified. +func (c *Config) WorkflowBindingFor(repo string) (WorkflowBinding, bool) { + if c == nil { + return WorkflowBinding{}, false + } + key := repoPauseKey(c.Project.Org, repo) + if key == "" { + return WorkflowBinding{}, false + } + repoPauseMu.RLock() + defer repoPauseMu.RUnlock() + for _, b := range c.Project.WorkflowBindings { + if repoPauseKey(c.Project.Org, b.Repo) == key { + return b, true + } + } + return WorkflowBinding{}, false +} + +// SetWorkflowBinding binds repo to name@version, replacing any existing +// binding for the repo. An empty name removes the binding. It reports whether +// the config changed. +func (c *Config) SetWorkflowBinding(repo, name, version string) (bool, error) { + if c == nil { + return false, fmt.Errorf("nil config") + } + repo = strings.TrimSpace(repo) + key := repoPauseKey(c.Project.Org, repo) + if key == "" { + return false, fmt.Errorf("workflow binding: empty repo") + } + name, version = strings.TrimSpace(name), strings.TrimSpace(version) + if name != "" && version == "" { + return false, fmt.Errorf("workflow binding: %s has no version", name) + } + repoPauseMu.Lock() + defer repoPauseMu.Unlock() + kept := c.Project.WorkflowBindings[:0:0] + changed := false + for _, b := range c.Project.WorkflowBindings { + if repoPauseKey(c.Project.Org, b.Repo) == key { + changed = changed || name == "" || b.Name != name || b.Version != version + continue + } + kept = append(kept, b) + } + if name != "" { + if len(kept) == len(c.Project.WorkflowBindings) { + changed = true + } + kept = append(kept, WorkflowBinding{Repo: repo, Name: name, Version: version}) + } + if changed { + c.Project.WorkflowBindings = kept + } + return changed, nil +} + +func validateWorkflowBindings(bs []WorkflowBinding) error { + seen := map[string]bool{} + for i, b := range bs { + if strings.TrimSpace(b.Repo) == "" { + return fmt.Errorf("project.workflow_bindings[%d]: repo is required", i) + } + if strings.TrimSpace(b.Name) == "" || strings.TrimSpace(b.Version) == "" { + return fmt.Errorf("project.workflow_bindings[%d] (%s): name and version are required", i, b.Repo) + } + k := strings.ToLower(b.Repo) + if seen[k] { + return fmt.Errorf("project.workflow_bindings: %s bound twice", b.Repo) + } + seen[k] = true + } + return nil +} diff --git a/src/pkg/config/workflow_binding_test.go b/src/pkg/config/workflow_binding_test.go new file mode 100644 index 0000000000..55410374e6 --- /dev/null +++ b/src/pkg/config/workflow_binding_test.go @@ -0,0 +1,68 @@ +package config + +import ( + "strings" + "testing" +) + +func TestWorkflowBindings(t *testing.T) { + var nilCfg *Config + if _, ok := nilCfg.WorkflowBindingFor("x"); ok { + t.Fatal("nil config bound") + } + if _, err := nilCfg.SetWorkflowBinding("x", "a", "1"); err == nil { + t.Fatal("nil config set") + } + c := &Config{Project: ProjectConfig{Org: "hivecommons"}} + if _, ok := c.WorkflowBindingFor(""); ok { + t.Fatal("empty repo bound") + } + if _, err := c.SetWorkflowBinding(" ", "a", "1"); err == nil { + t.Fatal("empty repo accepted") + } + if _, err := c.SetWorkflowBinding("docs", "a", ""); err == nil { + t.Fatal("missing version accepted") + } + changed, err := c.SetWorkflowBinding("docs", "cncf-techdocs", "1") + if err != nil || !changed { + t.Fatalf("%v %v", changed, err) + } + b, ok := c.WorkflowBindingFor("HiveCommons/Docs") + if !ok || b.Key() != "cncf-techdocs@1" { + t.Fatalf("%+v %v", b, ok) + } + if changed, _ := c.SetWorkflowBinding("hivecommons/docs", "cncf-techdocs", "1"); changed { + t.Fatal("same binding reported changed") + } + if changed, _ := c.SetWorkflowBinding("docs", "cncf-techdocs", "2"); !changed || len(c.Project.WorkflowBindings) != 1 { + t.Fatalf("%+v", c.Project.WorkflowBindings) + } + if changed, _ := c.SetWorkflowBinding("other", "", ""); changed { + t.Fatal("unbinding an unbound repo changed") + } + if changed, _ := c.SetWorkflowBinding("docs", "", ""); !changed || len(c.Project.WorkflowBindings) != 0 { + t.Fatalf("%+v", c.Project.WorkflowBindings) + } +} + +func TestValidateWorkflowBindings(t *testing.T) { + cases := []struct { + bs []WorkflowBinding + want string + }{ + {nil, ""}, + {[]WorkflowBinding{{Repo: "a", Name: "m", Version: "1"}}, ""}, + {[]WorkflowBinding{{Name: "m", Version: "1"}}, "repo is required"}, + {[]WorkflowBinding{{Repo: "a", Name: "m"}}, "name and version"}, + {[]WorkflowBinding{{Repo: "a", Name: "m", Version: "1"}, {Repo: "A", Name: "n", Version: "1"}}, "bound twice"}, + } + for _, tc := range cases { + err := validateWorkflowBindings(tc.bs) + if tc.want == "" && err != nil { + t.Fatalf("%+v: %v", tc.bs, err) + } + if tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want)) { + t.Fatalf("%+v: %v", tc.bs, err) + } + } +} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index d471ec1dca..c58a544502 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -35,6 +35,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // Issue claims (hivecommons/hive#8380). Routes register unconditionally; // handlers answer "not enabled" when deps.IssueClaims is nil. s.registerClaimsRoutes() + s.registerWorkflowRoutes() // Approval desk (RFC #4000). Routes register unconditionally; the handlers // report "not enabled" when deps.ApprovalInbox is nil, so a disabled desk is // an honest 200 the panel can render rather than a 404 that looks broken. diff --git a/src/pkg/dashboard/api_workflows.go b/src/pkg/dashboard/api_workflows.go new file mode 100644 index 0000000000..c1065c0952 --- /dev/null +++ b/src/pkg/dashboard/api_workflows.go @@ -0,0 +1,223 @@ +package dashboard + +import ( + "errors" + "fmt" + "net/http" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/workflowmodel" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +// Workflow-model library and bindings (hivecommons/hive#17620, RFC phase 2). +// +// Reads are open to any dashboard user; writes are owner-gated and audited. +// The store is optional: without one every endpoint answers 503 so the UI can +// say "workflows not enabled" instead of showing an empty library. +func (s *Server) registerWorkflowRoutes() { + s.mux.HandleFunc("GET /api/workflows", s.handleWorkflowList) + s.mux.HandleFunc("POST /api/workflows", s.handleWorkflowSave) + s.mux.HandleFunc("POST /api/workflows/compile", s.handleWorkflowCompile) + s.mux.HandleFunc("POST /api/workflows/ingest", s.handleWorkflowIngest) + s.mux.HandleFunc("GET /api/workflows/bindings", s.handleWorkflowBindingsGet) + s.mux.HandleFunc("PUT /api/workflows/bindings", s.handleWorkflowBindingPut) + s.mux.HandleFunc("GET /api/workflows/{name}/{version}", s.handleWorkflowGet) + s.mux.HandleFunc("PUT /api/workflows/{name}/{version}", s.handleWorkflowSave) + s.mux.HandleFunc("DELETE /api/workflows/{name}/{version}", s.handleWorkflowDelete) +} + +func (s *Server) workflowStore(w http.ResponseWriter) *wfstore.Store { + if s.deps == nil || s.deps.WorkflowStore == nil { + jsonError(w, "workflow store not enabled", http.StatusServiceUnavailable) + return nil + } + return s.deps.WorkflowStore +} + +// workflowProfileLookup is the store's Profile method, or nil without a store. +func (s *Server) workflowProfileLookup() workflowProfileLookup { + if s.deps == nil || s.deps.WorkflowStore == nil { + return nil + } + return s.deps.WorkflowStore.Profile +} + +func workflowStoreError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, wfstore.ErrNotFound): + jsonError(w, err.Error(), http.StatusNotFound) + case errors.Is(err, wfstore.ErrReadOnly): + jsonError(w, err.Error(), http.StatusForbidden) + case errors.Is(err, wfstore.ErrBadName), errors.Is(err, wfstore.ErrBadVersion), errors.Is(err, wfstore.ErrNotCompiled): + jsonError(w, err.Error(), http.StatusBadRequest) + default: + jsonError(w, err.Error(), http.StatusInternalServerError) + } +} + +func (s *Server) handleWorkflowList(w http.ResponseWriter, r *http.Request) { + st := s.workflowStore(w) + if st == nil { + return + } + entries, err := st.List() + if err != nil { + workflowStoreError(w, err) + return + } + jsonResponse(w, map[string]interface{}{ + "workflows": entries, + "bindings": s.workflowBindings(), + "enabled": s.deps.Config != nil && s.deps.Config.Workflow.Enabled, + }) +} + +func (s *Server) handleWorkflowGet(w http.ResponseWriter, r *http.Request) { + st := s.workflowStore(w) + if st == nil { + return + } + m, e, err := st.Get(r.PathValue("name"), r.PathValue("version")) + if err != nil { + workflowStoreError(w, err) + return + } + resp := map[string]interface{}{"entry": e, "model": m} + if p, _, cerr := workflowmodel.Compile(m); cerr == nil { + resp["profile"] = p + } + jsonResponse(w, resp) +} + +// handleWorkflowCompile compiles a model without saving it so the editor can +// show diagnostics as the operator types. +func (s *Server) handleWorkflowCompile(w http.ResponseWriter, r *http.Request) { + var m workflowmodel.Model + if err := decodeBody(r, &m); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + p, diags, err := workflowmodel.Compile(&m) + resp := map[string]interface{}{"compiled": err == nil, "diagnostics": diags} + if diags == nil { + resp["diagnostics"] = []workflowmodel.Diagnostic{} + } + if p != nil { + resp["profile"] = p + } + jsonResponse(w, resp) +} + +func (s *Server) handleWorkflowSave(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + st := s.workflowStore(w) + if st == nil { + return + } + var m workflowmodel.Model + if err := decodeBody(r, &m); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + if name := r.PathValue("name"); name != "" && (name != m.Metadata.Name || r.PathValue("version") != m.Spec.Meta.Version) { + jsonError(w, fmt.Sprintf("body is %s@%s, path is %s@%s", m.Metadata.Name, m.Spec.Meta.Version, name, r.PathValue("version")), http.StatusBadRequest) + return + } + e, err := st.Save(&m, requestUser(r), time.Now().UTC()) + if err != nil { + workflowStoreError(w, err) + return + } + s.auditFromRequest(r, "workflow_save", fmt.Sprintf("%s compiled=%v", e.Key(), e.Compiled), "") + jsonStatusResponse(w, http.StatusCreated, map[string]interface{}{"entry": e}) +} + +func (s *Server) handleWorkflowDelete(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + st := s.workflowStore(w) + if st == nil { + return + } + name, version := r.PathValue("name"), r.PathValue("version") + if s.deps.Config != nil { + for _, b := range s.deps.Config.Project.WorkflowBindings { + if b.Name == name && b.Version == version { + jsonError(w, fmt.Sprintf("%s@%s is bound to %s; unbind first", name, version, b.Repo), http.StatusConflict) + return + } + } + } + if err := st.Delete(name, version); err != nil { + workflowStoreError(w, err) + return + } + s.auditFromRequest(r, "workflow_delete", name+"@"+version, "") + okResponse(w, nil) +} + +func (s *Server) workflowBindings() []config.WorkflowBinding { + if s.deps == nil || s.deps.Config == nil || s.deps.Config.Project.WorkflowBindings == nil { + return []config.WorkflowBinding{} + } + return s.deps.Config.Project.WorkflowBindings +} + +func (s *Server) handleWorkflowBindingsGet(w http.ResponseWriter, r *http.Request) { + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + jsonResponse(w, map[string]interface{}{ + "bindings": s.workflowBindings(), + "enabled": s.deps.Config.Workflow.Enabled, + }) +} + +// handleWorkflowBindingPut binds (name+version set) or unbinds (name empty) a +// repository. A bound model must exist and compile so a stale binding can +// never leave the tracker without columns. +func (s *Server) handleWorkflowBindingPut(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + var body config.WorkflowBinding + if err := decodeBody(r, &body); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + action := "workflow_unbind" + if body.Name != "" { + st := s.workflowStore(w) + if st == nil { + return + } + if _, err := st.Profile(body.Name, body.Version); err != nil { + workflowStoreError(w, err) + return + } + action = "workflow_bind" + } + changed, err := s.deps.Config.SetWorkflowBinding(body.Repo, body.Name, body.Version) + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + if changed { + if err := s.saveConfig(); err != nil { + jsonError(w, "save config: "+err.Error(), http.StatusInternalServerError) + return + } + s.auditFromRequest(r, action, fmt.Sprintf("%s -> %s@%s", body.Repo, body.Name, body.Version), "") + } + jsonResponse(w, map[string]interface{}{"changed": changed, "bindings": s.workflowBindings()}) +} diff --git a/src/pkg/dashboard/api_workflows_ingest.go b/src/pkg/dashboard/api_workflows_ingest.go new file mode 100644 index 0000000000..155f08a24f --- /dev/null +++ b/src/pkg/dashboard/api_workflows_ingest.go @@ -0,0 +1,134 @@ +package dashboard + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/ingest" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +// workflowIngestTimeout bounds one repository fetch + ingest. +const workflowIngestTimeout = 2 * time.Minute + +// workflowIngestRequest is the body of POST /api/workflows/ingest. Exactly +// one of Repo (fetch the default branch through the forge) or Files +// (pasted/uploaded CI definitions, repo-relative path -> contents) is set. +type workflowIngestRequest struct { + Repo string `json:"repo"` + Files map[string]string `json:"files,omitempty"` + // Save stores the result as a draft under Name (default: the ingest's + // slug of the repository) at the next free integer version. + Save bool `json:"save,omitempty"` + Name string `json:"name,omitempty"` +} + +// handleWorkflowIngest turns a repository's CI definitions into a lifecycle +// model (RFC #17620 P3): hive-default's stages plus the repository's +// pipelines, provenance ingested-unreviewed. Owner-gated because it reads +// the forge on the hive's credential and may write the store. +func (s *Server) handleWorkflowIngest(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + var req workflowIngestRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + req.Repo = strings.TrimSpace(req.Repo) + if (req.Repo == "") == (len(req.Files) == 0) { + jsonError(w, "set exactly one of repo or files", http.StatusBadRequest) + return + } + var files map[string][]byte + ref := "" + repo := req.Repo + switch { + case len(req.Files) > 0: + if repo == "" { + repo = "local/pasted" + } + files = make(map[string][]byte, len(req.Files)) + for p, body := range req.Files { + files[strings.TrimPrefix(strings.TrimSpace(p), "/")] = []byte(body) + } + default: + if !strings.Contains(repo, "/") { + jsonError(w, "repo must be owner/name", http.StatusBadRequest) + return + } + if s.deps == nil || s.deps.WorkflowRepoFiles == nil { + jsonError(w, "repository ingest not available: no forge client", http.StatusServiceUnavailable) + return + } + ctx, cancel := context.WithTimeout(r.Context(), workflowIngestTimeout) + defer cancel() + var err error + files, ref, err = s.deps.WorkflowRepoFiles(ctx, repo) + if err != nil { + jsonError(w, fmt.Sprintf("fetch %s: %v", repo, err), http.StatusBadGateway) + return + } + } + + m := ingest.Lifecycle(workflowmodel.Scope{Forge: "github.com", Repository: repo}, files) + if req.Name != "" { + m.Metadata.Name = req.Name + } + p, diags, cerr := workflowmodel.Compile(m) + if diags == nil { + diags = []workflowmodel.Diagnostic{} + } + resp := map[string]interface{}{ + "model": m, "compiled": cerr == nil, "diagnostics": diags, + "ref": ref, "files": len(files), "pipelines": len(m.Spec.Pipelines), + } + if p != nil { + resp["profile"] = p + } + if !req.Save { + jsonResponse(w, resp) + return + } + st := s.workflowStore(w) + if st == nil { + return + } + version, err := nextWorkflowVersion(st, m.Metadata.Name) + if err != nil { + workflowStoreError(w, err) + return + } + m.Spec.Meta.Version = version + e, err := st.Save(m, requestUser(r), time.Now().UTC()) + if err != nil { + workflowStoreError(w, err) + return + } + s.auditFromRequest(r, "workflow_ingest", fmt.Sprintf("%s from %s@%s files=%d compiled=%v", e.Key(), repo, ref, len(files), e.Compiled), "") + resp["entry"] = e + jsonStatusResponse(w, http.StatusCreated, resp) +} + +// nextWorkflowVersion is one past the highest integer version stored under +// name ("1" for a new name); non-integer versions are ignored. +func nextWorkflowVersion(st *wfstore.Store, name string) (string, error) { + entries, err := st.Versions(name) + if err != nil && !errors.Is(err, wfstore.ErrNotFound) { + return "", err + } + max := 0 + for _, e := range entries { + if n, err := strconv.Atoi(e.Version); err == nil && n > max { + max = n + } + } + return strconv.Itoa(max + 1), nil +} diff --git a/src/pkg/dashboard/api_workflows_ingest_test.go b/src/pkg/dashboard/api_workflows_ingest_test.go new file mode 100644 index 0000000000..ec96d72e6a --- /dev/null +++ b/src/pkg/dashboard/api_workflows_ingest_test.go @@ -0,0 +1,105 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "testing" + + "github.com/hivecommons/hive/pkg/workflowmodel" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +const ingestCIYAML = "name: CI\non: [pull_request, push]\njobs:\n test:\n runs-on: ubuntu-latest\n steps: [{run: make test}]\n" + +func TestWorkflowIngestFromFilesCompilesAndSaves(t *testing.T) { + s := workflowTestServer(t, true) + body := map[string]any{"files": map[string]string{".github/workflows/ci.yml": ingestCIYAML}, "name": "pasted", "save": true} + rec := wfReq(s, http.MethodPost, "/api/workflows/ingest", body, true) + if rec.Code != http.StatusCreated { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + var resp struct { + Compiled bool `json:"compiled"` + Pipelines int `json:"pipelines"` + Entry wfstore.Entry `json:"entry"` + Model workflowmodel.Model `json:"model"` + Diags []workflowmodel.Diagnostic `json:"diagnostics"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if !resp.Compiled || resp.Pipelines != 1 || resp.Entry.Key() != "pasted@1" || !resp.Entry.Compiled { + t.Fatalf("%+v", resp) + } + if resp.Model.Spec.Meta.Provenance != workflowmodel.ProvenanceIngestedUnreviewed { + t.Fatalf("provenance %q", resp.Model.Spec.Meta.Provenance) + } + // A second ingest of the same name lands at the next version. + rec = wfReq(s, http.MethodPost, "/api/workflows/ingest", body, true) + if rec.Code != http.StatusCreated { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Entry.Key() != "pasted@2" { + t.Fatalf("second version %s", resp.Entry.Key()) + } + // Dry run (no save) needs no store and returns the model. + s2 := workflowTestServer(t, false) + rec = wfReq(s2, http.MethodPost, "/api/workflows/ingest", map[string]any{"files": map[string]string{".github/workflows/ci.yml": ingestCIYAML}}, true) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } +} + +func TestWorkflowIngestFromRepoUsesForgeFetcher(t *testing.T) { + s := workflowTestServer(t, true) + var asked string + s.deps.WorkflowRepoFiles = func(_ context.Context, repo string) (map[string][]byte, string, error) { + asked = repo + if repo == "acme/missing" { + return nil, "", errors.New("404") + } + return map[string][]byte{".github/workflows/ci.yml": []byte(ingestCIYAML)}, "main", nil + } + rec := wfReq(s, http.MethodPost, "/api/workflows/ingest", map[string]any{"repo": "acme/widgets"}, true) + if rec.Code != http.StatusOK || asked != "acme/widgets" { + t.Fatalf("%d %s asked=%q", rec.Code, rec.Body, asked) + } + var resp struct { + Ref string `json:"ref"` + Model workflowmodel.Model `json:"model"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.Ref != "main" || resp.Model.Metadata.Name != "acme-widgets" || resp.Model.Spec.Scope.Repository != "acme/widgets" { + t.Fatalf("%+v", resp) + } + if rec := wfReq(s, http.MethodPost, "/api/workflows/ingest", map[string]any{"repo": "acme/missing"}, true); rec.Code != http.StatusBadGateway { + t.Fatalf("fetch failure %d", rec.Code) + } +} + +func TestWorkflowIngestGuards(t *testing.T) { + s := workflowTestServer(t, true) + cases := []struct { + body map[string]any + owner bool + want int + }{ + {map[string]any{"repo": "acme/widgets"}, false, http.StatusForbidden}, + {map[string]any{}, true, http.StatusBadRequest}, + {map[string]any{"repo": "acme/widgets", "files": map[string]string{"a.yml": "x"}}, true, http.StatusBadRequest}, + {map[string]any{"repo": "nojslash"}, true, http.StatusBadRequest}, + {map[string]any{"repo": "acme/widgets"}, true, http.StatusServiceUnavailable}, // no fetcher + } + for i, c := range cases { + if rec := wfReq(s, http.MethodPost, "/api/workflows/ingest", c.body, c.owner); rec.Code != c.want { + t.Fatalf("case %d: %d %s", i, rec.Code, rec.Body) + } + } +} diff --git a/src/pkg/dashboard/api_workflows_test.go b/src/pkg/dashboard/api_workflows_test.go new file mode 100644 index 0000000000..bb9e077957 --- /dev/null +++ b/src/pkg/dashboard/api_workflows_test.go @@ -0,0 +1,278 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +func workflowTestServer(t *testing.T, withStore bool) *Server { + t.Helper() + logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})) + s := NewServer(0, logger) + deps := testDeps(t) + if withStore { + deps.WorkflowStore = wfstore.Open(t.TempDir()) + } + s.RegisterAPI(deps) + return s +} + +func techdocsModel(t *testing.T) *workflowmodel.Model { + t.Helper() + b, err := os.ReadFile("../workflowmodel/testdata/models/techdocs.json") + if err != nil { + t.Fatal(err) + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return &m +} + +func wfReq(s *Server, method, path string, body any, owner bool) *httptest.ResponseRecorder { + var buf bytes.Buffer + if body != nil { + if raw, ok := body.(string); ok { + buf.WriteString(raw) + } else { + _ = json.NewEncoder(&buf).Encode(body) + } + } + req := httptest.NewRequest(method, path, &buf) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-User", "andy") + if owner { + req.Header.Set("X-Hive-Role", "owner") + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + return rec +} + +func TestWorkflowAPIDisabledWithoutStore(t *testing.T) { + s := workflowTestServer(t, false) + for _, c := range []struct{ method, path string }{ + {http.MethodGet, "/api/workflows"}, + {http.MethodGet, "/api/workflows/x/1"}, + {http.MethodPost, "/api/workflows"}, + {http.MethodDelete, "/api/workflows/x/1"}, + } { + if rec := wfReq(s, c.method, c.path, nil, true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%s %s: %d %s", c.method, c.path, rec.Code, rec.Body) + } + } + // compile needs no store + rec := wfReq(s, http.MethodPost, "/api/workflows/compile", techdocsModel(t), false) + var out struct{ Compiled bool } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &out) != nil || !out.Compiled { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + // binding a model requires the store + rec = wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "repo1", "name": "x", "version": "1"}, true) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%d %s", rec.Code, rec.Body) + } +} + +func TestWorkflowAPIOwnerGate(t *testing.T) { + s := workflowTestServer(t, true) + for _, c := range []struct{ method, path string }{ + {http.MethodPost, "/api/workflows"}, + {http.MethodPut, "/api/workflows/x/1"}, + {http.MethodDelete, "/api/workflows/x/1"}, + {http.MethodPut, "/api/workflows/bindings"}, + } { + if rec := wfReq(s, c.method, c.path, techdocsModel(t), false); rec.Code != http.StatusForbidden { + t.Fatalf("%s %s: %d", c.method, c.path, rec.Code) + } + } +} + +func TestWorkflowAPILifecycle(t *testing.T) { + s := workflowTestServer(t, true) + m := techdocsModel(t) + + rec := wfReq(s, http.MethodGet, "/api/workflows", nil, false) + var list struct { + Workflows []wfstore.Entry + Bindings []json.RawMessage + Enabled bool + } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &list) != nil || len(list.Workflows) != 1 || list.Bindings == nil || list.Enabled { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + + if rec := wfReq(s, http.MethodPost, "/api/workflows", "{", true); rec.Code != http.StatusBadRequest { + t.Fatalf("bad json: %d", rec.Code) + } + if rec := wfReq(s, http.MethodPost, "/api/workflows", m, true); rec.Code != http.StatusCreated { + t.Fatalf("save: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/cncf-techdocs/9", m, true); rec.Code != http.StatusBadRequest { + t.Fatalf("path mismatch: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/cncf-techdocs/1", m, true); rec.Code != http.StatusCreated { + t.Fatalf("put: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPost, "/api/workflows", hivedefault.Generate(), true); rec.Code != http.StatusForbidden { + t.Fatalf("builtin save: %d", rec.Code) + } + + rec = wfReq(s, http.MethodGet, "/api/workflows/cncf-techdocs/1", nil, false) + var got struct { + Entry wfstore.Entry + Profile *workflowmodel.Profile + } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &got) != nil || got.Profile == nil || got.Entry.SavedBy != "andy" { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodGet, "/api/workflows/cncf-techdocs/2", nil, false); rec.Code != http.StatusNotFound { + t.Fatalf("missing: %d", rec.Code) + } + if rec := wfReq(s, http.MethodGet, "/api/workflows/Bad%20Name/2", nil, false); rec.Code != http.StatusBadRequest { + t.Fatalf("bad name: %d", rec.Code) + } + + // drafts save but cannot be bound + draft := techdocsModel(t) + draft.Spec.Meta.Version = "draft" + draft.Spec.Gates[0].ReleasedBy = "" + if rec := wfReq(s, http.MethodPost, "/api/workflows", draft, true); rec.Code != http.StatusCreated { + t.Fatalf("draft save: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "repo1", "name": "cncf-techdocs", "version": "draft"}, true); rec.Code != http.StatusBadRequest { + t.Fatalf("bind draft: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/bindings", "{", true); rec.Code != http.StatusBadRequest { + t.Fatalf("bind bad json: %d", rec.Code) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "", "name": "cncf-techdocs", "version": "1"}, true); rec.Code != http.StatusBadRequest { + t.Fatalf("bind empty repo: %d", rec.Code) + } + + rec = wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "repo1", "name": "cncf-techdocs", "version": "1"}, true) + var bind struct { + Changed bool + Bindings []struct{ Repo, Name, Version string } + } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &bind) != nil || !bind.Changed || len(bind.Bindings) != 1 { + t.Fatalf("bind: %d %s", rec.Code, rec.Body) + } + if b, ok := s.deps.Config.WorkflowBindingFor("myorg/repo1"); !ok || b.Version != "1" { + t.Fatalf("%+v %v", b, ok) + } + rec = wfReq(s, http.MethodGet, "/api/workflows/bindings", nil, false) + if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte(`"cncf-techdocs"`)) { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + + // bound models cannot be deleted + if rec := wfReq(s, http.MethodDelete, "/api/workflows/cncf-techdocs/1", nil, true); rec.Code != http.StatusConflict { + t.Fatalf("delete bound: %d %s", rec.Code, rec.Body) + } + rec = wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "repo1"}, true) + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &bind) != nil || !bind.Changed || len(bind.Bindings) != 0 { + t.Fatalf("unbind: %d %s", rec.Code, rec.Body) + } + rec = wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "repo1"}, true) + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &bind) != nil || bind.Changed { + t.Fatalf("unbind again: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodDelete, "/api/workflows/cncf-techdocs/1", nil, true); rec.Code != 200 { + t.Fatalf("delete: %d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodDelete, "/api/workflows/cncf-techdocs/1", nil, true); rec.Code != http.StatusNotFound { + t.Fatalf("delete twice: %d", rec.Code) + } + if rec := wfReq(s, http.MethodDelete, "/api/workflows/hive-default/1", nil, true); rec.Code != http.StatusForbidden { + t.Fatalf("delete builtin: %d", rec.Code) + } + + // compile reports diagnostics for drafts and invalid shapes + rec = wfReq(s, http.MethodPost, "/api/workflows/compile", draft, false) + var comp struct { + Compiled bool + Diagnostics []workflowmodel.Diagnostic + } + if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &comp) != nil || comp.Compiled || len(comp.Diagnostics) == 0 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if rec := wfReq(s, http.MethodPost, "/api/workflows/compile", "{", false); rec.Code != http.StatusBadRequest { + t.Fatalf("compile bad json: %d", rec.Code) + } +} + +func TestWorkflowBindingsWithoutConfig(t *testing.T) { + s := workflowTestServer(t, true) + s.deps.Config = nil + if rec := wfReq(s, http.MethodGet, "/api/workflows/bindings", nil, false); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%d", rec.Code) + } + if rec := wfReq(s, http.MethodPut, "/api/workflows/bindings", map[string]string{"repo": "r"}, true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%d", rec.Code) + } + rec := wfReq(s, http.MethodGet, "/api/workflows", nil, false) + if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte(`"bindings":[]`)) { + t.Fatalf("%d %s", rec.Code, rec.Body) + } +} + +func TestStageTrackerWorkflowsBlock(t *testing.T) { + qualify := func(r string) string { return "myorg/" + r } + if stageTrackerWorkflows(nil, nil, qualify) != nil { + t.Fatal("nil config produced a block") + } + s := workflowTestServer(t, true) + if stageTrackerWorkflows(s.deps.Config, s.workflowProfileLookup(), qualify) != nil { + t.Fatal("unbound hive produced a block") + } + if rec := wfReq(s, http.MethodPost, "/api/workflows", techdocsModel(t), true); rec.Code != http.StatusCreated { + t.Fatal(rec.Body.String()) + } + if _, err := s.deps.Config.SetWorkflowBinding("repo1", "cncf-techdocs", "1"); err != nil { + t.Fatal(err) + } + if _, err := s.deps.Config.SetWorkflowBinding("repo2", "ghost", "1"); err != nil { + t.Fatal(err) + } + blk := stageTrackerWorkflows(s.deps.Config, s.workflowProfileLookup(), qualify) + if blk == nil || blk.Default.Name != hivedefault.Name || len(blk.Default.Columns) != 7 { + t.Fatalf("%+v", blk) + } + td := blk.Repos["myorg/repo1"] + if td.Name != "cncf-techdocs" || td.Error != "" || len(td.Columns) != 5 { + t.Fatalf("%+v", td) + } + var nums int + for _, c := range td.Columns { + nums += len(c.Numbers) + } + if nums == 0 { + t.Fatalf("no stage numbers anchored: %+v", td.Columns) + } + if g := blk.Repos["myorg/repo2"]; g.Error == "" || g.Name != "ghost" { + t.Fatalf("%+v", g) + } + noStore := stageTrackerWorkflows(s.deps.Config, nil, qualify) + if noStore.Repos["myorg/repo1"].Error == "" { + t.Fatalf("%+v", noStore.Repos) + } + // the tracker response carries it + resp := s.buildStageTracker(&StatusPayload{HiveID: "h"}, nil, time.Now()) + if resp.Workflows == nil || len(resp.Workflows.Repos) != 2 { + t.Fatalf("%+v", resp.Workflows) + } +} diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index 565544d6ff..b796186b11 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -2,6 +2,7 @@ package dashboard import ( "context" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" "log/slog" "net/http" "os" @@ -57,6 +58,13 @@ type ChatPoll struct { type Dependencies struct { Config *config.Config + // WorkflowStore serves the workflow-model library (hivecommons/hive#17620). + // Nil disables the /api/workflows endpoints. + WorkflowStore *wfstore.Store + // WorkflowRepoFiles fetches a repository's default-branch CI definition + // files (repo-relative slash path -> contents) and the ref read, for + // POST /api/workflows/ingest. Nil disables ingest from a repository. + WorkflowRepoFiles func(ctx context.Context, repo string) (files map[string][]byte, ref string, err error) // AgentMgr is the agent runtime (hivecommons/hive#13536). The dashboard // programs against the crux.Runtime surface, not *agent.Manager; tests that // need manager-only seams unwrap it with agentManager. diff --git a/src/pkg/dashboard/import_count_test.go b/src/pkg/dashboard/import_count_test.go index 5a67cebfda..5bda3be660 100644 --- a/src/pkg/dashboard/import_count_test.go +++ b/src/pkg/dashboard/import_count_test.go @@ -72,8 +72,11 @@ func TestDashboardInternalImportCountRatchet(t *testing.T) { // surfaces render one markup (hivecommons/hive#16236), plus // pkg/maintainernotes, the append-only store behind the Activity // Monitor's private per-item maintainer notes and the /api/notes routes, - // shared with the scheduler's kick injection (hivecommons/hive#17244). - const maxDashboardInternalImports = 67 + // shared with the scheduler's kick injection (hivecommons/hive#17244), + // plus pkg/workflowmodel/store, the spoke-local library of workflow + // models behind the /api/workflows routes and the tracker's per-repo + // column block (RFC hivecommons/hive#17620, phase 2). + const maxDashboardInternalImports = 68 entries, err := os.ReadDir(".") if err != nil { diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index c5fe0c8734..60aa9f75cc 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -709,3 +709,7 @@ governor.hotspot_min_lines # merge-hotspot advisor; yaml-only governor.hotspot_refile_days # merge-hotspot advisor; yaml-only governor.hotspot_max_open # merge-hotspot advisor; yaml-only governor.hotspot_max_per_pass # merge-hotspot advisor; yaml-only +data.workflows_dir # workflow-model store root; deployment knob, no Settings control planned (RFC #17620) +project.workflow_bindings[].name # set through the per-repo workflow select on Settings → Repos via PUT /api/workflows/bindings, not a leaf-path control (RFC #17620) +project.workflow_bindings[].repo # see project.workflow_bindings[].name +project.workflow_bindings[].version # see project.workflow_bindings[].name diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 0bf70f091e..24b18d87c9 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -77,6 +77,10 @@ type StageTrackerResponse struct { // Engine is the ADR-0025 central stage engine's mode and counters for // the tracker's status strip; absent when the hive has no engine. Engine *stageengine.Status `json:"engine,omitempty"` + // Workflows names the workflow model each bound repository follows and + // its column layout (hivecommons/hive#17620); absent when no repository + // is bound. + Workflows *StageTrackerWorkflows `json:"workflows,omitempty"` // RecentlyMerged lists the pull requests GitHub reports merged within // stageTrackerMergedWindow, whoever merged them: the audit log's // pr_merged entries (the hive's own sweep, queue, relay and forge diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index caa5694ef0..2f7fdef85d 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -57,6 +57,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto cfg = s.deps.Config } resp.NeedsHumanLabels = needsHumanPresetLabels(cfg, status.HiveID) + resp.Workflows = stageTrackerWorkflows(cfg, s.workflowProfileLookup(), qualifyRepo) expectedPerspectives := stageTrackerExpectedPerspectives(cfg) // A Review track only waits on "the hive reviewer" when this hive's // planner dispatches one; with the swarm off it says a person reviews. diff --git a/src/pkg/dashboard/stage_tracker_workflows.go b/src/pkg/dashboard/stage_tracker_workflows.go new file mode 100644 index 0000000000..3e0d593361 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflows.go @@ -0,0 +1,89 @@ +package dashboard + +import ( + "sort" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// StageTrackerWorkflows is the tracker's `workflows` block +// (hivecommons/hive#17620, RFC phase 2): which model each bound repository +// follows and the column/state layout the SPA renders for it. Absent when no +// repository is bound, so the v5/v6 payload is unchanged for every hive that +// has not opted in. +type StageTrackerWorkflows struct { + // Default is the hive-default model every unbound repository follows. + Default StageTrackerWorkflow `json:"default"` + // Repos maps an org-qualified repository to its bound model. Repos + // bound to a model that is missing or no longer compiles are listed + // with Error set and fall back to Default in the SPA. + Repos map[string]StageTrackerWorkflow `json:"repos"` +} + +// StageTrackerWorkflow is one model's identity and column layout. +type StageTrackerWorkflow struct { + Name string `json:"name"` + Version string `json:"version"` + Hash string `json:"hash,omitempty"` + Columns []StageTrackerWorkflowColumn `json:"columns,omitempty"` + Error string `json:"error,omitempty"` +} + +// StageTrackerWorkflowColumn is a column with the stage numbers it anchors, +// so the SPA can place an item by its stage/NNN number without knowing the +// model's state ids. +type StageTrackerWorkflowColumn struct { + ID string `json:"id"` + Label string `json:"label"` + Hint string `json:"hint,omitempty"` + Terminal bool `json:"terminal,omitempty"` + States []string `json:"states"` + Numbers []int `json:"numbers"` +} + +// workflowProfileLookup resolves a bound name@version to its compiled +// profile; the store's Profile method satisfies it. +type workflowProfileLookup func(name, version string) (*workflowmodel.Profile, error) + +func stageTrackerWorkflowBlock(p *workflowmodel.Profile) StageTrackerWorkflow { + out := StageTrackerWorkflow{Name: p.Name, Version: p.Version, Hash: p.Hash} + for _, c := range p.Columns { + col := StageTrackerWorkflowColumn{ID: c.ID, Label: c.Label, Hint: c.Hint, Terminal: c.Terminal, States: append([]string{}, c.States...), Numbers: []int{}} + for _, id := range c.States { + if st := p.States[id]; st != nil && st.Lifecycle.Number > 0 { + col.Numbers = append(col.Numbers, st.Lifecycle.Number) + } + } + sort.Ints(col.Numbers) + out.Columns = append(out.Columns, col) + } + return out +} + +// stageTrackerWorkflows builds the block from the config's bindings; nil when +// there are none. +func stageTrackerWorkflows(cfg *config.Config, lookup workflowProfileLookup, qualify func(string) string) *StageTrackerWorkflows { + if cfg == nil || len(cfg.Project.WorkflowBindings) == 0 { + return nil + } + out := &StageTrackerWorkflows{ + Default: stageTrackerWorkflowBlock(hivedefault.Profile()), + Repos: map[string]StageTrackerWorkflow{}, + } + for _, b := range cfg.Project.WorkflowBindings { + repo := qualify(b.Repo) + if lookup == nil { + out.Repos[repo] = StageTrackerWorkflow{Name: b.Name, Version: b.Version, Error: "workflow store not enabled"} + continue + } + p, err := lookup(b.Name, b.Version) + if err != nil { + out.Repos[repo] = StageTrackerWorkflow{Name: b.Name, Version: b.Version, Error: err.Error()} + continue + } + out.Repos[repo] = stageTrackerWorkflowBlock(p) + } + return out +} diff --git a/src/pkg/dashboard/stage_tracker_workflows_ui_test.go b/src/pkg/dashboard/stage_tracker_workflows_ui_test.go new file mode 100644 index 0000000000..1e2d2a1ce9 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflows_ui_test.go @@ -0,0 +1,101 @@ +package dashboard + +import ( + "os/exec" + "strings" + "testing" +) + +// TestStageTrackerWorkflowColumnsWiring pins the RFC phase-2 surface +// (hivecommons/hive#17620): the tracker reads `workflows` from the payload, +// a bound repository's group header carries the model badge and its own +// column header, and the row strip switches to the model's columns only +// when stageTrackerWorkflowOf resolves one. +func TestStageTrackerWorkflowColumnsWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `ctx.workflows = d.workflows || null;`, + `function stageTrackerWorkflowOf(ctx, repo)`, + `function stageTrackerWorkflowColumnIndex(wf, stage)`, + `function stageTrackerWorkflowStripItems(item, wf, stages)`, + `function stageTrackerWorkflowHeaderHtml(wf)`, + `const rowWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, item.repo) : null;`, + `${rowWorkflow ? stageTrackerWorkflowStripItems(shown, rowWorkflow, stages) : stageTrackerStripItems(`, + `const groupWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, g.repo) : null;`, + `${groupWorkflow && !g.collapsed ? stageTrackerWorkflowHeaderHtml(groupWorkflow) : ''}`, + `.ham-wf-badge {`, + `.ham-seg.ham-wf-uncovered {`, + // Settings → Repos binding select. + `function renderRepoWorkflowRow(repo)`, + `async function setRepoWorkflow(repo, value)`, + `fetch('/api/workflows/bindings', {`, + `+ ldSub + renderRepoWorkflowRow(r);`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing workflow-columns wiring %q", want) + } + } +} + +// The pure helpers under node: an unbound hive resolves no model (so the +// built-in strip is untouched), hive-default itself resolves none, a bound +// repository places rows by stage number into the model's columns, a +// terminal stage lights the terminal column, and an uncovered number is +// drawn as "Not covered" rather than dropped. +func TestStageTrackerWorkflowColumnsNode(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed") + } + html := indexHTML(t) + script := `const assert = require('assert'); +const STAGE_TRACKER_TERMINAL = 110; +function esc(s) { return String(s).replace(/&/g, '&').replace(/ html.match(/
  • m.slice(11, -1)); +const words = html => [...html.matchAll(/([^<]*)<\/span>/g)].map(m => m[1]); +let s = stageTrackerWorkflowStripItems({ stage: 45 }, td, stages); +assert.deepStrictEqual(li(s), ['ham-seg ham-wf-seg done', 'ham-seg ham-wf-seg active', 'ham-seg ham-wf-seg todo', 'ham-seg ham-wf-seg todo cap']); +assert.deepStrictEqual(words(s), ['Requested', 'Decision', 'Writing', 'Published'], 'active column wears the stage word'); +s = stageTrackerWorkflowStripItems({ stage: 110 }, td, stages); +assert.deepStrictEqual(li(s), ['ham-seg ham-wf-seg done', 'ham-seg ham-wf-seg done', 'ham-seg ham-wf-seg done', 'ham-seg ham-wf-seg active cap']); +s = stageTrackerWorkflowStripItems({ stage: 85 }, td, stages); +assert.ok(li(s)[0].includes('ham-wf-uncovered') && words(s)[0] === 'Not covered', s); +assert.ok(s.includes('stage/085 is not a state of cncf-techdocs@1')); +s = stageTrackerWorkflowStripItems({ stage: 0 }, td, stages); +assert.deepStrictEqual(li(s)[0], 'ham-seg ham-wf-seg active'); + +const head = stageTrackerWorkflowHeaderHtml(td); +assert.ok(head.includes('data-ham-workflow="cncf-techdocs@1"') && head.includes('title="Asked for"') && li(head).length === 4, head); +assert.ok(stageTrackerWorkflowBadgeHtml(td).includes('>cncf-techdocs@1<')); +assert.strictEqual(stageTrackerWorkflowBadgeHtml(null), ''); +` + if out, err := runNodeStdin(node, script); err != nil { + t.Fatalf("node workflow columns fixture failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index b7c729d01a..f3e24adcf4 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -267,6 +267,13 @@ .ham-group-n, .ham-group-attn { flex: 0 0 auto; font-size: var(--fs-xs); color: var(--text-faint); white-space: nowrap; } .ham-group-attn { color: var(--amber); } .ham-group-collapsed .ham-group-name { color: var(--muted); } + /* Workflow-model columns (RFC 17620): the model badge on a + bound repository's group header, its own column header, and the + "Not covered" chevron for a stage the model has no state for. */ + .ham-wf-badge { flex: 0 0 auto; font-family: var(--font-mono); font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.02em; padding: var(--sp-1) var(--sp-3); border-radius: var(--r-pill); white-space: nowrap; color: var(--indigo); background: color-mix(in srgb, var(--indigo) 12%, transparent); border: 1px solid color-mix(in srgb, var(--indigo) 40%, transparent); } + .ham-wf-cols { position: static; } + .ham-wf-cols .ham-wf-col { color: var(--indigo); } + .ham-seg.ham-wf-uncovered { background: color-mix(in srgb, var(--amber) 18%, transparent); color: var(--amber); outline: 1px dashed var(--amber); } .ham-group-dist { flex: 0 0 auto; margin-left: auto; margin-right: calc(4em + var(--sp-3)); display: inline-flex; align-items: flex-end; gap: var(--sp-1); height: 0.9em; } .ham-gd { display: inline-block; width: 0.45em; height: 15%; border-radius: var(--sp-1); background: color-mix(in srgb, var(--text-faint) 35%, transparent); } .ham-gd-1 { height: 35%; background: color-mix(in srgb, var(--amber) 55%, transparent); } diff --git a/src/pkg/dashboard/static-src/js/config-governor.js b/src/pkg/dashboard/static-src/js/config-governor.js index 49d70fd669..e9ed9d8375 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -1104,7 +1104,7 @@ `; // Fully forge-qualified so the row is unambiguous: github.ibm.com/org/repo. const displayName = ghHost + '/' + r; - return `
    ${isDefault ? '★' : '☆'}${esc(displayName)}${inheritButton}${rtRow}${cbRow}${pillLabel}
    ` + ldSub; + return `
    ${isDefault ? '★' : '☆'}${esc(displayName)}${inheritButton}${rtRow}${cbRow}${pillLabel}
    ` + ldSub + renderRepoWorkflowRow(r); }).join(''); const hostNote = isGHE ? ` on ${esc(ghHost)} (GitHub Enterprise)` diff --git a/src/pkg/dashboard/static-src/js/config-workflows.js b/src/pkg/dashboard/static-src/js/config-workflows.js new file mode 100644 index 0000000000..407bed42df --- /dev/null +++ b/src/pkg/dashboard/static-src/js/config-workflows.js @@ -0,0 +1,96 @@ + // Workflow-model bindings (hivecommons/hive#17620, RFC phase 2). + // + // Each repo row on Settings → Repos carries a "Workflow" select: hive-default + // (the built-in lifecycle every unbound repo follows) or any compiled model + // from the library. Binding persists immediately through + // PUT /api/workflows/bindings (owner-only, audited) — it is not part of the + // tab's Save button, because a binding is validated server-side against the + // store (the model must exist and compile) and the tracker picks the new + // columns up on its next poll. + const WORKFLOW_DEFAULT_KEY = 'hive-default@1'; + const _workflowState = { loaded: false, loading: false, enabled: false, workflows: [], bindings: [] }; + + function workflowKey(name, version) { return (name || '') + '@' + (version || ''); } + + async function loadWorkflowLibrary(onDone) { + if (_workflowState.loading) return; + _workflowState.loading = true; + try { + const res = await fetch('/api/workflows', { headers: _inceptionAuthHeaders() }); + if (res.status === 503) { _workflowState.loaded = true; _workflowState.workflows = []; return; } + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const data = await res.json(); + _workflowState.workflows = Array.isArray(data.workflows) ? data.workflows : []; + _workflowState.bindings = Array.isArray(data.bindings) ? data.bindings : []; + _workflowState.enabled = !!data.enabled; + _workflowState.loaded = true; + } catch (err) { + _workflowState.loaded = true; + showToast('Could not load the workflow library: ' + err.message, 'error'); + } finally { + _workflowState.loading = false; + if (typeof onDone === 'function') onDone(); + } + } + + function workflowBindingFor(repo) { + const want = String(repo || '').toLowerCase(); + const org = String((_configState.data && _configState.data.org) || '').toLowerCase(); + return _workflowState.bindings.find(b => { + const r = String(b.repo || '').toLowerCase(); + return r === want || (org && (r === org + '/' + want || want === org + '/' + r)); + }) || null; + } + + // renderRepoWorkflowRow returns the per-repo select, or '' when the hive + // has no workflow store (the row simply does not appear; nothing else on + // the tab changes). + function renderRepoWorkflowRow(repo) { + if (!_workflowState.loaded) { + loadWorkflowLibrary(() => { if (_configState.tab === 'Repos') renderConfigTab('Repos'); }); + return ''; + } + if (!_workflowState.workflows.length) return ''; + const bound = workflowBindingFor(repo); + const current = bound ? workflowKey(bound.name, bound.version) : WORKFLOW_DEFAULT_KEY; + const locked = !dashboardRoleAtLeast(window._hiveRole || 'read', 'owner'); + const options = _workflowState.workflows.map(w => { + const key = workflowKey(w.name, w.version); + const compiled = w.compiled !== false; + const label = key + (w.description ? ' — ' + w.description : '') + (compiled ? '' : ' (draft, does not compile)'); + return ``; + }).join(''); + const flag = _workflowState.enabled + ? '' + : 'derivation off'; + return `
    ${flag}${bound ? `bound` : 'default'}
    `; + } + + async function setRepoWorkflow(repo, value) { + if (!dashboardRoleAtLeast(window._hiveRole || 'read', 'owner')) { + showToast('Owner role is required to bind a workflow.', 'error'); + renderConfigTab('Repos'); + return; + } + const key = String(value || ''); + const body = { repo: repo }; + if (key && key !== WORKFLOW_DEFAULT_KEY) { + const at = key.lastIndexOf('@'); + body.name = key.slice(0, at); + body.version = key.slice(at + 1); + } + try { + const res = await fetch('/api/workflows/bindings', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify(body), + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const data = await res.json(); + _workflowState.bindings = Array.isArray(data.bindings) ? data.bindings : []; + showToast(body.name ? `${repo} now follows ${key}` : `${repo} back on hive-default`); + } catch (err) { + showToast('Failed to bind workflow: ' + err.message, 'error'); + } + renderConfigTab('Repos'); + } diff --git a/src/pkg/dashboard/static-src/js/tracker-filter-render.js b/src/pkg/dashboard/static-src/js/tracker-filter-render.js index c406c9ff17..740f74b828 100644 --- a/src/pkg/dashboard/static-src/js/tracker-filter-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-filter-render.js @@ -87,6 +87,8 @@ } stageTrackerSyncToolbar(f); const ctx = { nowMs, stages, moves: _stageTrackerMoves }; + // Workflow-model columns for bound repositories (hivecommons/hive#17620). + ctx.workflows = d.workflows || null; ctx.workers = stageTrackerWorkers(window._lastStatus); ctx.events = _stageTrackerEvents; ctx.noteTuck = stageTrackerNoteTuckSetting(); diff --git a/src/pkg/dashboard/static-src/js/tracker-row-render.js b/src/pkg/dashboard/static-src/js/tracker-row-render.js index a4f87184a9..ee7a393061 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -63,6 +63,7 @@ // needs-attention count and a mini per-column distribution. Keyed // `group:owner/repo` by the render so the reconcile keeps it stable. function stageTrackerGroupHeaderHtml(g, stages, ctx) { + const groupWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, g.repo) : null; const max = Math.max(1, ...g.cols); const dist = g.cols.map((c, i) => ``).join(''); const attn = g.attention ? `${g.attention} need${g.attention === 1 ? 's' : ''} attention` : ''; @@ -70,10 +71,10 @@ const chipCtx = { repoChips: Object.assign({}, (ctx && ctx.repoChips) || {}) }; return `
    - ${stageTrackerRepoChipHtml(g.repo, chipCtx)}${esc(g.repo)} + ${stageTrackerRepoChipHtml(g.repo, chipCtx)}${esc(g.repo)}${groupWorkflow ? stageTrackerWorkflowBadgeHtml(groupWorkflow) : ''} ${g.count} ${g.count === 1 ? 'row' : 'rows'}${attn} - ${dist} -
    `; + ${groupWorkflow ? '' : `${dist}`} + ${groupWorkflow && !g.collapsed ? stageTrackerWorkflowHeaderHtml(groupWorkflow) : ''}`; } // Row = title line (number, title, chips, since) + thin strip. Non-active @@ -196,6 +197,9 @@ // One note line per row: the human line takes the stage note (folded // or dropped), so the event slot below the caption renders nothing. const rowKey = stageTrackerItemKey(item); + // A repository bound to a workflow model draws the model's columns + // (tracker-workflows.js); null keeps the built-in strip byte for byte. + const rowWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, item.repo) : null; const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; // One human-gate pill per gated row (hivecommons/hive#17470): it @@ -210,7 +214,7 @@
    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} -
      ${stageTrackerStripItems(shown, stages, range, nowMs, sharedUnder ? Object.assign({}, ctx, { gateElsewhere: true }) : ctx)}
    +
      ${rowWorkflow ? stageTrackerWorkflowStripItems(shown, rowWorkflow, stages) : stageTrackerStripItems(shown, stages, range, nowMs, sharedUnder ? Object.assign({}, ctx, { gateElsewhere: true }) : ctx)}
    ${stageTrackerSinceHtml(shown, nowMs)}${typeof stageTrackerPillHtml === 'function' ? stageTrackerPillHtml(shown, stages, range, nowMs, ctx) : ''}
    ${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${typeof stageTrackerNotesPanelHtml === 'function' ? stageTrackerNotesPanelHtml(item, hamNotesCtx(item)) : ''}${subs} `; diff --git a/src/pkg/dashboard/static-src/js/tracker-workflows.js b/src/pkg/dashboard/static-src/js/tracker-workflows.js new file mode 100644 index 0000000000..df16e47b27 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/tracker-workflows.js @@ -0,0 +1,77 @@ + /* ---- Workflow-model columns (hivecommons/hive#17620, RFC phase 2) ----- + GET /api/stage-tracker carries `workflows` only when at least one + repository is bound to a model other than hive-default. For such a + repository the group header names the model and draws the model's own + column header, and each row's strip is one chevron per model column, + placed by the stage/NNN number the row wears. Everything else on the + row (lead cell, chips, human gate, notes) is unchanged. Hives with no + binding never reach this code: stageTrackerWorkflowOf returns null and + the built-in strip renders exactly as before. Pure helpers so the node + harness (stage_tracker_workflows_ui_test.go) can run them. */ + const STAGE_TRACKER_WORKFLOW_UNCOVERED_WORD = 'Not covered'; + + // The model block for repo, or null when the repo follows hive-default + // (unbound, bound to hive-default itself, or bound to a model the + // server reported as unusable — the row then falls back to the + // built-in strip, which is what the engine does too). + function stageTrackerWorkflowOf(ctx, repo) { + const w = ctx && ctx.workflows; + if (!w || !w.repos) return null; + const wf = w.repos[String(repo || '')]; + if (!wf || wf.error || !Array.isArray(wf.columns) || !wf.columns.length) return null; + if (w.default && wf.name === w.default.name && wf.version === w.default.version) return null; + return wf; + } + + // Index of the column holding stage number `stage`; 0 for an unstaged + // item (the first column is the model's entry), the terminal column for + // a terminal stage, -1 when no column anchors the number (the model + // does not cover it: the engine abstained with "workflow: not covered"). + function stageTrackerWorkflowColumnIndex(wf, stage) { + const n = Number(stage) || 0; + const cols = wf.columns; + if (n === 0) return 0; + if (n >= (typeof STAGE_TRACKER_TERMINAL === 'number' ? STAGE_TRACKER_TERMINAL : 110)) { + const t = cols.findIndex(c => c.terminal); + return t >= 0 ? t : cols.length - 1; + } + return cols.findIndex(c => Array.isArray(c.numbers) && c.numbers.indexOf(n) >= 0); + } + + function stageTrackerWorkflowBadgeHtml(wf) { + if (!wf) return ''; + const key = `${wf.name}@${wf.version}`; + return `${esc(key)}`; + } + + // The model's column header, drawn under a bound repository's group + // header in place of the shared hive-default header. + function stageTrackerWorkflowHeaderHtml(wf) { + const cols = wf.columns.map(c => `
  • ${esc(c.label)}
  • `).join(''); + return ``; + } + + // One row's strip under its model: done before the anchored column, + // active at it (the stage's own word from `stages`, or the column + // label), todo after. An uncovered stage lights the first column amber + // with the "Not covered" word so the gap is visible, not silent. + function stageTrackerWorkflowStripItems(item, wf, stages) { + const cur = Number(item.stage) || 0; + const terminal = cur >= (typeof STAGE_TRACKER_TERMINAL === 'number' ? STAGE_TRACKER_TERMINAL : 110); + let at = stageTrackerWorkflowColumnIndex(wf, cur); + const uncovered = at < 0; + if (uncovered) at = 0; + const st = (stages || []).find(s => Number(s.number) === cur) || {}; + return wf.columns.map((c, i) => { + let state = 'todo'; + if (terminal || i < at) state = 'done'; + else if (i === at) state = 'active'; + if (terminal && c.terminal) state = 'active'; + const word = state !== 'active' ? c.label : (uncovered ? STAGE_TRACKER_WORKFLOW_UNCOVERED_WORD : (st.short || st.label || c.label)); + const tip = state === 'active' && uncovered + ? `stage/${String(cur).padStart(3, '0')} is not a state of ${wf.name}@${wf.version}; the engine leaves this item where it is.` + : (c.hint || c.label) + (state === 'active' && cur ? ` — stage/${String(cur).padStart(3, '0')}` : ''); + const cls = ['ham-seg', 'ham-wf-seg', state, c.terminal ? 'cap' : '', uncovered && state === 'active' ? 'ham-wf-uncovered' : ''].filter(Boolean).join(' '); + return `
  • ${esc(word)}
  • `; + }).join(''); + } diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 2ba70649aa..2d894fd79b 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -75,6 +75,7 @@ js/tracker-words.js js/tracker-row-anchor.js js/tracker-row.js js/tracker-row-strip.js +js/tracker-workflows.js js/tracker-row-acted.js js/tracker-human-attention.js js/tracker-row-layout.js @@ -133,6 +134,7 @@ js/config-tabs.js js/config-hub.js js/config-agent.js js/config-governor.js +js/config-workflows.js js/config-watchdog-security.js js/config-features.js js/integration-execution-settings.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 9f8fc21453..882ab9ce19 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1612,6 +1612,13 @@ .ham-group-n, .ham-group-attn { flex: 0 0 auto; font-size: var(--fs-xs); color: var(--text-faint); white-space: nowrap; } .ham-group-attn { color: var(--amber); } .ham-group-collapsed .ham-group-name { color: var(--muted); } + /* Workflow-model columns (RFC 17620): the model badge on a + bound repository's group header, its own column header, and the + "Not covered" chevron for a stage the model has no state for. */ + .ham-wf-badge { flex: 0 0 auto; font-family: var(--font-mono); font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.02em; padding: var(--sp-1) var(--sp-3); border-radius: var(--r-pill); white-space: nowrap; color: var(--indigo); background: color-mix(in srgb, var(--indigo) 12%, transparent); border: 1px solid color-mix(in srgb, var(--indigo) 40%, transparent); } + .ham-wf-cols { position: static; } + .ham-wf-cols .ham-wf-col { color: var(--indigo); } + .ham-seg.ham-wf-uncovered { background: color-mix(in srgb, var(--amber) 18%, transparent); color: var(--amber); outline: 1px dashed var(--amber); } .ham-group-dist { flex: 0 0 auto; margin-left: auto; margin-right: calc(4em + var(--sp-3)); display: inline-flex; align-items: flex-end; gap: var(--sp-1); height: 0.9em; } .ham-gd { display: inline-block; width: 0.45em; height: 15%; border-radius: var(--sp-1); background: color-mix(in srgb, var(--text-faint) 35%, transparent); } .ham-gd-1 { height: 35%; background: color-mix(in srgb, var(--amber) 55%, transparent); } @@ -20022,6 +20029,83 @@

    Where to get help

    const rm = item && item.rebase_merge; return !!(rm && (rm.state === 'approved' || rm.state === 'rebasing' || rm.state === 'ci-pending')); } + /* ---- Workflow-model columns (hivecommons/hive#17620, RFC phase 2) ----- + GET /api/stage-tracker carries `workflows` only when at least one + repository is bound to a model other than hive-default. For such a + repository the group header names the model and draws the model's own + column header, and each row's strip is one chevron per model column, + placed by the stage/NNN number the row wears. Everything else on the + row (lead cell, chips, human gate, notes) is unchanged. Hives with no + binding never reach this code: stageTrackerWorkflowOf returns null and + the built-in strip renders exactly as before. Pure helpers so the node + harness (stage_tracker_workflows_ui_test.go) can run them. */ + const STAGE_TRACKER_WORKFLOW_UNCOVERED_WORD = 'Not covered'; + + // The model block for repo, or null when the repo follows hive-default + // (unbound, bound to hive-default itself, or bound to a model the + // server reported as unusable — the row then falls back to the + // built-in strip, which is what the engine does too). + function stageTrackerWorkflowOf(ctx, repo) { + const w = ctx && ctx.workflows; + if (!w || !w.repos) return null; + const wf = w.repos[String(repo || '')]; + if (!wf || wf.error || !Array.isArray(wf.columns) || !wf.columns.length) return null; + if (w.default && wf.name === w.default.name && wf.version === w.default.version) return null; + return wf; + } + + // Index of the column holding stage number `stage`; 0 for an unstaged + // item (the first column is the model's entry), the terminal column for + // a terminal stage, -1 when no column anchors the number (the model + // does not cover it: the engine abstained with "workflow: not covered"). + function stageTrackerWorkflowColumnIndex(wf, stage) { + const n = Number(stage) || 0; + const cols = wf.columns; + if (n === 0) return 0; + if (n >= (typeof STAGE_TRACKER_TERMINAL === 'number' ? STAGE_TRACKER_TERMINAL : 110)) { + const t = cols.findIndex(c => c.terminal); + return t >= 0 ? t : cols.length - 1; + } + return cols.findIndex(c => Array.isArray(c.numbers) && c.numbers.indexOf(n) >= 0); + } + + function stageTrackerWorkflowBadgeHtml(wf) { + if (!wf) return ''; + const key = `${wf.name}@${wf.version}`; + return `${esc(key)}`; + } + + // The model's column header, drawn under a bound repository's group + // header in place of the shared hive-default header. + function stageTrackerWorkflowHeaderHtml(wf) { + const cols = wf.columns.map(c => `
  • ${esc(c.label)}
  • `).join(''); + return ``; + } + + // One row's strip under its model: done before the anchored column, + // active at it (the stage's own word from `stages`, or the column + // label), todo after. An uncovered stage lights the first column amber + // with the "Not covered" word so the gap is visible, not silent. + function stageTrackerWorkflowStripItems(item, wf, stages) { + const cur = Number(item.stage) || 0; + const terminal = cur >= (typeof STAGE_TRACKER_TERMINAL === 'number' ? STAGE_TRACKER_TERMINAL : 110); + let at = stageTrackerWorkflowColumnIndex(wf, cur); + const uncovered = at < 0; + if (uncovered) at = 0; + const st = (stages || []).find(s => Number(s.number) === cur) || {}; + return wf.columns.map((c, i) => { + let state = 'todo'; + if (terminal || i < at) state = 'done'; + else if (i === at) state = 'active'; + if (terminal && c.terminal) state = 'active'; + const word = state !== 'active' ? c.label : (uncovered ? STAGE_TRACKER_WORKFLOW_UNCOVERED_WORD : (st.short || st.label || c.label)); + const tip = state === 'active' && uncovered + ? `stage/${String(cur).padStart(3, '0')} is not a state of ${wf.name}@${wf.version}; the engine leaves this item where it is.` + : (c.hint || c.label) + (state === 'active' && cur ? ` — stage/${String(cur).padStart(3, '0')}` : ''); + const cls = ['ham-seg', 'ham-wf-seg', state, c.terminal ? 'cap' : '', uncovered && state === 'active' ? 'ham-wf-uncovered' : ''].filter(Boolean).join(' '); + return `
  • ${esc(word)}
  • `; + }).join(''); + } const STAGE_TRACKER_ACTED_STATES = ['waiting', 'addressed', 'stuck', 'pending', 'failed', 'executing', 'blocked']; const STAGE_TRACKER_ACTED_FILTERS = ['any', 'awaiting', 'acted', 'stuck']; const STAGE_TRACKER_ACTED_STUCK_DEFAULT_S = 30 * 60; @@ -20968,6 +21052,7 @@

    Where to get help

    // needs-attention count and a mini per-column distribution. Keyed // `group:owner/repo` by the render so the reconcile keeps it stable. function stageTrackerGroupHeaderHtml(g, stages, ctx) { + const groupWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, g.repo) : null; const max = Math.max(1, ...g.cols); const dist = g.cols.map((c, i) => ``).join(''); const attn = g.attention ? `${g.attention} need${g.attention === 1 ? 's' : ''} attention` : ''; @@ -20975,10 +21060,10 @@

    Where to get help

    const chipCtx = { repoChips: Object.assign({}, (ctx && ctx.repoChips) || {}) }; return `
    - ${stageTrackerRepoChipHtml(g.repo, chipCtx)}${esc(g.repo)} + ${stageTrackerRepoChipHtml(g.repo, chipCtx)}${esc(g.repo)}${groupWorkflow ? stageTrackerWorkflowBadgeHtml(groupWorkflow) : ''} ${g.count} ${g.count === 1 ? 'row' : 'rows'}${attn} - ${dist} -
    `; + ${groupWorkflow ? '' : `${dist}`} + ${groupWorkflow && !g.collapsed ? stageTrackerWorkflowHeaderHtml(groupWorkflow) : ''}`; } // Row = title line (number, title, chips, since) + thin strip. Non-active @@ -21101,6 +21186,9 @@

    Where to get help

    // One note line per row: the human line takes the stage note (folded // or dropped), so the event slot below the caption renders nothing. const rowKey = stageTrackerItemKey(item); + // A repository bound to a workflow model draws the model's columns + // (tracker-workflows.js); null keeps the built-in strip byte for byte. + const rowWorkflow = typeof stageTrackerWorkflowOf === 'function' ? stageTrackerWorkflowOf(ctx, item.repo) : null; const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; // One human-gate pill per gated row (hivecommons/hive#17470): it @@ -21115,7 +21203,7 @@

    Where to get help

    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} -
      ${stageTrackerStripItems(shown, stages, range, nowMs, sharedUnder ? Object.assign({}, ctx, { gateElsewhere: true }) : ctx)}
    +
      ${rowWorkflow ? stageTrackerWorkflowStripItems(shown, rowWorkflow, stages) : stageTrackerStripItems(shown, stages, range, nowMs, sharedUnder ? Object.assign({}, ctx, { gateElsewhere: true }) : ctx)}
    ${stageTrackerSinceHtml(shown, nowMs)}${typeof stageTrackerPillHtml === 'function' ? stageTrackerPillHtml(shown, stages, range, nowMs, ctx) : ''}
    ${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${typeof stageTrackerNotesPanelHtml === 'function' ? stageTrackerNotesPanelHtml(item, hamNotesCtx(item)) : ''}${subs} `; @@ -23621,6 +23709,8 @@

    All labels

    } stageTrackerSyncToolbar(f); const ctx = { nowMs, stages, moves: _stageTrackerMoves }; + // Workflow-model columns for bound repositories (hivecommons/hive#17620). + ctx.workflows = d.workflows || null; ctx.workers = stageTrackerWorkers(window._lastStatus); ctx.events = _stageTrackerEvents; ctx.noteTuck = stageTrackerNoteTuckSetting(); @@ -65011,7 +65101,7 @@

    Clanker-requested PRs

    `; // Fully forge-qualified so the row is unambiguous: github.ibm.com/org/repo. const displayName = ghHost + '/' + r; - return `
    ${isDefault ? '★' : '☆'}${esc(displayName)}${inheritButton}${rtRow}${cbRow}${pillLabel}
    ` + ldSub; + return `
    ${isDefault ? '★' : '☆'}${esc(displayName)}${inheritButton}${rtRow}${cbRow}${pillLabel}
    ` + ldSub + renderRepoWorkflowRow(r); }).join(''); const hostNote = isGHE ? ` on ${esc(ghHost)} (GitHub Enterprise)` @@ -66055,6 +66145,102 @@

    Agent Watchdog

    — fixed progression; the last step is the cap. `; } + // Workflow-model bindings (hivecommons/hive#17620, RFC phase 2). + // + // Each repo row on Settings → Repos carries a "Workflow" select: hive-default + // (the built-in lifecycle every unbound repo follows) or any compiled model + // from the library. Binding persists immediately through + // PUT /api/workflows/bindings (owner-only, audited) — it is not part of the + // tab's Save button, because a binding is validated server-side against the + // store (the model must exist and compile) and the tracker picks the new + // columns up on its next poll. + const WORKFLOW_DEFAULT_KEY = 'hive-default@1'; + const _workflowState = { loaded: false, loading: false, enabled: false, workflows: [], bindings: [] }; + + function workflowKey(name, version) { return (name || '') + '@' + (version || ''); } + + async function loadWorkflowLibrary(onDone) { + if (_workflowState.loading) return; + _workflowState.loading = true; + try { + const res = await fetch('/api/workflows', { headers: _inceptionAuthHeaders() }); + if (res.status === 503) { _workflowState.loaded = true; _workflowState.workflows = []; return; } + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const data = await res.json(); + _workflowState.workflows = Array.isArray(data.workflows) ? data.workflows : []; + _workflowState.bindings = Array.isArray(data.bindings) ? data.bindings : []; + _workflowState.enabled = !!data.enabled; + _workflowState.loaded = true; + } catch (err) { + _workflowState.loaded = true; + showToast('Could not load the workflow library: ' + err.message, 'error'); + } finally { + _workflowState.loading = false; + if (typeof onDone === 'function') onDone(); + } + } + + function workflowBindingFor(repo) { + const want = String(repo || '').toLowerCase(); + const org = String((_configState.data && _configState.data.org) || '').toLowerCase(); + return _workflowState.bindings.find(b => { + const r = String(b.repo || '').toLowerCase(); + return r === want || (org && (r === org + '/' + want || want === org + '/' + r)); + }) || null; + } + + // renderRepoWorkflowRow returns the per-repo select, or '' when the hive + // has no workflow store (the row simply does not appear; nothing else on + // the tab changes). + function renderRepoWorkflowRow(repo) { + if (!_workflowState.loaded) { + loadWorkflowLibrary(() => { if (_configState.tab === 'Repos') renderConfigTab('Repos'); }); + return ''; + } + if (!_workflowState.workflows.length) return ''; + const bound = workflowBindingFor(repo); + const current = bound ? workflowKey(bound.name, bound.version) : WORKFLOW_DEFAULT_KEY; + const locked = !dashboardRoleAtLeast(window._hiveRole || 'read', 'owner'); + const options = _workflowState.workflows.map(w => { + const key = workflowKey(w.name, w.version); + const compiled = w.compiled !== false; + const label = key + (w.description ? ' — ' + w.description : '') + (compiled ? '' : ' (draft, does not compile)'); + return ``; + }).join(''); + const flag = _workflowState.enabled + ? '' + : 'derivation off'; + return `
    ${flag}${bound ? `bound` : 'default'}
    `; + } + + async function setRepoWorkflow(repo, value) { + if (!dashboardRoleAtLeast(window._hiveRole || 'read', 'owner')) { + showToast('Owner role is required to bind a workflow.', 'error'); + renderConfigTab('Repos'); + return; + } + const key = String(value || ''); + const body = { repo: repo }; + if (key && key !== WORKFLOW_DEFAULT_KEY) { + const at = key.lastIndexOf('@'); + body.name = key.slice(0, at); + body.version = key.slice(at + 1); + } + try { + const res = await fetch('/api/workflows/bindings', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify(body), + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const data = await res.json(); + _workflowState.bindings = Array.isArray(data.bindings) ? data.bindings : []; + showToast(body.name ? `${repo} now follows ${key}` : `${repo} back on hive-default`); + } catch (err) { + showToast('Failed to bind workflow: ' + err.message, 'error'); + } + renderConfigTab('Repos'); + } // ── Watchdog activity strip (#7254) ────────────────────────────────────── // "Review the watchdog-*-observed entries in the Audit Log, then switch to // Heal" is only a data-driven decision if the data is on the page. The diff --git a/src/pkg/dashboard/webstatic/style_ratchet_test.go b/src/pkg/dashboard/webstatic/style_ratchet_test.go index fa47c8fa53..36f02d81d0 100644 --- a/src/pkg/dashboard/webstatic/style_ratchet_test.go +++ b/src/pkg/dashboard/webstatic/style_ratchet_test.go @@ -28,9 +28,9 @@ var styleRatchetBaselines = map[string]styleRatchetCounts{ // v6 carries surfaces v5 does not have (runs section, standby, wavefront // fan-out UI); these baselines are v6's own counts, not v5's. "operator static/index.html": { - inlineStyles: 1508, - rawColors: 136, - rawFontSizes: 622, + inlineStyles: 1489, + rawColors: 135, + rawFontSizes: 614, rawPadding: 212, rawBorderRadii: 180, }, @@ -42,7 +42,7 @@ var styleRatchetBaselines = map[string]styleRatchetCounts{ rawBorderRadii: 53, }, "hub static pages": { - inlineStyles: 939, + inlineStyles: 928, rawColors: 448, rawFontSizes: 425, rawPadding: 164, diff --git a/src/pkg/stageengine/export_parity_test.go b/src/pkg/stageengine/export_parity_test.go new file mode 100644 index 0000000000..6d30a22fc7 --- /dev/null +++ b/src/pkg/stageengine/export_parity_test.go @@ -0,0 +1,44 @@ +package stageengine + +import ( + "github.com/hivecommons/hive/pkg/claims" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// ParityFacts hands the external parity test (workflow_parity_test.go, +// package stageengine_test — it imports hivedefault, which imports this +// package, so it cannot live here) the Facts corpus the built-in derivers +// are pinned by: every generated PR stage golden plus a sweep of issue +// facts reaching each issue stage. hivecommons/hive#17620. +func ParityFacts() []Facts { + var out []Facts + for _, cases := range generateStageGoldens() { + for _, c := range cases { + _, f := runStageGoldenWithFacts(c.Input) + out = append(out, f) + } + } + pr99 := &Ref{Owner: "acme", Repo: "widgets", Number: 99, Kind: stagelabels.PRItem} + for _, mut := range []func(f *Facts){ + nil, + func(f *Facts) { f.Issue.Bucket = BucketDependencyDashboard; f.Park.NeedsHuman = true }, + func(f *Facts) { f.Issue.TriageAwaiting = "carries needs-triage" }, + func(f *Facts) { + f.Issue.Bucket = BucketClaimed + f.Issue.Claim = &ClaimFact{Holder: "bob", Kind: "human"} + }, + func(f *Facts) { + f.Issue.Bucket = BucketClaimed + f.Issue.Claim = &ClaimFact{Kind: claims.KindAgent, PRStarted: true} + }, + func(f *Facts) { f.Issue.Bucket = BucketCoveredByPR; f.Issue.CoveringPR = pr99 }, + func(f *Facts) { f.Park.NeedsHuman = true }, + func(f *Facts) { f.Park.PossiblyExists = true }, + func(f *Facts) { f.Issue.DiscussionLabel = "proposal" }, + func(f *Facts) { f.Open = false }, + func(f *Facts) { f.Issue.Bucket = BucketFiltered }, + } { + out = append(out, derivedIssueFacts(mut)) + } + return out +} diff --git a/src/pkg/stageengine/reconciler.go b/src/pkg/stageengine/reconciler.go index 3d265e6eb0..9089dea26a 100644 --- a/src/pkg/stageengine/reconciler.go +++ b/src/pkg/stageengine/reconciler.go @@ -10,6 +10,7 @@ import ( "time" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" ) // Transition is what Reconcile reports to its caller and the audit log. @@ -38,14 +39,23 @@ type Reconciler interface { // Options configures New. type Options struct { - Mode Mode - Store *stagelabels.Store // stagelabels.Shared() by default; API unchanged - Writer StageWriter - Issue Deriver // defaults to DeriveIssue - PR Deriver // defaults to DerivePR - Now func() time.Time - Logger *slog.Logger - Metrics Metrics + Mode Mode + Store *stagelabels.Store // stagelabels.Shared() by default; API unchanged + Writer StageWriter + Issue Deriver // defaults to DeriveIssue + PR Deriver // defaults to DerivePR + // Workflow, when set, derives through the compiled workflow model + // (DeriveFromModel) and overrides Issue and PR. hivecommons/hive#17620. + Workflow *workflowmodel.Profile + // WorkflowFor, when set, resolves the compiled model bound to a + // repository (owner/repo) at derivation time; nil means the repository + // is unbound and the Issue/PR derivers run unchanged. It composes with + // Workflow: Workflow is the engine-wide model, WorkflowFor the + // per-repository override. hivecommons/hive#17620 (RFC phase 2). + WorkflowFor func(owner, repo string) *workflowmodel.Profile + Now func() time.Time + Logger *slog.Logger + Metrics Metrics } // ErrNoWriter is returned by an enforce-mode Reconcile with no Writer. @@ -73,12 +83,20 @@ func New(o Options) Reconciler { if o.Store == nil { o.Store = stagelabels.Shared() } + if o.Workflow != nil { + o.Issue = DeriveFromModel(o.Workflow, stagelabels.IssueItem) + o.PR = DeriveFromModel(o.Workflow, stagelabels.PRItem) + } if o.Issue == nil { o.Issue = IssueDeriver() } if o.PR == nil { o.PR = PRDeriver() } + if o.WorkflowFor != nil { + o.Issue = DeriveForRepo(o.WorkflowFor, o.Issue) + o.PR = DeriveForRepo(o.WorkflowFor, o.PR) + } if o.Now == nil { o.Now = time.Now } diff --git a/src/pkg/stageengine/workflow.go b/src/pkg/stageengine/workflow.go new file mode 100644 index 0000000000..f344eef66f --- /dev/null +++ b/src/pkg/stageengine/workflow.go @@ -0,0 +1,339 @@ +package stageengine + +import ( + "fmt" + "strings" + "sync" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +// DeriveForRepo returns a Deriver of fallback's kind that derives through +// the model lookup returns for the item's repository, or through fallback +// when lookup returns nil. Profiles are compiled per lookup result and +// cached by hash, so a rebinding takes effect on the next derivation. +func DeriveForRepo(lookup func(owner, repo string) *workflowmodel.Profile, fallback Deriver) Deriver { + if lookup == nil || fallback == nil { + return fallback + } + kind := fallback.Kind() + var mu sync.Mutex + cache := map[string]Deriver{} + return DeriverFunc(kind, func(f Facts) Decision { + p := lookup(f.Ref.Owner, f.Ref.Repo) + if p == nil { + return fallback.Derive(f) + } + mu.Lock() + d, ok := cache[p.Hash] + if !ok { + d = DeriveFromModel(p, kind) + cache[p.Hash] = d + } + mu.Unlock() + return d.Derive(f) + }) +} + +// DeriveFromModel is the third Deriver (hivecommons/hive#17620 "One +// engine, one writer"): it derives an item's stage under a compiled +// workflow model and produces the same Decision the built-in derivers do, +// so the Reconciler stays the only label writer. +// +// Under derivation mode builtin the built-in deriver for kind decides and +// the model only has to cover the stage it produced; a stage the model has +// no state for is "not covered" and the deriver abstains (fail closed, +// never a silent fall-through). Under mode rules the model's ordered rules +// are evaluated over Facts; the first rule whose predicates all hold names +// the state, and an item no rule matches is not covered. +func DeriveFromModel(p *workflowmodel.Profile, kind stagelabels.Item) Deriver { + if p == nil { + return builtinDeriver(kind) + } + return modelDeriver{p: p, kind: kind, inner: builtinDeriver(kind)} +} + +func builtinDeriver(kind stagelabels.Item) Deriver { + if kind == stagelabels.PRItem { + return prDeriverF + } + return issueDeriverF +} + +type modelDeriver struct { + p *workflowmodel.Profile + kind stagelabels.Item + inner Deriver +} + +func (d modelDeriver) Kind() stagelabels.Item { return d.kind } + +// ReasonNotCovered prefixes every abstention the model forces. +const ReasonNotCovered = "workflow: not covered" + +func (d modelDeriver) Derive(f Facts) Decision { + if f.Ref.Kind != d.kind { + return abstain(reasonKindMismatch) + } + switch d.p.Mode { + case workflowmodel.DerivationBuiltin: + dec := d.inner.Derive(f) + if dec.Abstain || dec.Stage == stagelabels.None { + return dec + } + if _, ok := d.p.StateForNumber(dec.Stage.Number()); !ok { + return abstain(fmt.Sprintf("%s: %s@%s has no state for stage %s", ReasonNotCovered, d.p.Name, d.p.Version, dec.Stage)) + } + return dec + case workflowmodel.DerivationRules: + return d.rules(f) + } + return abstain(fmt.Sprintf("%s: %s@%s has derivation mode %q", ReasonNotCovered, d.p.Name, d.p.Version, d.p.Mode)) +} + +// rules evaluates the profile's rules in order. +func (d modelDeriver) rules(f Facts) Decision { + want := workflowmodel.KindIssue + if d.kind == stagelabels.PRItem { + want = workflowmodel.KindPR + } + for i, r := range d.p.Rules { + if r.Kind != workflowmodel.KindAny && r.Kind != want { + continue + } + if !holdsAll(f, r.When) { + continue + } + id := r.ID + if id == "" { + id = fmt.Sprintf("rules[%d]", i) + } + reason := r.Reason + if reason == "" { + reason = fmt.Sprintf("workflow %s@%s: rule %s", d.p.Name, d.p.Version, id) + } + return d.decisionFor(r.State, reason, f) + } + return abstain(fmt.Sprintf("%s: %s@%s has no rule for this %s", ReasonNotCovered, d.p.Name, d.p.Version, want)) +} + +// decisionFor turns a model state into a Decision: its stage number maps +// to the stage label, a terminal state with no number is Stage None. +func (d modelDeriver) decisionFor(state, reason string, f Facts) Decision { + st := d.p.States[state] + if st == nil { + return abstain(fmt.Sprintf("%s: state %q is not in %s@%s", ReasonNotCovered, state, d.p.Name, d.p.Version)) + } + dec := Decision{Reason: reason, Kind: f.Author.Kind, Role: f.Author.Role} + if st.Lifecycle.Number == 0 { + if d.p.Terminal[state] { + dec.Terminal = true + return dec + } + return abstain(fmt.Sprintf("%s: state %q carries no stage number and is not terminal", ReasonNotCovered, state)) + } + stage, ok := stageByNumber(st.Lifecycle.Number) + if !ok { + return abstain(fmt.Sprintf("%s: state %q stage number %d is not in the stage table", ReasonNotCovered, state, st.Lifecycle.Number)) + } + if !stage.Applies(d.kind) { + return abstain(fmt.Sprintf("%s: state %q stage number %d is not a %s stage", ReasonNotCovered, state, st.Lifecycle.Number, d.kind)) + } + dec.Stage = stage + if f.PR != nil { + dec.DCO = f.PR.DCO + } + return dec +} + +func stageByNumber(n int) (stagelabels.Stage, bool) { + for _, def := range stagelabels.Table { + if def.Number == n { + return def.Stage, true + } + } + return stagelabels.None, false +} + +func holdsAll(f Facts, preds []workflowmodel.Predicate) bool { + for _, p := range preds { + if !holds(f, p) { + return false + } + } + return true +} + +// holds evaluates one predicate from the workflowmodel.Facts vocabulary. +// An unknown fact or a mismatched operator is false: the compiler has +// already refused such a model, so this is defence in depth. +func holds(f Facts, p workflowmodel.Predicate) bool { + switch workflowmodel.Facts[p.Fact] { + case workflowmodel.FactBool: + v, ok := boolFact(f, p.Fact) + if !ok { + return false + } + return (p.Op == workflowmodel.OpTrue) == v + case workflowmodel.FactScalar: + v, ok := scalarFact(f, p.Fact) + if !ok { + return false + } + eq := strings.EqualFold(v, p.Value) + return (p.Op == workflowmodel.OpIs) == eq + case workflowmodel.FactSet: + set, ok := setFact(f, p.Fact) + if !ok { + return false + } + has := false + for _, s := range set { + if matchGlob(p.Value, s) { + has = true + break + } + } + return (p.Op == workflowmodel.OpHas) == has + } + return false +} + +// matchGlob matches value against pattern, where a trailing `*` matches +// any suffix. Comparison is case-insensitive, as labels are. +func matchGlob(pattern, value string) bool { + if strings.HasSuffix(pattern, "*") { + return strings.HasPrefix(strings.ToLower(value), strings.ToLower(strings.TrimSuffix(pattern, "*"))) + } + return strings.EqualFold(pattern, value) +} + +func boolFact(f Facts, name string) (bool, bool) { + switch name { + case "open": + return f.Open, true + case "merged": + return f.Merged, true + case "draft": + return f.Draft, true + case "hold": + return len(f.Park.Holds) > 0, true + case "park": + return f.Park.NeedsHuman || f.Park.DecisionLabel != "" || f.Park.PossiblyExists, true + case "issue.claimed": + return f.Issue != nil && f.Issue.Claim != nil, true + case "issue.covered": + return f.Issue != nil && f.Issue.CoveringPR != nil, true + case "issue.stalled": + return f.Issue != nil && f.Issue.Stalled, true + case "issue.open_children": + return f.Issue != nil && f.Issue.OpenChildren > 0, true + case "pr.changes_requested": + return f.PR != nil && f.PR.ChangesRequested, true + case "pr.conflicting": + return f.PR != nil && f.PR.Conflicting, true + case "pr.head_fresh": + return f.PR != nil && f.PR.HeadFresh, true + } + return false, false +} + +// Scalar fact values. pr.checks: green | red | pending | missing | unknown. +// pr.review: pending | approved | changes_requested | unavailable. +// pr.dco: yes | no | unknown. author.kind: human | hive | clanker | unknown. +func scalarFact(f Facts, name string) (string, bool) { + switch name { + case "origin": + return f.Origin, true + case "author.kind": + return authorKindName(f.Author.Kind), true + case "author.login": + return f.Author.Login, true + case "issue.bucket": + if f.Issue == nil { + return "", true + } + return string(f.Issue.Bucket), true + case "pr.checks": + if f.PR == nil { + return "", true + } + return checksName(f.PR.Checks), true + case "pr.review": + if f.PR == nil { + return "", true + } + return reviewName(f.PR.Review.State), true + case "pr.dco": + if f.PR == nil { + return "", true + } + return dcoName(f.PR.DCO), true + case "pr.base": + if f.PR == nil { + return "", true + } + return f.PR.BaseRef, true + case "pipeline.status": + // Post-merge runs are not observed yet (see workflowmodel.Facts). + return "unknown", true + } + return "", false +} + +func setFact(f Facts, name string) ([]string, bool) { + if name == "labels" { + return f.Labels, true + } + return nil, false +} + +func authorKindName(k authorkind.Kind) string { + switch k { + case authorkind.Human: + return "human" + case authorkind.Hive: + return "hive" + case authorkind.Clanker: + return "clanker" + } + return "unknown" +} + +func checksName(c stagelabels.CheckSummary) string { + switch { + case !c.Known: + return "unknown" + case len(c.Red) > 0: + return "red" + case len(c.Missing) > 0: + return "missing" + case c.Pending > 0: + return "pending" + } + return "green" +} + +func reviewName(s stagelabels.VerdictState) string { + switch s { + case stagelabels.VerdictApproved: + return "approved" + case stagelabels.VerdictChangesRequested: + return "changes_requested" + case stagelabels.VerdictUnavailable: + return "unavailable" + } + return "pending" +} + +func dcoName(d stagelabels.DCOState) string { + switch d { + case stagelabels.DCOYes: + return "yes" + case stagelabels.DCONo: + return "no" + } + return "unknown" +} diff --git a/src/pkg/stageengine/workflow_parity_test.go b/src/pkg/stageengine/workflow_parity_test.go new file mode 100644 index 0000000000..665e6f16c0 --- /dev/null +++ b/src/pkg/stageengine/workflow_parity_test.go @@ -0,0 +1,147 @@ +package stageengine_test + +import ( + "reflect" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// TestDeriveFromModelHiveDefaultParity is the RFC's P1 bar +// (hivecommons/hive#17620): under the generated hive-default model every +// Decision is identical to the built-in derivers', across the whole PR +// golden corpus and the issue stage sweep. +func TestDeriveFromModelHiveDefaultParity(t *testing.T) { + p := hivedefault.Profile() + derivers := map[stagelabels.Item][2]stageengine.Deriver{ + stagelabels.IssueItem: {stageengine.IssueDeriver(), stageengine.DeriveFromModel(p, stagelabels.IssueItem)}, + stagelabels.PRItem: {stageengine.PRDeriver(), stageengine.DeriveFromModel(p, stagelabels.PRItem)}, + } + facts := stageengine.ParityFacts() + if len(facts) < 100 { + t.Fatalf("parity corpus has only %d facts", len(facts)) + } + stages := map[stagelabels.Stage]bool{} + for i, f := range facts { + d := derivers[f.Ref.Kind] + want, got := d[0].Derive(f), d[1].Derive(f) + if !reflect.DeepEqual(want, got) { + t.Errorf("facts[%d] %s: built-in %+v, hive-default %+v", i, f.Ref.Key(), want, got) + } + if !want.Abstain && !want.Terminal { + stages[want.Stage] = true + } + } + if len(stages) < 15 { + t.Errorf("corpus reached only %d stages: %v", len(stages), stages) + } +} + +// A nil profile is the built-in deriver, and a model that is missing a +// stage the built-in deriver produced abstains "not covered" rather than +// writing a label the model does not know. +func TestDeriveFromModelCoverage(t *testing.T) { + f := stageengine.ParityFacts()[0] + if f.Ref.Kind != stagelabels.PRItem { + t.Fatalf("expected a PR fixture first, got %s", f.Ref.Kind) + } + nilD := stageengine.DeriveFromModel(nil, stagelabels.PRItem) + if got, want := nilD.Derive(f), stageengine.PRDeriver().Derive(f); !reflect.DeepEqual(got, want) { + t.Fatalf("nil profile: %+v != %+v", got, want) + } + if stageengine.DeriveFromModel(nil, stagelabels.IssueItem).Derive(f).Abstain != true { + t.Fatal("kind mismatch must abstain") + } + + base := stageengine.PRDeriver().Derive(f) + if base.Abstain || base.Terminal { + t.Skipf("first fixture is %+v; coverage case needs a staged PR", base) + } + m := hivedefault.Generate() + drop := hivedefault.StateID(base.Stage) + var kept []workflowmodel.State + for _, s := range m.Spec.States { + if s.ID != drop { + kept = append(kept, s) + } + } + m.Spec.States = kept + var tr []workflowmodel.Transition + for _, x := range m.Spec.Transitions { + if x.From != drop && x.To != drop { + tr = append(tr, x) + } + } + m.Spec.Transitions = tr + for i := range m.Spec.Columns { + var st []string + for _, s := range m.Spec.Columns[i].States { + if s != drop { + st = append(st, s) + } + } + m.Spec.Columns[i].States = st + } + for i := range m.Spec.Agents { + var st []string + for _, s := range m.Spec.Agents[i].States { + if s != drop { + st = append(st, s) + } + } + m.Spec.Agents[i].States = st + } + p, _, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("trimmed model: %v", err) + } + got := stageengine.DeriveFromModel(p, stagelabels.PRItem).Derive(f) + if !got.Abstain || !strings.HasPrefix(got.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("missing state %s: got %+v", drop, got) + } +} + +// DeriveForRepo routes bound repositories through their model and leaves +// unbound repositories on the built-in deriver, decision for decision. +func TestDeriveForRepo(t *testing.T) { + p := hivedefault.Profile() + calls := 0 + lookup := func(owner, repo string) *workflowmodel.Profile { + calls++ + if repo == "bound" { + return p + } + return nil + } + if stageengine.DeriveForRepo(nil, stageengine.PRDeriver()) == nil || stageengine.DeriveForRepo(lookup, nil) != nil { + t.Fatal("nil handling") + } + derivers := map[stagelabels.Item][2]stageengine.Deriver{ + stagelabels.IssueItem: {stageengine.IssueDeriver(), stageengine.DeriveForRepo(lookup, stageengine.IssueDeriver())}, + stagelabels.PRItem: {stageengine.PRDeriver(), stageengine.DeriveForRepo(lookup, stageengine.PRDeriver())}, + } + if derivers[stagelabels.PRItem][1].Kind() != stagelabels.PRItem { + t.Fatal("kind") + } + for i, f := range stageengine.ParityFacts() { + for _, repo := range []string{"bound", "free"} { + f.Ref.Repo = repo + d := derivers[f.Ref.Kind] + if want, got := d[0].Derive(f), d[1].Derive(f); !reflect.DeepEqual(want, got) { + t.Errorf("facts[%d] %s/%s: built-in %+v, routed %+v", i, repo, f.Ref.Key(), want, got) + } + } + } + if calls == 0 { + t.Fatal("lookup never consulted") + } + // the engine composes it when Options.WorkflowFor is set + r := stageengine.New(stageengine.Options{WorkflowFor: lookup, Store: stagelabels.NewStore(t.TempDir()+"/stages.json", nil)}) + if r == nil { + t.Fatal("engine") + } +} diff --git a/src/pkg/stageengine/workflow_rules_test.go b/src/pkg/stageengine/workflow_rules_test.go new file mode 100644 index 0000000000..418a661983 --- /dev/null +++ b/src/pkg/stageengine/workflow_rules_test.go @@ -0,0 +1,211 @@ +package stageengine_test + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +func techdocsProfile(t *testing.T) *workflowmodel.Profile { + t.Helper() + b, err := os.ReadFile("../workflowmodel/testdata/models/techdocs.json") + if err != nil { + t.Fatal(err) + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + p, diags, err := workflowmodel.Compile(&m) + if err != nil { + t.Fatalf("%v %+v", err, diags) + } + return p +} + +func issueFacts(labels ...string) stageengine.Facts { + return stageengine.Facts{ + Ref: stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 1, Kind: stagelabels.IssueItem}, + Open: true, + Labels: labels, + Author: stageengine.AuthorFacts{Kind: authorkind.Human, Login: "nate"}, + Issue: &stageengine.IssueFacts{}, + } +} + +func prFacts(labels ...string) stageengine.Facts { + return stageengine.Facts{ + Ref: stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 2, Kind: stagelabels.PRItem}, + Open: true, + Labels: labels, + Author: stageengine.AuthorFacts{Kind: authorkind.Hive}, + PR: &stageengine.PRFacts{Checks: stagelabels.CheckSummary{Known: true, Total: 2, Green: 2}, DCO: stagelabels.DCOYes}, + } +} + +// TestDeriveFromModelRules walks a TechDocs engagement through the rules +// deriver: ordered first match, kind filtering, glob labels, scalar +// facts, terminal states and the not-covered abstention. +func TestDeriveFromModelRules(t *testing.T) { + p := techdocsProfile(t) + issues := stageengine.DeriveFromModel(p, stagelabels.IssueItem) + prs := stageengine.DeriveFromModel(p, stagelabels.PRItem) + + cases := []struct { + name string + d stageengine.Deriver + f func() stageengine.Facts + stage stagelabels.Stage + term bool + reason string + }{ + {"request filed", issues, func() stageengine.Facts { return issueFacts("techdocs/request") }, stagelabels.Actionable, false, "workflow cncf-techdocs@1: rule requested"}, + {"accepted", issues, func() stageengine.Facts { return issueFacts("techdocs/request", "techdocs/accepted") }, stagelabels.Claimed, false, ""}, + {"analysis posted", issues, func() stageengine.Facts { return issueFacts("techdocs/accepted", "techdocs/analysis") }, stagelabels.IssueNeedsDecision, false, ""}, + {"covered by a draft PR", issues, func() stageengine.Facts { + f := issueFacts("techdocs/analysis") + f.Issue.CoveringPR = &stageengine.Ref{Owner: "cncf", Repo: "techdocs", Number: 2, Kind: stagelabels.PRItem} + return f + }, stagelabels.CoveredByPR, false, ""}, + {"closed unpublished", issues, func() stageengine.Facts { f := issueFacts("techdocs/request"); f.Open = false; return f }, stagelabels.None, true, "closed without publishing"}, + {"draft PR", prs, func() stageengine.Facts { f := prFacts("techdocs/project-x"); f.Draft = true; return f }, stagelabels.Fixing, false, ""}, + {"ready PR awaits review", prs, func() stageengine.Facts { return prFacts("TechDocs/project-x") }, stagelabels.ReviewPending, false, ""}, + {"approved green PR", prs, func() stageengine.Facts { + f := prFacts("techdocs/project-x") + f.PR.Review.State = stagelabels.VerdictApproved + return f + }, stagelabels.ReadyForHumanMerge, false, ""}, + {"approved but red stays in review", prs, func() stageengine.Facts { + f := prFacts("techdocs/project-x") + f.PR.Review.State = stagelabels.VerdictApproved + f.PR.Checks.Red = []string{"lint"} + return f + }, stagelabels.ReviewPending, false, ""}, + {"merged", prs, func() stageengine.Facts { f := prFacts(); f.Open, f.Merged = false, true; return f }, stagelabels.None, true, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := tc.d.Derive(tc.f()) + if got.Abstain { + t.Fatalf("abstained: %s", got.Reason) + } + if got.Terminal != tc.term || got.Stage != tc.stage { + t.Fatalf("got %+v; want stage %s terminal %v", got, tc.stage, tc.term) + } + if tc.reason != "" && got.Reason != tc.reason { + t.Fatalf("reason %q, want %q", got.Reason, tc.reason) + } + if tc.f().Ref.Kind == stagelabels.PRItem && !tc.term && got.DCO != stagelabels.DCOYes { + t.Fatalf("DCO not carried: %+v", got) + } + }) + } + + t.Run("no rule matches", func(t *testing.T) { + got := issues.Derive(issueFacts("bug")) + if !got.Abstain || !strings.HasPrefix(got.Reason, stageengine.ReasonNotCovered) { + t.Fatalf("%+v", got) + } + }) + t.Run("kind mismatch", func(t *testing.T) { + if got := prs.Derive(issueFacts("techdocs/request")); !got.Abstain { + t.Fatalf("%+v", got) + } + }) + t.Run("stage numbers follow the model", func(t *testing.T) { + if got := issues.Derive(issueFacts("techdocs/request")); got.Stage.Number() != 10 { + t.Fatalf("%+v", got) + } + }) + t.Run("issue-side number on a PR state is not covered", func(t *testing.T) { + q := *p + q.Rules = []workflowmodel.Rule{{State: "requested", When: []workflowmodel.Predicate{{Fact: "open", Op: workflowmodel.OpTrue}}}} + got := stageengine.DeriveFromModel(&q, stagelabels.PRItem).Derive(prFacts()) + if !got.Abstain || !strings.Contains(got.Reason, "not a pr stage") { + t.Fatalf("%+v", got) + } + }) +} + +// Every fact in the vocabulary evaluates; none is silently false because +// the evaluator forgot it. +func TestRulesFactVocabularyIsComplete(t *testing.T) { + p := techdocsProfile(t) + f := prFacts("x/y") + f.PR.Review.State = stagelabels.VerdictChangesRequested + f.PR.BaseRef = "main" + f.PR.ChangesRequested, f.PR.Conflicting, f.PR.HeadFresh = true, true, true + f.Draft, f.Merged = true, true + f.Park.Holds = []string{"hold"} + f.Park.NeedsHuman = true + f.Origin = "origin/scanner" + f.Author.Login = "someone" + fi := issueFacts("x/y") + fi.Issue.Bucket = stageengine.BucketClaimed + fi.Issue.Claim = &stageengine.ClaimFact{} + fi.Issue.CoveringPR = &stageengine.Ref{} + fi.Issue.Stalled = true + fi.Issue.OpenChildren = 1 + + for name, ft := range workflowmodel.Facts { + var pos, neg workflowmodel.Op + value := "" + switch ft { + case workflowmodel.FactBool: + pos, neg = workflowmodel.OpTrue, workflowmodel.OpFalse + case workflowmodel.FactScalar: + pos, neg = workflowmodel.OpIs, workflowmodel.OpNot + value = scalarValue(name) + case workflowmodel.FactSet: + pos, neg = workflowmodel.OpHas, workflowmodel.OpLacks + value = "x/*" + } + facts, state := f, "drafting" + if strings.HasPrefix(name, "issue.") { + facts, state = fi, "requested" + } + rp := *p + rp.Rules = []workflowmodel.Rule{{ID: "t", State: state, When: []workflowmodel.Predicate{{Fact: name, Op: pos, Value: value}}}} + rn := *p + rn.Rules = []workflowmodel.Rule{{ID: "t", State: state, When: []workflowmodel.Predicate{{Fact: name, Op: neg, Value: value}}}} + gp := stageengine.DeriveFromModel(&rp, facts.Ref.Kind).Derive(facts) + gn := stageengine.DeriveFromModel(&rn, facts.Ref.Kind).Derive(facts) + if gp.Abstain == gn.Abstain { + t.Errorf("fact %q: %s → %v, %s → %v (one must match)", name, pos, gp.Abstain, neg, gn.Abstain) + } + if gp.Abstain { + t.Errorf("fact %q: positive predicate %s %q did not hold on %+v", name, pos, value, facts) + } + } +} + +func scalarValue(fact string) string { + switch fact { + case "origin": + return "origin/scanner" + case "author.kind": + return "hive" + case "author.login": + return "someone" + case "issue.bucket": + return string(stageengine.BucketClaimed) + case "pr.checks": + return "green" + case "pr.review": + return "changes_requested" + case "pr.dco": + return "yes" + case "pipeline.status": + // Post-merge runs are not observed yet; the engine reports unknown. + return "unknown" + case "pr.base": + return "main" + } + return "?" +} diff --git a/src/pkg/workflowmodel/compile.go b/src/pkg/workflowmodel/compile.go new file mode 100644 index 0000000000..ce30c1ac6f --- /dev/null +++ b/src/pkg/workflowmodel/compile.go @@ -0,0 +1,469 @@ +package workflowmodel + +import ( + "errors" + "fmt" + "sort" + "strings" +) + +// Diagnostic is one compiler finding. Errors refuse the model; warnings +// are shown in the editor and on the monitor but compile. +type Diagnostic struct { + Code string `json:"code"` + Severity string `json:"severity"` + Subject string `json:"subject,omitempty"` + Detail string `json:"detail"` +} + +// Diagnostic severities. +const ( + DiagError = "error" + DiagWarning = "warning" +) + +// Diagnostic codes. Each is one of the refusals in hivecommons/hive#17620 +// "Deterministic", or a structural check the engine needs. +const ( + CodeNoExit = "state-no-exit" + CodeGateNoOwner = "gate-no-owner" + CodeAgentNoHumanGate = "agent-no-human-gate" + CodeDuplicateEvent = "duplicate-event-fact" + CodeNoColumn = "state-no-column" + CodeUnknownColumn = "unknown-column" + CodeUnknownState = "unknown-state" + CodeColumnEmpty = "column-empty" + CodeNoTerminalColumn = "no-terminal-column" + CodeDuplicateNumber = "duplicate-stage-number" + CodeUnknownFact = "unknown-fact" + CodeBadOp = "bad-op" + CodeNoRules = "no-rules" + CodeBadMode = "bad-derivation-mode" + CodeUnknownRole = "unknown-role" + CodeUnknownGate = "unknown-gate" + CodeUnknownEvent = "unknown-event" + CodeNoVersion = "no-version" + CodeInferred = "inferred-element" +) + +// ErrCompile wraps a compile refused by error diagnostics. +var ErrCompile = errors.New("workflow model does not compile") + +// Profile is a compiled model: what the engine and the monitor consume. +// It is derived, never edited; recompile from the Model instead. +type Profile struct { + Name string `json:"name"` + Version string `json:"version"` + Hash string `json:"hash"` + // Mode is the derivation mode. + Mode DerivationMode `json:"mode"` + // Columns in display order with their states resolved. + Columns []Column `json:"columns"` + // States by id, flattened (regions included). + States map[string]*State `json:"-"` + // ColumnOf maps a state id to its column id. + ColumnOf map[string]string `json:"columnOf"` + // StateOfNumber maps a stage number to the state id that carries it. + StateOfNumber map[int]string `json:"stateOfNumber"` + // Terminal is the set of states in a terminal column or of final type. + Terminal map[string]bool `json:"terminal"` + // Rules are the derivation rules, in evaluation order (rules mode). + Rules []Rule `json:"rules,omitempty"` + // Replies maps a state id to the human-gate verbs it offers. + Replies map[string][]string `json:"replies,omitempty"` + // Labels is the label set to reconcile. + Labels LabelSet `json:"labels,omitzero"` + // Diagnostics are the warnings left after a successful compile. + Diagnostics []Diagnostic `json:"diagnostics,omitempty"` +} + +// Compile validates m, then checks the lifecycle half and builds the +// Profile. Error diagnostics refuse the compile: the returned Profile is +// nil and err wraps ErrCompile; diagnostics are always returned so an +// editor can show them all at once. +func Compile(m *Model) (*Profile, []Diagnostic, error) { + if err := m.Validate(); err != nil { + return nil, []Diagnostic{{Code: "invalid", Severity: DiagError, Detail: err.Error()}}, err + } + c := &compiler{m: m} + c.run() + sort.SliceStable(c.diags, func(i, j int) bool { + if c.diags[i].Severity != c.diags[j].Severity { + return c.diags[i].Severity == DiagError + } + return false + }) + for _, d := range c.diags { + if d.Severity == DiagError { + return nil, c.diags, fmt.Errorf("%w: %s", ErrCompile, summarize(c.diags)) + } + } + c.p.Diagnostics = c.diags + return c.p, c.diags, nil +} + +func summarize(diags []Diagnostic) string { + var parts []string + for _, d := range diags { + if d.Severity != DiagError { + continue + } + if d.Subject != "" { + parts = append(parts, d.Code+" "+d.Subject) + } else { + parts = append(parts, d.Code) + } + } + return strings.Join(parts, "; ") +} + +type compiler struct { + m *Model + p *Profile + diags []Diagnostic +} + +func (c *compiler) errorf(code, subject, format string, a ...any) { + c.diags = append(c.diags, Diagnostic{Code: code, Severity: DiagError, Subject: subject, Detail: fmt.Sprintf(format, a...)}) +} + +func (c *compiler) warnf(code, subject, format string, a ...any) { + c.diags = append(c.diags, Diagnostic{Code: code, Severity: DiagWarning, Subject: subject, Detail: fmt.Sprintf(format, a...)}) +} + +func (c *compiler) run() { + m := c.m + c.p = &Profile{Name: m.Metadata.Name, Version: m.Spec.Meta.Version, Hash: m.Hash(), Mode: m.Spec.Derivation.Mode, States: map[string]*State{}, ColumnOf: map[string]string{}, StateOfNumber: map[int]string{}, Terminal: map[string]bool{}, Replies: map[string][]string{}, Labels: m.Spec.Labels} + if c.p.Version == "" { + c.errorf(CodeNoVersion, "", "spec.meta.version is empty") + } + var flatten func(states []State) + flatten = func(states []State) { + for i := range states { + s := &states[i] + c.p.States[s.ID] = s + flatten(s.Regions) + } + } + flatten(m.Spec.States) + + c.columns() + c.numbers() + c.exits() + c.roles() + c.events() + c.derivation() + c.inferred() +} + +// columns checks every top-level state sits in exactly one column and +// every column names real states; a terminal column must exist. +func (c *compiler) columns() { + m := c.m + cols := map[string]bool{} + terminal := false + for _, col := range m.Spec.Columns { + cols[col.ID] = true + if col.Terminal { + terminal = true + } + if len(col.States) == 0 { + c.errorf(CodeColumnEmpty, col.ID, "column %q collects no state", col.ID) + } + for _, sid := range col.States { + s, ok := c.p.States[sid] + if !ok { + c.errorf(CodeUnknownState, col.ID, "column %q collects unknown state %q", col.ID, sid) + continue + } + if prev, dup := c.p.ColumnOf[sid]; dup && prev != col.ID { + c.errorf(CodeUnknownColumn, sid, "state %q is in columns %q and %q", sid, prev, col.ID) + } + c.p.ColumnOf[sid] = col.ID + if col.Terminal || s.Type == StateFinal { + c.p.Terminal[sid] = true + } + } + } + for _, s := range m.Spec.States { + if s.Lifecycle.Column != "" && !cols[s.Lifecycle.Column] { + c.errorf(CodeUnknownColumn, s.ID, "state %q names column %q, which does not exist", s.ID, s.Lifecycle.Column) + } + if s.Lifecycle.Column != "" && c.p.ColumnOf[s.ID] != "" && c.p.ColumnOf[s.ID] != s.Lifecycle.Column { + c.errorf(CodeUnknownColumn, s.ID, "state %q says column %q but column %q collects it", s.ID, s.Lifecycle.Column, c.p.ColumnOf[s.ID]) + } + if _, ok := c.p.ColumnOf[s.ID]; !ok { + if s.Lifecycle.Column != "" && cols[s.Lifecycle.Column] { + c.p.ColumnOf[s.ID] = s.Lifecycle.Column + continue + } + c.errorf(CodeNoColumn, s.ID, "state %q is not in any column", s.ID) + } + if s.Type == StateFinal { + c.p.Terminal[s.ID] = true + } + } + if len(m.Spec.Columns) > 0 && !terminal { + c.errorf(CodeNoTerminalColumn, "", "no column is terminal") + } + c.p.Columns = append([]Column(nil), m.Spec.Columns...) +} + +// numbers checks stage numbers are unique per item kind. +func (c *compiler) numbers() { + seen := map[string]string{} + for _, s := range c.m.Spec.States { + n := s.Lifecycle.Number + if n == 0 { + continue + } + kinds := s.Lifecycle.Kinds + if len(kinds) == 0 { + kinds = []ItemKind{KindIssue, KindPR} + } + for _, k := range kinds { + key := fmt.Sprintf("%s/%d", k, n) + if prev, dup := seen[key]; dup { + c.errorf(CodeDuplicateNumber, s.ID, "states %q and %q both carry stage number %d for %s", prev, s.ID, n, k) + } + seen[key] = s.ID + } + if _, ok := c.p.StateOfNumber[n]; !ok { + c.p.StateOfNumber[n] = s.ID + } + if len(s.Lifecycle.Replies) > 0 { + c.p.Replies[s.ID] = append([]string(nil), s.Lifecycle.Replies...) + } + } +} + +// exits checks every non-terminal state has a way out. +func (c *compiler) exits() { + out := map[string]bool{} + for _, t := range c.m.Spec.Transitions { + out[t.From] = true + } + for _, s := range c.m.Spec.States { + if c.p.Terminal[s.ID] || out[s.ID] || s.Type == StateParallel { + continue + } + c.errorf(CodeNoExit, s.ID, "state %q is not terminal and has no transition out", s.ID) + } +} + +// roles checks gates name a releasing role and that an agent-granted +// state is followed by a human-released gate on every path out. +func (c *compiler) roles() { + m := c.m + roles := map[string]RoleDef{} + for _, r := range m.Spec.Roles { + roles[r.ID] = r + } + gates := map[string]Gate{} + for _, g := range m.Spec.Gates { + gates[g.ID] = g + if g.ReleasedBy == "" { + c.errorf(CodeGateNoOwner, g.ID, "gate %q has no releasing role", g.ID) + continue + } + if _, ok := roles[g.ReleasedBy]; !ok { + c.errorf(CodeUnknownRole, g.ID, "gate %q is released by unknown role %q", g.ID, g.ReleasedBy) + } + } + for _, t := range m.Spec.Transitions { + if t.GateRef != "" { + if _, ok := gates[t.GateRef]; !ok { + c.errorf(CodeUnknownGate, t.From+"->"+t.To, "transition %s->%s needs unknown gate %q", t.From, t.To, t.GateRef) + } + } + } + for _, e := range m.Spec.Events { + if e.Actor != "" { + if _, ok := roles[e.Actor]; !ok { + c.errorf(CodeUnknownRole, e.ID, "event %q actor %q is not a role", e.ID, e.Actor) + } + } + } + if len(m.Spec.Agents) == 0 { + return + } + humanGate := func(t Transition) bool { + g, ok := gates[t.GateRef] + return ok && roles[g.ReleasedBy].Human + } + // A closure edge (item closed unmerged) is an observation, not an + // outcome an agent can bring about, so it is not a path to inspect. + events := map[string]Event{} + for _, e := range m.Spec.Events { + events[e.ID] = e + } + closure := func(t Transition) bool { + e, ok := events[t.On] + return ok && c.p.Terminal[t.To] && e.Fact.Fact == "open" && e.Fact.Op == OpFalse + } + // adjacency over transitions + next := map[string][]Transition{} + for _, t := range m.Spec.Transitions { + next[t.From] = append(next[t.From], t) + } + for _, a := range m.Spec.Agents { + for _, sid := range a.States { + if _, ok := c.p.States[sid]; !ok { + c.errorf(CodeUnknownState, a.Profile, "agent %q acts in unknown state %q", a.Profile, sid) + continue + } + if !c.humanGateReachable(sid, next, humanGate, closure) { + c.errorf(CodeAgentNoHumanGate, sid, "agent %q acts in %q but no human-released gate follows it before a terminal state", a.Profile, sid) + } + } + } +} + +// humanGateReachable is true when every path from start to a terminal +// state crosses a human-released gate (a path with no such gate is a +// refusal). Cycles without a gate do not count as a path; closure edges +// are skipped. +func (c *compiler) humanGateReachable(start string, next map[string][]Transition, human, skip func(Transition) bool) bool { + var visit func(state string, seen map[string]bool) bool + visit = func(state string, seen map[string]bool) bool { + if c.p.Terminal[state] { + return false // reached terminal without a gate + } + if seen[state] { + return true // cycle: no gate-free path to terminal through here + } + seen[state] = true + defer delete(seen, state) + for _, t := range next[state] { + if human(t) || skip(t) { + continue + } + if !visit(t.To, seen) { + return false + } + } + return true + } + return visit(start, map[string]bool{}) +} + +// events checks no two events bind the same predicate and transitions +// name declared events. +func (c *compiler) events() { + m := c.m + ids := map[string]bool{} + byFact := map[string]string{} + for _, e := range m.Spec.Events { + ids[e.ID] = true + c.predicate(e.ID, e.Fact) + k := e.Fact.Fact + "|" + string(e.Fact.Op) + "|" + e.Fact.Value + if prev, dup := byFact[k]; dup { + c.errorf(CodeDuplicateEvent, e.ID, "events %q and %q both fire on %s %s %s", prev, e.ID, e.Fact.Fact, e.Fact.Op, e.Fact.Value) + } + byFact[k] = e.ID + } + if len(m.Spec.Events) == 0 { + return + } + for _, t := range m.Spec.Transitions { + if t.On != "" && !ids[t.On] { + c.errorf(CodeUnknownEvent, t.From+"->"+t.To, "transition %s->%s fires on undeclared event %q", t.From, t.To, t.On) + } + } + for _, b := range m.Spec.Bookkeeping { + if !ids[b.On] { + c.errorf(CodeUnknownEvent, b.Action, "bookkeeping %q fires on undeclared event %q", b.Action, b.On) + } + } +} + +// predicate checks a predicate against the fact vocabulary. +func (c *compiler) predicate(subject string, p Predicate) { + ft, ok := Facts[p.Fact] + if !ok { + c.errorf(CodeUnknownFact, subject, "fact %q is not in the vocabulary", p.Fact) + return + } + valid := map[FactType][]Op{ + FactBool: {OpTrue, OpFalse}, + FactScalar: {OpIs, OpNot}, + FactSet: {OpHas, OpLacks}, + }[ft] + for _, op := range valid { + if op == p.Op { + if ft != FactBool && p.Value == "" { + c.errorf(CodeBadOp, subject, "fact %q %s needs a value", p.Fact, p.Op) + } + return + } + } + c.errorf(CodeBadOp, subject, "fact %q is %s; operator %q does not apply", p.Fact, ft, p.Op) +} + +// derivation checks the mode and compiles the rules. +func (c *compiler) derivation() { + d := c.m.Spec.Derivation + switch d.Mode { + case DerivationBuiltin: + if len(d.Rules) > 0 { + c.warnf(CodeBadMode, "", "derivation is builtin; %d rules are ignored", len(d.Rules)) + } + case DerivationRules: + if len(d.Rules) == 0 { + c.errorf(CodeNoRules, "", "derivation is rules but spec.derivation.rules is empty") + } + for i, r := range d.Rules { + subject := r.ID + if subject == "" { + subject = fmt.Sprintf("rules[%d]", i) + } + if _, ok := c.p.States[r.State]; !ok { + c.errorf(CodeUnknownState, subject, "rule %s puts items in unknown state %q", subject, r.State) + } + if len(r.When) == 0 { + c.warnf(CodeNoRules, subject, "rule %s has no predicates and matches everything after it is reached", subject) + } + for _, p := range r.When { + c.predicate(subject, p) + } + } + c.p.Rules = append([]Rule(nil), d.Rules...) + default: + c.errorf(CodeBadMode, "", "spec.derivation.mode %q is not builtin or rules", d.Mode) + } +} + +// inferred warns about every element a human has not confirmed. +func (c *compiler) inferred() { + for _, s := range c.m.Spec.States { + if s.Lifecycle.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, s.ID, "state %q is inferred and unconfirmed", s.ID) + } + } + for _, e := range c.m.Spec.Events { + if e.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, e.ID, "event %q is inferred and unconfirmed", e.ID) + } + } + for _, g := range c.m.Spec.Gates { + if g.Confidence == ConfidenceInferred { + c.warnf(CodeInferred, g.ID, "gate %q is inferred and unconfirmed", g.ID) + } + } +} + +// StateForNumber returns the state carrying stage number n, if any. +func (p *Profile) StateForNumber(n int) (string, bool) { + s, ok := p.StateOfNumber[n] + return s, ok +} + +// Column returns the column with id, or nil. +func (p *Profile) Column(id string) *Column { + for i := range p.Columns { + if p.Columns[i].ID == id { + return &p.Columns[i] + } + } + return nil +} diff --git a/src/pkg/workflowmodel/compile_test.go b/src/pkg/workflowmodel/compile_test.go new file mode 100644 index 0000000000..38ee918c6c --- /dev/null +++ b/src/pkg/workflowmodel/compile_test.go @@ -0,0 +1,175 @@ +package workflowmodel + +import ( + "encoding/json" + "os" + "strings" + "testing" +) + +func loadModel(t *testing.T, path string) *Model { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var m Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return &m +} + +func techdocs(t *testing.T) *Model { return loadModel(t, "testdata/models/techdocs.json") } + +func TestCompileTechDocs(t *testing.T) { + p, diags, err := Compile(techdocs(t)) + if err != nil { + t.Fatalf("%v\n%+v", err, diags) + } + if p.Mode != DerivationRules || len(p.Rules) != 9 { + t.Fatalf("mode %s rules %d", p.Mode, len(p.Rules)) + } + if p.ColumnOf["draft-review"] != "writing" || !p.Terminal["published"] || p.Terminal["approved"] { + t.Fatalf("columns %v terminal %v", p.ColumnOf, p.Terminal) + } + if id, ok := p.StateForNumber(45); !ok || id != "analysis-review" { + t.Fatalf("StateForNumber(45) = %q %v", id, ok) + } + if got := p.Replies["draft-review"]; len(got) != 2 { + t.Fatalf("replies %v", got) + } + if p.Hash == "" || p.Version != "1" { + t.Fatalf("hash %q version %q", p.Hash, p.Version) + } + for _, d := range diags { + if d.Severity == DiagError { + t.Errorf("unexpected error diagnostic %+v", d) + } + } +} + +// Each refusal from the RFC's "Deterministic" list, and the structural +// checks around them, produces its code and no Profile. +func TestCompileRefusals(t *testing.T) { + cases := []struct { + name string + mut func(m *Model) + code string + }{ + {"no version", func(m *Model) { m.Spec.Meta.Version = "" }, CodeNoVersion}, + {"state without exit", func(m *Model) { + var tr []Transition + for _, x := range m.Spec.Transitions { + if x.From != "approved" { + tr = append(tr, x) + } + } + m.Spec.Transitions = tr + }, CodeNoExit}, + {"gate without owner", func(m *Model) { m.Spec.Gates[0].ReleasedBy = "" }, CodeGateNoOwner}, + {"gate with unknown role", func(m *Model) { m.Spec.Gates[0].ReleasedBy = "nobody" }, CodeUnknownRole}, + {"agent with no human gate after it", func(m *Model) { + for i := range m.Spec.Roles { + m.Spec.Roles[i].Human = false + } + }, CodeAgentNoHumanGate}, + {"agent in unknown state", func(m *Model) { m.Spec.Agents[0].States = []string{"ghost"} }, CodeUnknownState}, + {"two events on one fact", func(m *Model) { m.Spec.Events[1].Fact = m.Spec.Events[0].Fact }, CodeDuplicateEvent}, + {"state in no column", func(m *Model) { m.Spec.Columns[0].States = []string{"analysing"} }, CodeNoColumn}, + {"state in two columns", func(m *Model) { m.Spec.Columns[0].States = []string{"requested", "analysing"} }, CodeUnknownColumn}, + {"state names a column that does not collect it", func(m *Model) { m.Spec.States[0].Lifecycle.Column = "done" }, CodeUnknownColumn}, + {"column collects unknown state", func(m *Model) { m.Spec.Columns[0].States = append(m.Spec.Columns[0].States, "ghost") }, CodeUnknownState}, + {"empty column", func(m *Model) { m.Spec.Columns = append(m.Spec.Columns, Column{ID: "x", Label: "x"}) }, CodeColumnEmpty}, + {"no terminal column", func(m *Model) { m.Spec.Columns[4].Terminal = false }, CodeNoTerminalColumn}, + {"duplicate stage number", func(m *Model) { m.Spec.States[1].Lifecycle.Number = 10 }, CodeDuplicateNumber}, + {"unknown fact", func(m *Model) { m.Spec.Derivation.Rules[0].When[0].Fact = "weather" }, CodeUnknownFact}, + {"bad operator", func(m *Model) { m.Spec.Derivation.Rules[0].When[0].Op = OpHas }, CodeBadOp}, + {"scalar op without value", func(m *Model) { m.Spec.Derivation.Rules[2].When[0].Value = "" }, CodeBadOp}, + {"rules mode with no rules", func(m *Model) { m.Spec.Derivation.Rules = nil }, CodeNoRules}, + {"rule names unknown state", func(m *Model) { m.Spec.Derivation.Rules[0].State = "ghost" }, CodeUnknownState}, + {"bad derivation mode", func(m *Model) { m.Spec.Derivation.Mode = "oracle" }, CodeBadMode}, + {"transition on undeclared event", func(m *Model) { m.Spec.Transitions[0].On = "thunder" }, CodeUnknownEvent}, + {"transition needs unknown gate", func(m *Model) { m.Spec.Transitions[0].GateRef = "ghost" }, CodeUnknownGate}, + {"event actor is not a role", func(m *Model) { m.Spec.Events[0].Actor = "ghost" }, CodeUnknownRole}, + {"bookkeeping on undeclared event", func(m *Model) { + m.Spec.Bookkeeping = []Effect{{On: "thunder", Action: "comment"}} + }, CodeUnknownEvent}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := techdocs(t) + tc.mut(m) + p, diags, err := Compile(m) + if err == nil || p != nil { + t.Fatalf("compiled; diags %+v", diags) + } + if !strings.Contains(err.Error(), ErrCompile.Error()) { + t.Fatalf("err %v does not wrap ErrCompile", err) + } + found := false + for _, d := range diags { + if d.Code == tc.code && d.Severity == DiagError { + found = true + } + } + if !found { + t.Fatalf("want %s in %+v", tc.code, diags) + } + }) + } +} + +func TestCompileWarnings(t *testing.T) { + m := techdocs(t) + m.Spec.Gates[0].Confidence = ConfidenceInferred + m.Spec.Events[0].Confidence = ConfidenceInferred + p, diags, err := Compile(m) + if err != nil { + t.Fatal(err) + } + n := 0 + for _, d := range diags { + if d.Code == CodeInferred && d.Severity == DiagWarning { + n++ + } + } + if n != 2 || len(p.Diagnostics) != len(diags) { + t.Fatalf("inferred warnings %d; profile carries %d of %d", n, len(p.Diagnostics), len(diags)) + } + + m = techdocs(t) + m.Spec.Derivation.Mode = DerivationBuiltin + if _, diags, err = Compile(m); err != nil { + t.Fatal(err) + } + if len(diags) != 1 || diags[0].Code != CodeBadMode || diags[0].Severity != DiagWarning { + t.Fatalf("builtin with rules: %+v", diags) + } +} + +func TestCompileInvalidModel(t *testing.T) { + m := techdocs(t) + m.Spec.Initial = "ghost" + p, diags, err := Compile(m) + if err == nil || p != nil || len(diags) != 1 || diags[0].Code != "invalid" { + t.Fatalf("%v %+v", err, diags) + } +} + +// A closure edge out of an agent state is an observation, not a way for +// the agent to reach an outcome unsupervised; a merge edge is. +func TestCompileClosureEdgesAreNotAgentPaths(t *testing.T) { + m := techdocs(t) + if _, _, err := Compile(m); err != nil { + t.Fatal(err) + } + m.Spec.Transitions = append(m.Spec.Transitions, Transition{From: "drafting", To: "published", On: "merged"}) + _, diags, err := Compile(m) + if err == nil { + t.Fatal("agent merging its own draft must be refused") + } + if !strings.Contains(err.Error(), CodeAgentNoHumanGate+" drafting") { + t.Fatalf("%v %+v", err, diags) + } +} diff --git a/src/pkg/workflowmodel/hivedefault/hivedefault.go b/src/pkg/workflowmodel/hivedefault/hivedefault.go new file mode 100644 index 0000000000..80f488b950 --- /dev/null +++ b/src/pkg/workflowmodel/hivedefault/hivedefault.go @@ -0,0 +1,254 @@ +// Package hivedefault generates the `hive-default` workflow model: Hive's +// own lifecycle expressed in the workflow-model schema +// (hivecommons/hive#17620). Nothing here is hand-maintained: states come +// from stagelabels.Table, transitions from stageengine.DiagramEdges and +// the columns from the Activity Monitor's layout constants, so the model +// is the schema's conformance test — if it cannot express Hive's graph, +// the schema is not done. +// +// The model declares derivation mode builtin: an item's state is still +// decided by the Go derivers, and DeriveFromModel only checks that what +// they produce is a state the model knows. That is what keeps the stage +// goldens byte-for-byte and the v5/v6 monitor pixel-identical for +// repositories that bind nothing. +package hivedefault + +import ( + "fmt" + "sort" + "strings" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +// Name is the model's metadata.name; Version its spec.meta.version. The +// version is bumped by hand when the generator's output changes shape. +const ( + Name = "hive-default" + Version = "1" +) + +// Column ids. These are the Activity Monitor's columns in order; the +// anchor numbers mirror STAGE_TRACKER_PATH = [0, 10, 20, 30, 50, 80] plus +// the terminal Merged cap (agent-now.js, tracker-motion.js). +const ( + ColumnOpen = "open" + ColumnActionable = "actionable" + ColumnClaimed = "claimed" + ColumnPRInProgress = "pr-in-progress" + ColumnCIReview = "ci-review" + ColumnMergeQueue = "merge-queue" + ColumnMerged = "merged" +) + +// Terminal state ids (no stage label; observed, not written). +const ( + StateOpen = "open" + StateMerged = "merged" + StateClosed = "closed" +) + +// Role ids. +const ( + RoleMaintainer = "maintainer" + RoleAuthor = "author" + RoleReviewSwarm = "review-swarm" + RoleHiveAgent = "hive-agent" + RoleCI = "ci" +) + +// Gate and event ids. +const ( + GateMaintainerDecision = "maintainer-decision" + GateMaintainerApprove = "maintainer-approve" + GateAuthorPush = "author-push" + EventOpened = "opened" + EventMerged = "merged" + EventClosed = "closed" + EventStageChange = "stage-change" +) + +// columnAnchors maps a stage number to the column that lights for it, +// mirroring stageTrackerColumn / tracker-row-anchor.js. Every Table +// number must be here; Generate panics otherwise. +var columnAnchors = map[int]string{ + 10: ColumnActionable, 15: ColumnActionable, 17: ColumnActionable, 18: ColumnActionable, 45: ColumnActionable, + 20: ColumnClaimed, + 30: ColumnPRInProgress, 40: ColumnPRInProgress, + 50: ColumnCIReview, 60: ColumnCIReview, 70: ColumnCIReview, 71: ColumnCIReview, 72: ColumnCIReview, 74: ColumnCIReview, + 80: ColumnMergeQueue, 85: ColumnMergeQueue, 90: ColumnMergeQueue, 95: ColumnMergeQueue, 100: ColumnMergeQueue, +} + +// replies are the human-gate verbs the monitor offers in a stage today +// (tracker-actions.js); declared here so a model can carry its own. +var replies = map[int][]string{ + 15: {"accept-triage", "decide:close-issue"}, + 17: {"decide:approve", "decide:close-superseded"}, + 45: {"decide:delegate", "decide:approve", "decide:direction", "decide:close-superseded", "decide:close-wontfix", "hold"}, + 85: {"decide:delegate", "decide:approve", "decide:direction", "decide:merge-now", "decide:queue-merge", "decide:adopt", "decide:close-superseded", "hold"}, + 90: {"decide:approve", "decide:merge-now"}, +} + +// owner says who moves work out of a stage. +func owner(d stagelabels.Definition) workflowmodel.Owner { + switch d.Stage { + case stagelabels.TriageNeeded, stagelabels.PossiblyExisting, stagelabels.OpenForDiscussion, stagelabels.IssueNeedsDecision, + stagelabels.NeedsDecision, stagelabels.ReadyForHumanMerge, stagelabels.NeedsAuthor, stagelabels.ReturnedToContributor: + return workflowmodel.OwnerHuman + case stagelabels.ReviewPending, stagelabels.Reviewed, stagelabels.AwaitingMergeAdmission, stagelabels.PreMergeSoak, stagelabels.MergeQueue: + return workflowmodel.OwnerExternalService + case stagelabels.CoveredByPR: + return workflowmodel.OwnerExternalObservation + } + return workflowmodel.OwnerRegisteredAgent +} + +// StateID is the model state id for a stage: its slug, suffixed with the +// item kind where two stages share a slug (045 and 085 needs-decision). +func StateID(s stagelabels.Stage) string { + switch s { + case stagelabels.None: + return "" + case stagelabels.IssueNeedsDecision: + return "needs-decision-issue" + case stagelabels.NeedsDecision: + return "needs-decision-pr" + } + return s.Slug() +} + +// Generate builds the hive-default model from the live stage table. +func Generate() *workflowmodel.Model { + m := workflowmodel.New(Name, workflowmodel.Scope{Forge: "github.com", Repository: "*"}) + m.Spec.Meta = workflowmodel.Meta{Version: Version, Author: "hivecommons", Description: "Hive's built-in issue and pull-request lifecycle, generated from the stage table", License: "Apache-2.0", Source: workflowmodel.SourceBuiltIn, Provenance: workflowmodel.ProvenanceBuiltIn} + m.Spec.Initial = StateOpen + m.Spec.Derivation = workflowmodel.Derivation{Mode: workflowmodel.DerivationBuiltin} + m.Spec.Labels.Prefix = stagelabels.Prefix + + order := []workflowmodel.Column{ + {ID: ColumnOpen, Label: "Open", Hint: "Filed; not yet staged", States: []string{StateOpen}}, + {ID: ColumnActionable, Label: "Actionable", Hint: "Triaged or parked on a person"}, + {ID: ColumnClaimed, Label: "Claimed", Hint: "An agent or contributor holds it"}, + {ID: ColumnPRInProgress, Label: "PR in progress", Hint: "A PR is under way or open"}, + {ID: ColumnCIReview, Label: "CI / Review", Hint: "Verdict and checks on the current head"}, + {ID: ColumnMergeQueue, Label: "Merge queue", Hint: "Admitted; waiting on soak, tide or a human merge"}, + {ID: ColumnMerged, Label: "Merged", Hint: "Done", Terminal: true, States: []string{StateMerged, StateClosed}}, + } + cols := map[string]*workflowmodel.Column{} + for i := range order { + cols[order[i].ID] = &order[i] + } + + m.Spec.States = append(m.Spec.States, workflowmodel.State{ID: StateOpen, Label: "Open", Owner: workflowmodel.OwnerExternalObservation, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnOpen}}) + + table := append([]stagelabels.Definition(nil), stagelabels.Table...) + sort.SliceStable(table, func(i, j int) bool { return table[i].Number < table[j].Number }) + for _, d := range table { + id := StateID(d.Stage) + col, ok := columnAnchors[d.Number] + if !ok { + panic(fmt.Sprintf("hivedefault: stage %d has no column anchor", d.Number)) + } + var kinds []workflowmodel.ItemKind + if d.Issue { + kinds = append(kinds, workflowmodel.KindIssue) + } + if d.PR { + kinds = append(kinds, workflowmodel.KindPR) + } + st := workflowmodel.State{ID: id, Label: label(d), Owner: owner(d), Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: col, Number: d.Number, Kinds: kinds, Replies: replies[d.Number]}} + if d.Dwell > 0 { + st.Lifecycle.Waiting = []string{"stalled after " + d.Dwell.String()} + } + m.Spec.States = append(m.Spec.States, st) + cols[col].States = append(cols[col].States, id) + m.Spec.Labels.Entries = append(m.Spec.Labels.Entries, workflowmodel.LabelEntry{Name: d.Stage.Label(), Description: d.Description, State: id}) + } + m.Spec.States = append(m.Spec.States, + workflowmodel.State{ID: StateMerged, Label: "Merged", Owner: workflowmodel.OwnerExternalObservation, Type: workflowmodel.StateFinal, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnMerged, Kinds: []workflowmodel.ItemKind{workflowmodel.KindPR}}}, + workflowmodel.State{ID: StateClosed, Label: "Closed", Owner: workflowmodel.OwnerExternalObservation, Type: workflowmodel.StateFinal, Origin: workflowmodel.OriginHiveDefault, Lifecycle: workflowmodel.StateLifecycle{Column: ColumnMerged}}, + ) + m.Spec.Columns = order + + m.Spec.Roles = []workflowmodel.RoleDef{ + {ID: RoleMaintainer, Label: "Maintainer", Kind: workflowmodel.RolePermission, Params: map[string]string{"permission": "write"}, Human: true}, + {ID: RoleAuthor, Label: "Author", Kind: workflowmodel.RoleAuthorKind, Params: map[string]string{"kind": "human"}, Human: true}, + {ID: RoleReviewSwarm, Label: "Review swarm", Kind: workflowmodel.RoleBot, Params: map[string]string{"login": "hive"}}, + {ID: RoleHiveAgent, Label: "Hive agent", Kind: workflowmodel.RoleBot, Params: map[string]string{"login": "hive"}}, + {ID: RoleCI, Label: "CI", Kind: workflowmodel.RoleBot}, + } + m.Spec.Gates = []workflowmodel.Gate{ + {ID: GateMaintainerDecision, ReleasedBy: RoleMaintainer, Reply: "/hive decision"}, + {ID: GateMaintainerApprove, ReleasedBy: RoleMaintainer, Reply: "/lgtm /approve", Conditions: []workflowmodel.Predicate{{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "green"}}}, + {ID: GateAuthorPush, ReleasedBy: RoleAuthor}, + } + m.Spec.Events = []workflowmodel.Event{ + {ID: EventOpened, Label: "Item opened", Fact: workflowmodel.Predicate{Fact: "open", Op: workflowmodel.OpTrue}}, + {ID: EventMerged, Label: "PR merged", Fact: workflowmodel.Predicate{Fact: "merged", Op: workflowmodel.OpTrue}}, + {ID: EventClosed, Label: "Item closed unmerged", Fact: workflowmodel.Predicate{Fact: "open", Op: workflowmodel.OpFalse}}, + {ID: "claimed", Label: "Claim taken", Fact: workflowmodel.Predicate{Fact: "issue.claimed", Op: workflowmodel.OpTrue}}, + {ID: "covered", Label: "PR covers the issue", Fact: workflowmodel.Predicate{Fact: "issue.covered", Op: workflowmodel.OpTrue}}, + {ID: "checks-green", Label: "Checks green", Fact: workflowmodel.Predicate{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "green"}}, + {ID: "checks-red", Label: "Checks red", Fact: workflowmodel.Predicate{Fact: "pr.checks", Op: workflowmodel.OpIs, Value: "red"}}, + {ID: "review-approved", Label: "Verdict approve", Fact: workflowmodel.Predicate{Fact: "pr.review", Op: workflowmodel.OpIs, Value: "approved"}}, + {ID: "changes-requested", Label: "Changes requested", Fact: workflowmodel.Predicate{Fact: "pr.changes_requested", Op: workflowmodel.OpTrue}}, + {ID: "held", Label: "Hold label applied", Fact: workflowmodel.Predicate{Fact: "hold", Op: workflowmodel.OpTrue}}, + {ID: "parked", Label: "Park label applied", Fact: workflowmodel.Predicate{Fact: "park", Op: workflowmodel.OpTrue}}, + {ID: EventStageChange, Label: "Stage re-derived", Fact: workflowmodel.Predicate{Fact: "labels", Op: workflowmodel.OpHas, Value: stagelabels.Prefix + "*"}}, + } + m.Spec.Agents = []workflowmodel.AgentGrant{ + {Profile: "scanner", States: []string{StateID(stagelabels.Actionable), StateID(stagelabels.TriageNeeded), StateID(stagelabels.OpenForDiscussion)}, Produces: []string{"claim"}}, + {Profile: "worker", States: []string{StateID(stagelabels.Claimed), StateID(stagelabels.PRInProgress), StateID(stagelabels.Fixing), StateID(stagelabels.AdoptedByHive)}, Produces: []string{"pull-request", "push"}}, + {Profile: "review-swarm", States: []string{StateID(stagelabels.ReviewPending)}, Produces: []string{"review"}}, + } + + // Transitions from the expected-edge table; gates on the edges a human + // releases. + for _, e := range stageengine.DiagramEdges() { + t := workflowmodel.Transition{From: StateID(e.From), To: StateID(e.To), On: EventStageChange, Note: fmt.Sprintf("%s → %s", e.From, e.To)} + switch { + case e.From == stagelabels.IssueNeedsDecision || e.From == stagelabels.NeedsDecision || e.From == stagelabels.PossiblyExisting: + t.GateRef = GateMaintainerDecision + case e.From == stagelabels.ReadyForHumanMerge && e.To == stagelabels.MergeQueue: + t.GateRef = GateMaintainerApprove + case e.From == stagelabels.NeedsAuthor || e.From == stagelabels.ReturnedToContributor: + t.GateRef = GateAuthorPush + } + m.Spec.Transitions = append(m.Spec.Transitions, t) + } + // Intake and terminal edges, which the diagram draws as [*]. + m.Spec.Transitions = append(m.Spec.Transitions, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.Actionable), On: EventOpened, Note: "triaged intake"}, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.TriageNeeded), On: EventOpened, Note: "reporter-trust gate"}, + workflowmodel.Transition{From: StateOpen, To: StateID(stagelabels.ReviewPending), On: EventOpened, Note: "PR opened"}, + ) + for _, d := range table { + switch d.Stage { + case stagelabels.MergeQueue: + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateMerged, On: EventMerged, GateRef: GateMaintainerApprove, Note: "tide / lane merges"}) + case stagelabels.ReadyForHumanMerge: + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateMerged, On: EventMerged, GateRef: GateMaintainerApprove, Note: "maintainer merges"}) + } + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: StateID(d.Stage), To: StateClosed, On: EventClosed}) + } + return m +} + +// label is the display label for a stage: its slug, humanised. +func label(d stagelabels.Definition) string { + s := strings.ReplaceAll(d.Slug, "-", " ") + return strings.ToUpper(s[:1]) + s[1:] +} + +// Profile generates and compiles the model. It panics on a compile +// error: the generator and the schema ship together, so a refusal is a +// programming error, not an operator one. +func Profile() *workflowmodel.Profile { + p, diags, err := workflowmodel.Compile(Generate()) + if err != nil { + panic(fmt.Sprintf("hivedefault: %v (%d diagnostics)", err, len(diags))) + } + return p +} diff --git a/src/pkg/workflowmodel/hivedefault/hivedefault_test.go b/src/pkg/workflowmodel/hivedefault/hivedefault_test.go new file mode 100644 index 0000000000..585029e136 --- /dev/null +++ b/src/pkg/workflowmodel/hivedefault/hivedefault_test.go @@ -0,0 +1,151 @@ +package hivedefault + +import ( + "encoding/json" + "testing" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" +) + +func TestGenerateCompiles(t *testing.T) { + m := Generate() + if err := m.Validate(); err != nil { + t.Fatal(err) + } + p, diags, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("%v\n%+v", err, diags) + } + if len(diags) != 0 { + t.Errorf("hive-default must compile clean, got %+v", diags) + } + if p.Name != Name || p.Version != Version || p.Mode != workflowmodel.DerivationBuiltin { + t.Fatalf("profile %s@%s mode %s", p.Name, p.Version, p.Mode) + } + if Profile().Hash != p.Hash { + t.Fatal("Profile() is not Generate() compiled") + } +} + +func TestEveryStageIsAState(t *testing.T) { + p := Profile() + ids := map[string]bool{} + for _, d := range stagelabels.Table { + id := StateID(d.Stage) + if ids[id] { + t.Errorf("StateID(%s) = %q collides", d.Stage, id) + } + ids[id] = true + s, ok := p.States[id] + if !ok { + t.Errorf("stage %s has no state %q", d.Stage, id) + continue + } + if s.Lifecycle.Number != d.Number { + t.Errorf("state %q number %d, stage %d", id, s.Lifecycle.Number, d.Number) + } + if got, ok := p.StateForNumber(d.Number); !ok || got != id { + t.Errorf("StateForNumber(%d) = %q %v, want %q", d.Number, got, ok, id) + } + if p.ColumnOf[id] == "" || p.ColumnOf[id] == ColumnOpen || p.ColumnOf[id] == ColumnMerged { + t.Errorf("state %q sits in column %q", id, p.ColumnOf[id]) + } + wantKind := workflowmodel.KindIssue + if d.PR { + wantKind = workflowmodel.KindPR + } + if len(s.Lifecycle.Kinds) != 1 || s.Lifecycle.Kinds[0] != wantKind { + t.Errorf("state %q kinds %v, want [%s]", id, s.Lifecycle.Kinds, wantKind) + } + } + if StateID(stagelabels.IssueNeedsDecision) == StateID(stagelabels.NeedsDecision) { + t.Error("045 and 085 must have distinct state ids") + } +} + +func TestColumnsMatchTheMonitor(t *testing.T) { + p := Profile() + want := []string{ColumnOpen, ColumnActionable, ColumnClaimed, ColumnPRInProgress, ColumnCIReview, ColumnMergeQueue, ColumnMerged} + if len(p.Columns) != len(want) { + t.Fatalf("columns %+v", p.Columns) + } + for i, c := range p.Columns { + if c.ID != want[i] { + t.Errorf("column %d = %q, want %q", i, c.ID, want[i]) + } + if c.Terminal != (c.ID == ColumnMerged) { + t.Errorf("column %q terminal %v", c.ID, c.Terminal) + } + } + // tracker-row-anchor.js: 15/17/18/45 light Actionable, 40 lights PR in + // progress, 6x/7x light CI / Review, 85+ light Merge queue. + for n, col := range map[int]string{10: ColumnActionable, 15: ColumnActionable, 45: ColumnActionable, 20: ColumnClaimed, 30: ColumnPRInProgress, 40: ColumnPRInProgress, 50: ColumnCIReview, 60: ColumnCIReview, 74: ColumnCIReview, 80: ColumnMergeQueue, 85: ColumnMergeQueue, 100: ColumnMergeQueue} { + id, _ := p.StateForNumber(n) + if p.ColumnOf[id] != col { + t.Errorf("stage %d (%s) in %q, want %q", n, id, p.ColumnOf[id], col) + } + } + if !p.Terminal[StateMerged] || !p.Terminal[StateClosed] || p.Terminal[StateOpen] { + t.Errorf("terminal %v", p.Terminal) + } +} + +// The transition graph is the stage engine's expected-edge table plus +// intake and closure: no edge the engine would log as an anomaly. +func TestTransitionsMirrorTheEngine(t *testing.T) { + m := Generate() + have := map[[2]string]bool{} + for _, tr := range m.Spec.Transitions { + have[[2]string{tr.From, tr.To}] = true + } + for _, e := range stageengine.DiagramEdges() { + k := [2]string{StateID(e.From), StateID(e.To)} + if !have[k] { + t.Errorf("engine edge %s -> %s missing from the model", e.From, e.To) + } + } + for _, d := range stagelabels.Table { + id := StateID(d.Stage) + if !have[[2]string{id, StateClosed}] { + t.Errorf("%s has no closure edge", id) + } + } + if !have[[2]string{StateOpen, StateID(stagelabels.Actionable)}] || !have[[2]string{StateOpen, StateID(stagelabels.ReviewPending)}] { + t.Error("intake edges missing") + } +} + +func TestModelRoundTripsJSON(t *testing.T) { + m := Generate() + b, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + var back workflowmodel.Model + if err := json.Unmarshal(b, &back); err != nil { + t.Fatal(err) + } + p1, _, err := workflowmodel.Compile(&back) + if err != nil { + t.Fatal(err) + } + if p1.Hash != Profile().Hash { + t.Fatal("hash changed across a JSON round trip") + } +} + +func TestOwnerAndStateIDHelpers(t *testing.T) { + if StateID(stagelabels.None) != "" { + t.Error("None is not a state") + } + for _, d := range stagelabels.Table { + if owner(d) == "" { + t.Errorf("stage %s has no owner", d.Stage) + } + if label(d) == "" { + t.Errorf("stage %s has no label", d.Stage) + } + } +} diff --git a/src/pkg/workflowmodel/ingest/lifecycle.go b/src/pkg/workflowmodel/ingest/lifecycle.go new file mode 100644 index 0000000000..b231f66f18 --- /dev/null +++ b/src/pkg/workflowmodel/ingest/lifecycle.go @@ -0,0 +1,139 @@ +package ingest + +import ( + "fmt" + "sort" + "strings" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// LifecycleVersion is the spec.meta.version every ingested lifecycle +// model starts at; the store and marketplace assign later versions. +const LifecycleVersion = "1" + +// EventPipelineSucceeded moves work along the ingested post-merge chain. +const EventPipelineSucceeded = "pipeline-succeeded" + +// Lifecycle ingests files for scope and returns a model with the RFC's +// lifecycle half filled in so that it compiles: the hive-default lifecycle +// (states, columns, builtin derivation, roles, gates, events) plus the +// repository's pipelines bound where they run — PR-verify pipelines on the +// CI / Review states, and the post-merge chain (main CI, release, deploys, +// done) as new columns after Merged. Everything the ingest added is +// origin ingested, confidence inferred (the compiler warns per element) +// and the model's provenance is ingested-unreviewed until a human edits it. +// +// The process half (Repository) is unchanged; this composes on top of it. +func Lifecycle(scope workflowmodel.Scope, files map[string][]byte) *workflowmodel.Model { + base := Repository(scope, files) + m := hivedefault.Generate() + m.Metadata.Name = base.Metadata.Name + m.Metadata.Annotations = base.Metadata.Annotations + m.Spec.Scope = scope + m.Spec.Meta.Version = LifecycleVersion + m.Spec.Meta.Author = "" + m.Spec.Meta.Description = fmt.Sprintf("Lifecycle ingested from %s: hive-default stages with the repository's pipelines bound", scope.Repository) + m.Spec.Meta.Source = ingestSource(base) + m.Spec.Meta.Provenance = workflowmodel.ProvenanceIngestedUnreviewed + m.Spec.Pipelines = base.Spec.Pipelines + m.Spec.Sources = base.Spec.Sources + m.Spec.Coverage = base.Spec.Coverage + if len(base.Spec.Pipelines) == 0 { + return m + } + + cite := citations(base.Spec.Pipelines) + + // PR-verify pipelines run on every head in the CI / Review column. + if ci := base.FindState(workflowmodel.StateCI); ci != nil && len(ci.Pipelines) > 0 { + for i := range m.Spec.States { + s := &m.Spec.States[i] + if s.Lifecycle.Column == hivedefault.ColumnCIReview { + s.Pipelines = append([]string(nil), ci.Pipelines...) + s.Lifecycle.Citations = cite(ci.Pipelines) + } + } + } + + // The post-merge chain: every ingested state after Merged, in order. + var post []workflowmodel.State + for _, s := range base.Spec.States { + if s.Origin == workflowmodel.OriginIngested && s.ID != workflowmodel.StateCI { + post = append(post, s) + } + } + if len(post) == 0 { + return m + } + for _, g := range base.Spec.Guards { + if g.Kind == workflowmodel.GuardEnvironmentApproval { + m.Spec.Guards = append(m.Spec.Guards, g) + } + } + m.Spec.Events = append(m.Spec.Events, workflowmodel.Event{ + ID: EventPipelineSucceeded, Label: "Post-merge pipeline succeeded", + Fact: workflowmodel.Predicate{Fact: "pipeline.status", Op: workflowmodel.OpIs, Value: "green"}, + Confidence: workflowmodel.ConfidenceInferred, + }) + prev := hivedefault.StateMerged + for _, s := range post { + st := s + st.Lifecycle = workflowmodel.StateLifecycle{Column: st.ID, Kinds: []workflowmodel.ItemKind{workflowmodel.KindPR}, Confidence: workflowmodel.ConfidenceInferred, Citations: cite(st.Pipelines)} + col := workflowmodel.Column{ID: st.ID, Label: st.Label, States: []string{st.ID}, Terminal: st.Type == workflowmodel.StateFinal} + if st.ID == workflowmodel.StateDone { + col.Hint = "Every post-merge pipeline has run" + } else { + col.Hint = "Runs after merge: " + strings.Join(st.Pipelines, ", ") + } + m.Spec.States = append(m.Spec.States, st) + m.Spec.Columns = append(m.Spec.Columns, col) + m.Spec.Transitions = append(m.Spec.Transitions, workflowmodel.Transition{From: prev, To: st.ID, On: EventPipelineSucceeded, GuardRef: st.GuardRef, Note: "ingested post-merge chain"}) + prev = st.ID + } + return m +} + +// ingestSource is the meta source for the systems the pipelines came from. +func ingestSource(m *workflowmodel.Model) workflowmodel.MetaSource { + var gha, tkn bool + for _, p := range m.Spec.Pipelines { + if p.System == workflowmodel.SystemTekton { + tkn = true + } else { + gha = true + } + } + switch { + case gha && !tkn: + return workflowmodel.SourceGitHubActions + case tkn && !gha: + return workflowmodel.SourceTekton + case gha && tkn: + return workflowmodel.SourceGitHubActions + "+" + workflowmodel.SourceTekton + } + return "" +} + +// citations returns a lookup from pipeline ids to the files they came from. +func citations(pipelines []workflowmodel.Pipeline) func(ids []string) []workflowmodel.Citation { + paths := map[string]string{} + for _, p := range pipelines { + paths[p.ID] = p.Path + } + return func(ids []string) []workflowmodel.Citation { + seen := map[string]bool{} + var out []workflowmodel.Citation + for _, id := range ids { + p, ok := paths[id] + if !ok || seen[p] { + continue + } + seen[p] = true + out = append(out, workflowmodel.Citation{Path: p, Text: id}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out + } +} diff --git a/src/pkg/workflowmodel/ingest/lifecycle_test.go b/src/pkg/workflowmodel/ingest/lifecycle_test.go new file mode 100644 index 0000000000..f37f884001 --- /dev/null +++ b/src/pkg/workflowmodel/ingest/lifecycle_test.go @@ -0,0 +1,144 @@ +package ingest + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// Every corpus repository must yield a lifecycle model that compiles; +// refusals are the ingest's bug, warnings are the inferred elements. +func TestLifecycleCorpusCompiles(t *testing.T) { + entries, err := os.ReadDir(corpusDir) + if err != nil { + t.Fatal(err) + } + seen := 0 + for _, e := range entries { + if !e.IsDir() { + continue + } + seen++ + t.Run(e.Name(), func(t *testing.T) { + repo := strings.ReplaceAll(e.Name(), "__", "/") + m := Lifecycle(workflowmodel.Scope{Forge: "github.com", Repository: repo}, readRepo(t, filepath.Join(corpusDir, e.Name()))) + p, diags, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("compile: %v\n%v", err, diags) + } + if p.Mode != workflowmodel.DerivationBuiltin { + t.Fatalf("mode %q", p.Mode) + } + if m.Spec.Meta.Provenance != workflowmodel.ProvenanceIngestedUnreviewed || m.Spec.Meta.Version == "" { + t.Fatalf("meta %+v", m.Spec.Meta) + } + if len(m.Spec.Pipelines) == 0 { + t.Fatal("corpus repo ingested no pipelines") + } + // The hive-default lifecycle is intact underneath. + for _, s := range hivedefault.Generate().Spec.States { + if _, ok := p.States[s.ID]; !ok { + t.Fatalf("hive-default state %q missing", s.ID) + } + } + // Every ingested element is inferred and warned about. + inferred := 0 + for _, d := range diags { + if d.Code == workflowmodel.CodeInferred { + inferred++ + } + } + ingested := 0 + for _, s := range m.Spec.States { + if s.Origin == workflowmodel.OriginIngested { + ingested++ + if s.Lifecycle.Confidence != workflowmodel.ConfidenceInferred || s.Lifecycle.Column != s.ID { + t.Fatalf("ingested state %+v", s.Lifecycle) + } + if s.ID != workflowmodel.StateDone && len(s.Lifecycle.Citations) == 0 { + t.Fatalf("ingested state %q has no citations", s.ID) + } + } + } + if ingested > 0 && inferred == 0 { + t.Fatalf("%d ingested states but no inferred warnings", ingested) + } + }) + } + if seen == 0 { + t.Fatal("empty corpus") + } +} + +func TestLifecyclePostMergeChain(t *testing.T) { + files := map[string][]byte{ + ".github/workflows/ci.yml": []byte("name: CI\non: [pull_request, push]\njobs:\n test:\n runs-on: ubuntu-latest\n steps: [{run: make test}]\n"), + ".github/workflows/release.yml": []byte("name: Release\non:\n push:\n tags: ['v*']\njobs:\n publish:\n runs-on: ubuntu-latest\n environment: production\n steps: [{run: make publish}]\n"), + } + m := Lifecycle(workflowmodel.Scope{Forge: "github.com", Repository: "acme/widgets"}, files) + p, diags, err := workflowmodel.Compile(m) + if err != nil { + t.Fatalf("%v %v", err, diags) + } + if m.Spec.Meta.Source != workflowmodel.SourceGitHubActions { + t.Fatalf("source %q", m.Spec.Meta.Source) + } + // Columns: hive-default's seven, then main CI, release, done. + var cols []string + for _, c := range m.Spec.Columns { + cols = append(cols, c.ID) + } + got := strings.Join(cols, " ") + if !strings.HasSuffix(got, hivedefault.ColumnMerged+" "+workflowmodel.StateMainCI+" "+workflowmodel.StateRelease+" "+workflowmodel.StateDone) { + t.Fatalf("columns %s", got) + } + if !p.Terminal[workflowmodel.StateDone] || !p.Terminal[hivedefault.StateMerged] { + t.Fatalf("terminal %v", p.Terminal) + } + // PR-verify pipelines sit on every CI / Review state with a citation. + bound := 0 + for _, s := range m.Spec.States { + if s.Lifecycle.Column == hivedefault.ColumnCIReview { + if len(s.Pipelines) != 1 || len(s.Lifecycle.Citations) != 1 || s.Lifecycle.Citations[0].Path != ".github/workflows/ci.yml" { + t.Fatalf("ci state %q: %v %v", s.ID, s.Pipelines, s.Lifecycle.Citations) + } + bound++ + } + } + if bound == 0 { + t.Fatal("no CI / Review state bound") + } + // The chain fires on the declared pipeline event, merged -> main-ci -> release -> done. + var chain []string + for _, tr := range m.Spec.Transitions { + if tr.On == EventPipelineSucceeded { + chain = append(chain, tr.From+">"+tr.To) + } + } + if want := "merged>main-ci main-ci>release release>done"; strings.Join(chain, " ") != want { + t.Fatalf("chain %v", chain) + } +} + +func TestLifecycleNoPipelinesIsHiveDefaultLifecycle(t *testing.T) { + m := Lifecycle(workflowmodel.Scope{Forge: "github.com", Repository: "acme/empty"}, map[string][]byte{"README.md": []byte("hi")}) + p, _, err := workflowmodel.Compile(m) + if err != nil { + t.Fatal(err) + } + ref, _, _ := workflowmodel.Compile(hivedefault.Generate()) + if len(p.States) != len(ref.States) || len(m.Spec.Columns) != len(hivedefault.Generate().Spec.Columns) { + t.Fatalf("states %d/%d", len(p.States), len(ref.States)) + } + if m.Spec.Meta.Source != "" || m.Spec.Meta.Provenance != workflowmodel.ProvenanceIngestedUnreviewed { + t.Fatalf("meta %+v", m.Spec.Meta) + } +} + +func scopeFor(repo string) workflowmodel.Scope { + return workflowmodel.Scope{Forge: "github.com", Repository: repo} +} diff --git a/src/pkg/workflowmodel/ingest/tree.go b/src/pkg/workflowmodel/ingest/tree.go new file mode 100644 index 0000000000..570674ef2f --- /dev/null +++ b/src/pkg/workflowmodel/ingest/tree.go @@ -0,0 +1,90 @@ +package ingest + +import ( + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/hivecommons/hive/pkg/workflowmodel/githubactions" + "github.com/hivecommons/hive/pkg/workflowmodel/tekton" +) + +// MaxTreeFiles bounds how many CI files ReadTree returns from one +// checkout; a monorepo past this is reported, not read to exhaustion. +const MaxTreeFiles = 2000 + +// tektonDirs are the directories Tekton resources conventionally live in +// (the same list the survey collector used, so a spoke ingest reads what +// the corpus read). +var tektonDirs = []string{".tekton/", "tekton/", "pipelines/", ".pipelines/", "openshift/ci/", "ci/tekton/"} + +// skipDirs are never descended into. +var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true, "testdata": true, "third_party": true} + +// ReadTree walks a checkout and returns the CI definition files the ingest +// reads, keyed by repo-relative slash path: every GitHub Actions workflow, +// every YAML under a Tekton directory, and any other YAML whose name hints +// at a pipeline and whose content looks like a Tekton document. Files over +// MaxFileBytes are returned too (Repository reports them). The result is +// what Repository and Lifecycle take. +func ReadTree(root string) (map[string][]byte, error) { + files := map[string][]byte{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, rerr := filepath.Rel(root, p) + if rerr != nil { + return rerr + } + rel = filepath.ToSlash(rel) + if d.IsDir() { + if rel != "." && skipDirs[d.Name()] { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() || !isYAMLPath(rel) || len(files) >= MaxTreeFiles { + return nil + } + switch { + case githubactions.IsWorkflowPath(rel), underTektonDir(rel): + case hintsPipeline(rel): + data, err := os.ReadFile(p) + if err != nil { + return err + } + if tekton.LooksTekton(data) { + files[rel] = data + } + return nil + default: + return nil + } + data, err := os.ReadFile(p) + if err != nil { + return err + } + files[rel] = data + return nil + }) + if err != nil { + return nil, err + } + return files, nil +} + +func underTektonDir(rel string) bool { + for _, d := range tektonDirs { + if strings.HasPrefix(rel, d) { + return true + } + } + return false +} + +func hintsPipeline(rel string) bool { + base := strings.ToLower(filepath.Base(rel)) + return strings.Contains(base, "pipeline") || strings.Contains(base, "tekton") +} diff --git a/src/pkg/workflowmodel/ingest/tree_test.go b/src/pkg/workflowmodel/ingest/tree_test.go new file mode 100644 index 0000000000..6c25e1b936 --- /dev/null +++ b/src/pkg/workflowmodel/ingest/tree_test.go @@ -0,0 +1,66 @@ +package ingest + +import ( + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +func TestReadTreeSelectsCIFiles(t *testing.T) { + root := t.TempDir() + write := func(rel, body string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + write(".github/workflows/ci.yml", "on: push\njobs: {}\n") + write(".github/workflows/nested/no.yml", "on: push\n") + write(".github/dependabot.yml", "version: 2\n") + write(".tekton/pr.yaml", "apiVersion: tekton.dev/v1\nkind: PipelineRun\n") + write("ci/tekton/build.yaml", "kind: Task\n") + write("deploy/release-pipeline.yaml", "apiVersion: tekton.dev/v1\nkind: Pipeline\n") + write("deploy/other-pipeline.yaml", "apiVersion: apps/v1\nkind: Deployment\n") + write("charts/values.yaml", "replicas: 1\n") + write("vendor/x/.github/workflows/v.yml", "on: push\n") + write("testdata/pipeline.yaml", "apiVersion: tekton.dev/v1\n") + write("README.md", "hi\n") + + files, err := ReadTree(root) + if err != nil { + t.Fatal(err) + } + var got []string + for p := range files { + got = append(got, p) + } + sort.Strings(got) + want := ".github/workflows/ci.yml .tekton/pr.yaml ci/tekton/build.yaml deploy/release-pipeline.yaml" + if strings.Join(got, " ") != want { + t.Fatalf("got %v", got) + } +} + +func TestReadTreeFeedsLifecycle(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, ".github", "workflows"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, ".github", "workflows", "ci.yml"), []byte("name: CI\non: pull_request\njobs:\n t:\n runs-on: ubuntu-latest\n steps: [{run: true}]\n"), 0o644); err != nil { + t.Fatal(err) + } + files, err := ReadTree(root) + if err != nil { + t.Fatal(err) + } + m := Lifecycle(scopeFor("acme/x"), files) + if len(m.Spec.Pipelines) != 1 { + t.Fatalf("pipelines %d", len(m.Spec.Pipelines)) + } +} diff --git a/src/pkg/workflowmodel/lifecycle.go b/src/pkg/workflowmodel/lifecycle.go new file mode 100644 index 0000000000..5860bdac49 --- /dev/null +++ b/src/pkg/workflowmodel/lifecycle.go @@ -0,0 +1,281 @@ +package workflowmodel + +// This file holds the lifecycle half of the schema (hivecommons/hive#17620 +// "The model"): columns, stage numbers, events, gates, roles, agents, +// checks, bookkeeping and labels. The ingest half (pipelines, coverage) is +// in model.go. A model that only carries the ingest half still validates; +// Compile needs the lifecycle half too. + +// Meta describes a model for the library and, later, the marketplace. +type Meta struct { + Version string `json:"version"` + Author string `json:"author,omitempty"` + Description string `json:"description,omitempty"` + License string `json:"license,omitempty"` + Source MetaSource `json:"source,omitempty"` + // Provenance is how much a human has vouched for the model. + Provenance Provenance `json:"provenance,omitempty"` +} + +// MetaSource is where the model came from. +type MetaSource string + +// Sources a model can be ingested from or written by. +const ( + SourceGitHubActions MetaSource = "github-actions" + SourceTekton MetaSource = "tekton" + SourceIssueTemplates MetaSource = "issue-templates" + SourceSpec MetaSource = "spec" + SourceHand MetaSource = "hand" + SourceBuiltIn MetaSource = "built-in" +) + +// Provenance tiers. Ratings and adoption never change a tier; only a +// human review does. +type Provenance string + +// Provenance values. +const ( + ProvenanceBuiltIn Provenance = "built-in" + ProvenanceCurated Provenance = "curated" + ProvenanceIngestedUnreviewed Provenance = "ingested-unreviewed" + // ProvenanceLocal is a model authored or edited on this hive and not + // (yet) published anywhere. + ProvenanceLocal Provenance = "local" +) + +// Confidence marks an element a human has not confirmed yet. +type Confidence string + +// Confidence values. The empty value means confirmed (hand-written or +// edited by a person). +const ( + ConfidenceConfirmed Confidence = "" + ConfidenceInferred Confidence = "inferred" +) + +// Citation points at the source paragraph or file an inferred element +// came from. +type Citation struct { + Path string `json:"path"` + Line int `json:"line,omitempty"` + Text string `json:"text,omitempty"` +} + +// Column is one Activity Monitor column; several states may share it. +type Column struct { + ID string `json:"id"` + Label string `json:"label"` + Hint string `json:"hint,omitempty"` + States []string `json:"states"` + Terminal bool `json:"terminal,omitempty"` +} + +// ItemKind is the kind of forge item a state or rule applies to. +type ItemKind string + +// Item kinds. The empty kind means both. +const ( + KindAny ItemKind = "" + KindIssue ItemKind = "issue" + KindPR ItemKind = "pr" +) + +// StateLifecycle is the lifecycle data on a State: where it sits on the +// board, which stage label it maps to and what a row in it may say. +type StateLifecycle struct { + // Column is the Column.ID the state is displayed in. + Column string `json:"column,omitempty"` + // Number is the stage/NNN label number; zero for states that carry + // no label (terminal observation states). + Number int `json:"number,omitempty"` + // Kinds says which item kinds may be in this state. + Kinds []ItemKind `json:"kinds,omitempty"` + // Waiting are the waiting reasons the monitor may show in this state. + Waiting []string `json:"waiting,omitempty"` + // Replies are the human-gate verbs offered in this state + // (decide:approve, release, …). + Replies []string `json:"replies,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// DerivationMode says how an item's state is computed from facts. +type DerivationMode string + +// Derivation modes. Builtin delegates to the hive's Go derivers (the +// hive-default model); Rules evaluates the model's own ordered rules. +const ( + DerivationBuiltin DerivationMode = "builtin" + DerivationRules DerivationMode = "rules" +) + +// Derivation is how the engine maps facts to a state. +type Derivation struct { + Mode DerivationMode `json:"mode"` + Rules []Rule `json:"rules,omitempty"` +} + +// Rule puts an item in State when every predicate holds. Rules are +// evaluated in order, first match wins; an item no rule matches is "not +// covered" and the engine abstains. +type Rule struct { + ID string `json:"id,omitempty"` + Kind ItemKind `json:"kind,omitempty"` + State string `json:"state"` + When []Predicate `json:"when"` + // Reason is the text stored on the record and shown on the monitor. + Reason string `json:"reason,omitempty"` +} + +// Predicate is one test over a fact the engine already has. +type Predicate struct { + Fact string `json:"fact"` + Op Op `json:"op"` + Value string `json:"value,omitempty"` +} + +// Op is a predicate operator. +type Op string + +// Operators. Is/Not compare a scalar fact; Has/Lacks test membership in a +// set fact (labels, checks); True/False test a boolean fact. +const ( + OpIs Op = "is" + OpNot Op = "not" + OpHas Op = "has" + OpLacks Op = "lacks" + OpTrue Op = "true" + OpFalse Op = "false" +) + +// FactType is the shape of a fact in the vocabulary. +type FactType string + +// Fact types. +const ( + FactBool FactType = "bool" + FactScalar FactType = "scalar" + FactSet FactType = "set" +) + +// Facts is the vocabulary a Rule may test. The engine implements every +// entry (pkg/stageengine); the compiler refuses a fact outside it. +var Facts = map[string]FactType{ + "open": FactBool, + "merged": FactBool, + "draft": FactBool, + "labels": FactSet, + "origin": FactScalar, + "author.kind": FactScalar, + "author.login": FactScalar, + "hold": FactBool, + "park": FactBool, + "issue.bucket": FactScalar, + "issue.claimed": FactBool, + "issue.covered": FactBool, + "issue.stalled": FactBool, + "issue.open_children": FactBool, + "pr.checks": FactScalar, + "pr.review": FactScalar, + "pr.changes_requested": FactBool, + "pr.conflicting": FactBool, + "pr.dco": FactScalar, + "pr.head_fresh": FactBool, + "pr.base": FactScalar, + // pipeline.status is the latest post-merge run of the pipelines bound + // to the item's state: green | red | running | unknown. The engine does + // not observe post-merge runs yet and always reports unknown, so a + // transition on it never fires; it exists so ingested post-merge chains + // compile honestly instead of inventing a fact. + "pipeline.status": FactScalar, +} + +// Event is something that moves work: a fact the engine observes, named +// so transitions and bookkeeping can refer to it. +type Event struct { + ID string `json:"id"` + Label string `json:"label,omitempty"` + // Fact is the predicate that fires the event. Two events may not bind + // the same predicate. + Fact Predicate `json:"fact"` + // Actor is the Role that may cause the event; empty for observations. + Actor string `json:"actor,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// Gate is a condition on a transition released by a role. +type Gate struct { + ID string `json:"id"` + Conditions []Predicate `json:"conditions,omitempty"` + // ReleasedBy is the Role that may release the gate. Required. + ReleasedBy string `json:"releasedBy"` + // Reply is the text posted when the gate is released. + Reply string `json:"reply,omitempty"` + Confidence Confidence `json:"confidence,omitempty"` + Citations []Citation `json:"citations,omitempty"` +} + +// RoleKind is how a role's members are determined. +type RoleKind string + +// Role kinds. Permission is a repository permission (admin, maintain, +// write); FrozenSet is a set named at an earlier event (the reviewers at +// request time); AuthorKind is authorkind (human, clanker, hive); Bot is a +// named bot login. +const ( + RolePermission RoleKind = "permission" + RoleFrozenSet RoleKind = "frozen-set" + RoleAuthorKind RoleKind = "author-kind" + RoleBot RoleKind = "bot" +) + +// RoleDef is who may fire which events and release which gates. +type RoleDef struct { + ID string `json:"id"` + Label string `json:"label,omitempty"` + Kind RoleKind `json:"kind"` + Params map[string]string `json:"params,omitempty"` + // Human is true for roles a person fills; the compiler needs at least + // one human-released gate after any agent action. + Human bool `json:"human,omitempty"` +} + +// AgentGrant says which agent profile may act in which states. +type AgentGrant struct { + Profile string `json:"profile"` + States []string `json:"states"` + Backend string `json:"backend,omitempty"` + Tools []string `json:"tools,omitempty"` + Produces []string `json:"produces,omitempty"` +} + +// Check is a CI check a gate may require. +type Check struct { + ID string `json:"id"` + Name string `json:"name"` + Required bool `json:"required,omitempty"` + Source string `json:"source,omitempty"` +} + +// Effect is a deterministic bookkeeping action on an event. +type Effect struct { + On string `json:"on"` + Action string `json:"action"` + Params map[string]string `json:"params,omitempty"` +} + +// LabelSet is the label vocabulary reconciled against the repository. +type LabelSet struct { + Prefix string `json:"prefix,omitempty"` + Entries []LabelEntry `json:"entries,omitempty"` +} + +// LabelEntry is one label; State is the state it marks, if any. +type LabelEntry struct { + Name string `json:"name"` + Color string `json:"color,omitempty"` + Description string `json:"description,omitempty"` + State string `json:"state,omitempty"` +} diff --git a/src/pkg/workflowmodel/model.go b/src/pkg/workflowmodel/model.go index 55cd35aa57..7ec6c90386 100644 --- a/src/pkg/workflowmodel/model.go +++ b/src/pkg/workflowmodel/model.go @@ -93,13 +93,23 @@ type Metadata struct { // Spec is the model body: the process graph (states, transitions, guards, // lanes) and the execution graphs (pipelines) bound into it. type Spec struct { + Meta Meta `json:"meta,omitzero"` Scope Scope `json:"scope"` Sources []Source `json:"sources,omitempty"` Initial string `json:"initial"` + Columns []Column `json:"columns,omitempty"` States []State `json:"states"` Transitions []Transition `json:"transitions,omitempty"` Guards []Guard `json:"guards,omitempty"` Lanes []Lane `json:"lanes,omitempty"` + Derivation Derivation `json:"derivation,omitzero"` + Events []Event `json:"events,omitempty"` + Gates []Gate `json:"gates,omitempty"` + Roles []RoleDef `json:"roles,omitempty"` + Agents []AgentGrant `json:"agents,omitempty"` + Checks []Check `json:"checks,omitempty"` + Bookkeeping []Effect `json:"bookkeeping,omitempty"` + Labels LabelSet `json:"labels,omitzero"` Pipelines []Pipeline `json:"pipelines,omitempty"` Coverage Coverage `json:"coverage"` } @@ -131,6 +141,8 @@ type State struct { // Pipelines bound into this state (by Pipeline.ID). Pipelines []string `json:"pipelines,omitempty"` Origin Origin `json:"origin,omitempty"` + // Lifecycle is the board/label half of the state (lifecycle.go). + Lifecycle StateLifecycle `json:"lifecycle,omitzero"` } // Transition moves work between states on an event, if its guard holds. @@ -139,6 +151,10 @@ type Transition struct { To string `json:"to"` On string `json:"on"` GuardRef string `json:"guardRef,omitempty"` + // GateRef is the lifecycle Gate (lifecycle.go) the move needs. + GateRef string `json:"gateRef,omitempty"` + // Note is the human-readable reason for the edge. + Note string `json:"note,omitempty"` } // GuardKind is the family a guard belongs to. diff --git a/src/pkg/workflowmodel/store/store.go b/src/pkg/workflowmodel/store/store.go new file mode 100644 index 0000000000..b81d46dba7 --- /dev/null +++ b/src/pkg/workflowmodel/store/store.go @@ -0,0 +1,415 @@ +// Package store persists workflow models on the hive's data volume +// (hivecommons/hive#17620, phase 2). +// +// Layout under Root: +// +// workflows//.json the model, as saved +// workflows/index.json catalogue: one entry per saved version +// +// hive-default is virtual: it is generated, listed read-only, and never +// written. Every save recompiles; a model that does not compile is still +// saved (so an editor can keep a draft) but its entry carries the +// diagnostics and Compiled=false, and Profile refuses it. +package store + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +// Layout constants. +const ( + // DefaultRoot is the spoke data volume. + DefaultRoot = "/data" + // EnvRoot overrides the root (test seam and operator relocation). + EnvRoot = "HIVE_WORKFLOWS_DATA_DIR" + // Subdir is the directory under the root. + Subdir = "workflows" + // IndexFile is the catalogue inside Subdir. + IndexFile = "index.json" +) + +// Errors. +var ( + ErrNotFound = errors.New("workflow model not found") + ErrReadOnly = errors.New("workflow model is read-only") + ErrBadName = errors.New("workflow model name must be lower-case letters, digits and hyphens") + ErrBadVersion = errors.New("workflow model version must be letters, digits, dots and hyphens") + ErrNotCompiled = errors.New("workflow model does not compile") +) + +var ( + nameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`) + versionRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]{0,31}$`) +) + +// Entry is one catalogue line. +type Entry struct { + Name string `json:"name"` + Version string `json:"version"` + Hash string `json:"hash"` + Description string `json:"description,omitempty"` + Author string `json:"author,omitempty"` + Source workflowmodel.MetaSource `json:"source,omitempty"` + Provenance workflowmodel.Provenance `json:"provenance,omitempty"` + Compiled bool `json:"compiled"` + Diagnostics []workflowmodel.Diagnostic `json:"diagnostics,omitempty"` + States int `json:"states"` + Columns int `json:"columns"` + SavedAt time.Time `json:"savedAt,omitzero"` + SavedBy string `json:"savedBy,omitempty"` + ReadOnly bool `json:"readOnly,omitempty"` + // Reserved for the marketplace and the benchmark / rating work (P7+): + // never written by the spoke store, carried verbatim across saves. + Adoption json.RawMessage `json:"adoption,omitempty"` + Ratings json.RawMessage `json:"ratings,omitempty"` + Benchmarks json.RawMessage `json:"benchmarks,omitempty"` +} + +// Key is name@version. +func (e Entry) Key() string { return e.Name + "@" + e.Version } + +// Store is the on-disk model library. +type Store struct { + root string + mu sync.Mutex +} + +// Root resolves the data root: EnvRoot, else configured, else DefaultRoot. +func Root(configured string) string { + if v := strings.TrimSpace(os.Getenv(EnvRoot)); v != "" { + return v + } + if strings.TrimSpace(configured) != "" { + return configured + } + return DefaultRoot +} + +// Open returns a Store rooted at root (the data dir, not the workflows +// subdirectory). Nothing is created until the first save. +func Open(root string) *Store { return &Store{root: root} } + +func (s *Store) dir() string { return filepath.Join(s.root, Subdir) } + +func (s *Store) modelPath(name, version string) string { + return filepath.Join(s.dir(), name, version+".json") +} + +func checkKey(name, version string) error { + if !nameRe.MatchString(name) { + return fmt.Errorf("%w: %q", ErrBadName, name) + } + if !versionRe.MatchString(version) { + return fmt.Errorf("%w: %q", ErrBadVersion, version) + } + return nil +} + +// IsBuiltin reports whether name is the generated, read-only model. +func IsBuiltin(name string) bool { return name == hivedefault.Name } + +func builtinEntry() Entry { + m := hivedefault.Generate() + p := hivedefault.Profile() + return Entry{ + Name: p.Name, Version: p.Version, Hash: p.Hash, + Description: m.Spec.Meta.Description, Author: m.Spec.Meta.Author, + Source: m.Spec.Meta.Source, Provenance: workflowmodel.ProvenanceBuiltIn, + Compiled: true, States: len(p.States), Columns: len(p.Columns), ReadOnly: true, + } +} + +func entryFor(m *workflowmodel.Model, by string, now time.Time) Entry { + e := Entry{ + Name: m.Metadata.Name, Version: m.Spec.Meta.Version, Hash: m.Hash(), + Description: m.Spec.Meta.Description, Author: m.Spec.Meta.Author, + Source: m.Spec.Meta.Source, Provenance: m.Spec.Meta.Provenance, + States: len(m.Spec.States), Columns: len(m.Spec.Columns), + SavedBy: by, + } + if !now.IsZero() { + e.SavedAt = now.UTC().Truncate(time.Second) + } + if e.Provenance == "" { + e.Provenance = workflowmodel.ProvenanceLocal + } + p, diags, err := workflowmodel.Compile(m) + e.Diagnostics = diags + e.Compiled = err == nil && p != nil + return e +} + +// List returns the catalogue: hive-default first, then saved entries by +// name then version. +func (s *Store) List() ([]Entry, error) { + s.mu.Lock() + defer s.mu.Unlock() + idx, err := s.readIndex() + if err != nil { + return nil, err + } + return append([]Entry{builtinEntry()}, idx...), nil +} + +// Get returns a saved model (or the generated hive-default) with its entry. +func (s *Store) Get(name, version string) (*workflowmodel.Model, Entry, error) { + if IsBuiltin(name) { + if version != "" && version != hivedefault.Version { + return nil, Entry{}, fmt.Errorf("%w: %s@%s", ErrNotFound, name, version) + } + return hivedefault.Generate(), builtinEntry(), nil + } + if err := checkKey(name, version); err != nil { + return nil, Entry{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + b, err := os.ReadFile(s.modelPath(name, version)) + if errors.Is(err, os.ErrNotExist) { + return nil, Entry{}, fmt.Errorf("%w: %s@%s", ErrNotFound, name, version) + } + if err != nil { + return nil, Entry{}, err + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + return nil, Entry{}, fmt.Errorf("%s@%s: %w", name, version, err) + } + idx, err := s.readIndex() + if err != nil { + return nil, Entry{}, err + } + for _, e := range idx { + if e.Name == name && e.Version == version { + return &m, e, nil + } + } + return &m, entryFor(&m, "", time.Time{}), nil +} + +// Profile returns the compiled profile for name@version; a saved draft +// that does not compile is ErrNotCompiled. +func (s *Store) Profile(name, version string) (*workflowmodel.Profile, error) { + if IsBuiltin(name) && (version == "" || version == hivedefault.Version) { + return hivedefault.Profile(), nil + } + m, _, err := s.Get(name, version) + if err != nil { + return nil, err + } + p, diags, err := workflowmodel.Compile(m) + if err != nil { + return nil, fmt.Errorf("%w: %s@%s: %s", ErrNotCompiled, name, version, summarize(diags)) + } + return p, nil +} + +func summarize(diags []workflowmodel.Diagnostic) string { + var parts []string + for _, d := range diags { + if d.Severity == workflowmodel.DiagError { + parts = append(parts, d.Code) + } + } + return strings.Join(parts, ", ") +} + +// Save writes m as metadata.name@spec.meta.version and refreshes the +// index. The model must validate (shape); a compile failure is recorded +// on the entry, not refused: drafts live in the library, never in a +// binding. +func (s *Store) Save(m *workflowmodel.Model, by string, now time.Time) (Entry, error) { + if m == nil { + return Entry{}, errors.New("nil model") + } + name, version := m.Metadata.Name, m.Spec.Meta.Version + if IsBuiltin(name) { + return Entry{}, fmt.Errorf("%w: %s", ErrReadOnly, name) + } + if err := checkKey(name, version); err != nil { + return Entry{}, err + } + if err := m.Validate(); err != nil { + return Entry{}, err + } + b, err := json.MarshalIndent(m, "", " ") + if err != nil { + return Entry{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := os.MkdirAll(filepath.Dir(s.modelPath(name, version)), 0o755); err != nil { + return Entry{}, err + } + if err := writeAtomic(s.modelPath(name, version), b); err != nil { + return Entry{}, err + } + idx, err := s.readIndex() + if err != nil { + return Entry{}, err + } + e := entryFor(m, by, now) + replaced := false + for i := range idx { + if idx[i].Name == name && idx[i].Version == version { + e.Adoption, e.Ratings, e.Benchmarks = idx[i].Adoption, idx[i].Ratings, idx[i].Benchmarks + idx[i] = e + replaced = true + } + } + if !replaced { + idx = append(idx, e) + } + return e, s.writeIndex(idx) +} + +// Delete removes one version. Whether a repository is bound to it is the +// caller's check: the config owns bindings. +func (s *Store) Delete(name, version string) error { + if IsBuiltin(name) { + return fmt.Errorf("%w: %s", ErrReadOnly, name) + } + if err := checkKey(name, version); err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := os.Remove(s.modelPath(name, version)); err != nil { + if errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("%w: %s@%s", ErrNotFound, name, version) + } + return err + } + _ = os.Remove(filepath.Join(s.dir(), name)) // succeeds only when empty + idx, err := s.readIndex() + if err != nil { + return err + } + out := idx[:0] + for _, e := range idx { + if e.Name != name || e.Version != version { + out = append(out, e) + } + } + return s.writeIndex(out) +} + +// Versions lists the entries of name, newest save first. +func (s *Store) Versions(name string) ([]Entry, error) { + all, err := s.List() + if err != nil { + return nil, err + } + var out []Entry + for _, e := range all { + if e.Name == name { + out = append(out, e) + } + } + if len(out) == 0 { + return nil, fmt.Errorf("%w: %s", ErrNotFound, name) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].SavedAt.After(out[j].SavedAt) }) + return out, nil +} + +// Rebuild regenerates the index from the model files on disk (recovery +// after a partial write or a hand-copied directory). +func (s *Store) Rebuild(now time.Time) ([]Entry, error) { + s.mu.Lock() + defer s.mu.Unlock() + names, err := os.ReadDir(s.dir()) + if errors.Is(err, os.ErrNotExist) { + return nil, s.writeIndex(nil) + } + if err != nil { + return nil, err + } + var idx []Entry + for _, d := range names { + if !d.IsDir() { + continue + } + files, err := os.ReadDir(filepath.Join(s.dir(), d.Name())) + if err != nil { + return nil, err + } + for _, f := range files { + if f.IsDir() || !strings.HasSuffix(f.Name(), ".json") { + continue + } + b, err := os.ReadFile(filepath.Join(s.dir(), d.Name(), f.Name())) + if err != nil { + return nil, err + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + continue // not a model; leave it alone + } + if m.Metadata.Name != d.Name() || m.Spec.Meta.Version+".json" != f.Name() { + continue // misfiled + } + idx = append(idx, entryFor(&m, "", now)) + } + } + return idx, s.writeIndex(idx) +} + +func sortIndex(idx []Entry) { + sort.SliceStable(idx, func(i, j int) bool { + if idx[i].Name != idx[j].Name { + return idx[i].Name < idx[j].Name + } + return idx[i].Version < idx[j].Version + }) +} + +func (s *Store) readIndex() ([]Entry, error) { + b, err := os.ReadFile(filepath.Join(s.dir(), IndexFile)) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var idx []Entry + if err := json.Unmarshal(b, &idx); err != nil { + return nil, fmt.Errorf("%s: %w", IndexFile, err) + } + return idx, nil +} + +func (s *Store) writeIndex(idx []Entry) error { + sortIndex(idx) + if idx == nil { + idx = []Entry{} + } + b, err := json.MarshalIndent(idx, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(s.dir(), 0o755); err != nil { + return err + } + return writeAtomic(filepath.Join(s.dir(), IndexFile), b) +} + +func writeAtomic(path string, b []byte) error { + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} diff --git a/src/pkg/workflowmodel/store/store_test.go b/src/pkg/workflowmodel/store/store_test.go new file mode 100644 index 0000000000..01d178341d --- /dev/null +++ b/src/pkg/workflowmodel/store/store_test.go @@ -0,0 +1,259 @@ +package store + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +func techdocs(t *testing.T) *workflowmodel.Model { + t.Helper() + b, err := os.ReadFile("../testdata/models/techdocs.json") + if err != nil { + t.Fatal(err) + } + var m workflowmodel.Model + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return &m +} + +var t0 = time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC) + +func TestEmptyStoreListsBuiltin(t *testing.T) { + s := Open(t.TempDir()) + got, err := s.List() + if err != nil || len(got) != 1 || got[0].Name != hivedefault.Name || !got[0].ReadOnly || !got[0].Compiled || got[0].Provenance != workflowmodel.ProvenanceBuiltIn { + t.Fatalf("%v %+v", err, got) + } + m, e, err := s.Get(hivedefault.Name, "") + if err != nil || m == nil || e.Hash != hivedefault.Profile().Hash { + t.Fatalf("%v %+v", err, e) + } + if _, _, err := s.Get(hivedefault.Name, "9"); !errors.Is(err, ErrNotFound) { + t.Fatal(err) + } + p, err := s.Profile(hivedefault.Name, hivedefault.Version) + if err != nil || p.Name != hivedefault.Name { + t.Fatal(err) + } + if _, err := s.Save(hivedefault.Generate(), "andy", t0); !errors.Is(err, ErrReadOnly) { + t.Fatal(err) + } + if err := s.Delete(hivedefault.Name, "1"); !errors.Is(err, ErrReadOnly) { + t.Fatal(err) + } +} + +func TestSaveGetListDelete(t *testing.T) { + root := t.TempDir() + s := Open(root) + m := techdocs(t) + e, err := s.Save(m, "andy", t0) + if err != nil { + t.Fatal(err) + } + if !e.Compiled || e.Provenance != workflowmodel.ProvenanceLocal || e.SavedBy != "andy" || !e.SavedAt.Equal(t0) || e.States != 9 || e.Columns != 5 || e.Key() != "cncf-techdocs@1" { + t.Fatalf("%+v", e) + } + if _, err := os.Stat(filepath.Join(root, Subdir, "cncf-techdocs", "1.json")); err != nil { + t.Fatal(err) + } + list, err := s.List() + if err != nil || len(list) != 2 || list[1].Key() != "cncf-techdocs@1" { + t.Fatalf("%v %+v", err, list) + } + got, ge, err := s.Get("cncf-techdocs", "1") + if err != nil || got.Hash() != m.Hash() || ge.SavedBy != "andy" { + t.Fatalf("%v %+v", err, ge) + } + if p, err := s.Profile("cncf-techdocs", "1"); err != nil || p.Mode != workflowmodel.DerivationRules { + t.Fatal(err) + } + + // second version, then Versions is newest first + m2 := techdocs(t) + m2.Spec.Meta.Version = "2" + if _, err := s.Save(m2, "nate", t0.Add(time.Hour)); err != nil { + t.Fatal(err) + } + vs, err := s.Versions("cncf-techdocs") + if err != nil || len(vs) != 2 || vs[0].Version != "2" { + t.Fatalf("%v %+v", err, vs) + } + if _, err := s.Versions("nobody"); !errors.Is(err, ErrNotFound) { + t.Fatal(err) + } + + if err := s.Delete("cncf-techdocs", "1"); err != nil { + t.Fatal(err) + } + if err := s.Delete("cncf-techdocs", "1"); !errors.Is(err, ErrNotFound) { + t.Fatal(err) + } + if _, _, err := s.Get("cncf-techdocs", "1"); !errors.Is(err, ErrNotFound) { + t.Fatal(err) + } + list, _ = s.List() + if len(list) != 2 || list[1].Version != "2" { + t.Fatalf("%+v", list) + } + if err := s.Delete("cncf-techdocs", "2"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(root, Subdir, "cncf-techdocs")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("empty model dir should be removed: %v", err) + } +} + +func TestDraftsSaveButDoNotProfile(t *testing.T) { + s := Open(t.TempDir()) + m := techdocs(t) + m.Spec.Gates[0].ReleasedBy = "" + e, err := s.Save(m, "", t0) + if err != nil { + t.Fatal(err) + } + if e.Compiled || len(e.Diagnostics) == 0 { + t.Fatalf("%+v", e) + } + if _, err := s.Profile("cncf-techdocs", "1"); !errors.Is(err, ErrNotCompiled) { + t.Fatal(err) + } + // an invalid shape is refused outright + m.Spec.Initial = "ghost" + if _, err := s.Save(m, "", t0); err == nil { + t.Fatal("invalid model saved") + } +} + +func TestKeysAreChecked(t *testing.T) { + s := Open(t.TempDir()) + m := techdocs(t) + m.Metadata.Name = "../etc" + if _, err := s.Save(m, "", t0); !errors.Is(err, ErrBadName) { + t.Fatal(err) + } + m = techdocs(t) + m.Spec.Meta.Version = "1/../x" + if _, err := s.Save(m, "", t0); !errors.Is(err, ErrBadVersion) { + t.Fatal(err) + } + if _, _, err := s.Get("Bad Name", "1"); !errors.Is(err, ErrBadName) { + t.Fatal(err) + } + if err := s.Delete("ok", "bad version"); !errors.Is(err, ErrBadVersion) { + t.Fatal(err) + } + if _, err := s.Save(nil, "", t0); err == nil { + t.Fatal("nil saved") + } +} + +func TestResaveKeepsReservedFields(t *testing.T) { + root := t.TempDir() + s := Open(root) + m := techdocs(t) + if _, err := s.Save(m, "", t0); err != nil { + t.Fatal(err) + } + idx, _ := s.readIndex() + idx[0].Ratings = json.RawMessage(`{"stars":5}`) + if err := s.writeIndex(idx); err != nil { + t.Fatal(err) + } + m.Spec.Meta.Description = "edited" + e, err := s.Save(m, "", t0.Add(time.Minute)) + if err != nil || e.Description != "edited" { + t.Fatalf("%v %+v", err, e) + } + var r struct{ Stars int } + if err := json.Unmarshal(e.Ratings, &r); err != nil || r.Stars != 5 { + t.Fatalf("ratings %s: %v", e.Ratings, err) + } +} + +func TestRebuild(t *testing.T) { + root := t.TempDir() + s := Open(root) + if _, err := s.Save(techdocs(t), "", t0); err != nil { + t.Fatal(err) + } + // corrupt the index, drop a stray file and a misfiled model + if err := os.WriteFile(filepath.Join(root, Subdir, IndexFile), []byte("nope"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := s.List(); err == nil { + t.Fatal("corrupt index read") + } + _ = os.WriteFile(filepath.Join(root, Subdir, "cncf-techdocs", "notes.txt"), []byte("x"), 0o644) + _ = os.WriteFile(filepath.Join(root, Subdir, "cncf-techdocs", "7.json"), []byte(`{"metadata":{"name":"other"}}`), 0o644) + _ = os.WriteFile(filepath.Join(root, Subdir, "cncf-techdocs", "8.json"), []byte(`not json`), 0o644) + idx, err := s.Rebuild(t0) + if err != nil || len(idx) != 1 || idx[0].Key() != "cncf-techdocs@1" { + t.Fatalf("%v %+v", err, idx) + } + // an index entry missing for a model on disk still resolves on Get + if err := os.WriteFile(filepath.Join(root, Subdir, IndexFile), []byte("[]"), 0o644); err != nil { + t.Fatal(err) + } + _, e, err := s.Get("cncf-techdocs", "1") + if err != nil || !e.Compiled || e.SavedBy != "" { + t.Fatalf("%v %+v", err, e) + } + + empty := Open(t.TempDir()) + if idx, err := empty.Rebuild(t0); err != nil || len(idx) != 0 { + t.Fatalf("%v %+v", err, idx) + } +} + +func TestUnreadableModelAndIndex(t *testing.T) { + root := t.TempDir() + s := Open(root) + if _, err := s.Save(techdocs(t), "", t0); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(s.modelPath("cncf-techdocs", "1"), []byte("{"), 0o644); err != nil { + t.Fatal(err) + } + if _, _, err := s.Get("cncf-techdocs", "1"); err == nil { + t.Fatal("truncated model read") + } + if _, err := s.Profile("cncf-techdocs", "1"); err == nil { + t.Fatal("truncated model profiled") + } + if err := os.WriteFile(filepath.Join(root, Subdir, IndexFile), []byte("["), 0o644); err != nil { + t.Fatal(err) + } + if _, err := s.Versions("cncf-techdocs"); err == nil { + t.Fatal("corrupt index listed") + } + if _, err := s.Save(techdocs(t), "", t0); err == nil { + t.Fatal("saved over a corrupt index") + } + if err := s.Delete("cncf-techdocs", "1"); err == nil { + t.Fatal("deleted over a corrupt index") + } + if vs, err := Open(t.TempDir()).Versions(hivedefault.Name); err != nil || len(vs) != 1 { + t.Fatalf("%v %+v", err, vs) + } +} + +func TestRoot(t *testing.T) { + t.Setenv(EnvRoot, "") + if Root("") != DefaultRoot || Root("/x") != "/x" { + t.Fatal("root resolution") + } + t.Setenv(EnvRoot, "/env") + if Root("/x") != "/env" { + t.Fatal("env must win") + } +} diff --git a/src/pkg/workflowmodel/testdata/models/techdocs.json b/src/pkg/workflowmodel/testdata/models/techdocs.json new file mode 100644 index 0000000000..bd1a529d30 --- /dev/null +++ b/src/pkg/workflowmodel/testdata/models/techdocs.json @@ -0,0 +1,79 @@ +{ + "apiVersion": "workflow.hivecommons.dev/v1alpha1", + "kind": "WorkflowModel", + "metadata": {"name": "cncf-techdocs"}, + "spec": { + "meta": {"version": "1", "author": "cncf/techdocs", "description": "Documentation engagement: request, analyse, review, iterate, publish", "source": "written"}, + "scope": {"forge": "github.com", "repository": "cncf/techdocs"}, + "initial": "requested", + "columns": [ + {"id": "requested", "label": "Requested", "states": ["requested"]}, + {"id": "analysis", "label": "Analysis", "states": ["analysing", "analysis-review"]}, + {"id": "writing", "label": "Writing", "states": ["draft-under-way", "drafting", "draft-review"]}, + {"id": "publishing", "label": "Publishing", "states": ["approved"]}, + {"id": "done", "label": "Published", "states": ["published", "withdrawn"], "terminal": true} + ], + "states": [ + {"id": "requested", "label": "Requested", "owner": "human", "lifecycle": {"number": 10, "kinds": ["issue"]}}, + {"id": "analysing", "label": "Analysing", "owner": "registered-agent", "lifecycle": {"number": 20, "kinds": ["issue"], "replies": ["hand back"]}}, + {"id": "analysis-review", "label": "Analysis review", "owner": "human", "lifecycle": {"number": 45, "kinds": ["issue"], "replies": ["approve analysis", "revise"]}}, + {"id": "draft-under-way", "label": "Draft under way", "owner": "registered-agent", "lifecycle": {"number": 40, "kinds": ["issue"]}}, + {"id": "drafting", "label": "Drafting", "owner": "registered-agent", "lifecycle": {"number": 70, "kinds": ["pr"]}}, + {"id": "draft-review", "label": "Draft review", "owner": "human", "lifecycle": {"number": 50, "kinds": ["pr"], "replies": ["approve", "request changes"]}}, + {"id": "approved", "label": "Approved", "owner": "human", "lifecycle": {"number": 90, "kinds": ["pr"]}}, + {"id": "published", "label": "Published", "owner": "external-observation", "type": "final"}, + {"id": "withdrawn", "label": "Withdrawn", "owner": "external-observation", "type": "final"} + ], + "roles": [ + {"id": "techdocs-maintainer", "label": "TechDocs maintainer", "kind": "permission", "params": {"min": "maintain"}, "human": true}, + {"id": "project-maintainer", "label": "Project maintainer", "kind": "frozen-set", "human": true} + ], + "gates": [ + {"id": "analysis-approved", "releasedBy": "techdocs-maintainer", "reply": "approve analysis"}, + {"id": "draft-approved", "releasedBy": "project-maintainer", "reply": "approve"} + ], + "events": [ + {"id": "accepted", "fact": {"fact": "labels", "op": "has", "value": "techdocs/accepted"}, "actor": "techdocs-maintainer"}, + {"id": "analysis-posted", "fact": {"fact": "labels", "op": "has", "value": "techdocs/analysis"}}, + {"id": "draft-opened", "fact": {"fact": "issue.covered", "op": "true"}}, + {"id": "pr-approved", "fact": {"fact": "pr.review", "op": "is", "value": "approved"}}, + {"id": "merged", "fact": {"fact": "merged", "op": "true"}}, + {"id": "closed", "fact": {"fact": "open", "op": "false"}} + ], + "agents": [ + {"profile": "techdocs-analyst", "states": ["analysing"], "produces": ["analysis"]}, + {"profile": "techdocs-writer", "states": ["drafting"], "produces": ["pr"]} + ], + "transitions": [ + {"from": "requested", "to": "analysing", "on": "accepted"}, + {"from": "analysing", "to": "analysis-review", "on": "analysis-posted"}, + {"from": "analysis-review", "to": "analysing", "on": "analysis-posted", "note": "revise"}, + {"from": "analysis-review", "to": "draft-under-way", "on": "draft-opened", "gateRef": "analysis-approved"}, + {"from": "draft-under-way", "to": "published", "on": "merged"}, + {"from": "draft-under-way", "to": "withdrawn", "on": "closed"}, + {"from": "analysis-review", "to": "drafting", "on": "draft-opened", "gateRef": "analysis-approved"}, + {"from": "drafting", "to": "draft-review", "on": "analysis-posted"}, + {"from": "draft-review", "to": "drafting", "on": "analysis-posted"}, + {"from": "draft-review", "to": "approved", "on": "pr-approved", "gateRef": "draft-approved"}, + {"from": "approved", "to": "published", "on": "merged"}, + {"from": "requested", "to": "withdrawn", "on": "closed"}, + {"from": "analysing", "to": "withdrawn", "on": "closed"}, + {"from": "drafting", "to": "withdrawn", "on": "closed"} + ], + "derivation": { + "mode": "rules", + "rules": [ + {"id": "closed", "state": "withdrawn", "when": [{"fact": "open", "op": "false"}, {"fact": "merged", "op": "false"}], "reason": "closed without publishing"}, + {"id": "published", "state": "published", "when": [{"fact": "merged", "op": "true"}]}, + {"id": "approved", "kind": "pr", "state": "approved", "when": [{"fact": "pr.review", "op": "is", "value": "approved"}, {"fact": "pr.checks", "op": "is", "value": "green"}]}, + {"id": "draft-review", "kind": "pr", "state": "draft-review", "when": [{"fact": "draft", "op": "false"}, {"fact": "labels", "op": "has", "value": "techdocs/*"}]}, + {"id": "drafting", "kind": "pr", "state": "drafting", "when": [{"fact": "labels", "op": "has", "value": "techdocs/*"}]}, + {"id": "analysis-review", "kind": "issue", "state": "analysis-review", "when": [{"fact": "labels", "op": "has", "value": "techdocs/analysis"}, {"fact": "issue.covered", "op": "false"}]}, + {"id": "drafting-issue", "kind": "issue", "state": "draft-under-way", "when": [{"fact": "issue.covered", "op": "true"}]}, + {"id": "analysing", "kind": "issue", "state": "analysing", "when": [{"fact": "labels", "op": "has", "value": "techdocs/accepted"}]}, + {"id": "requested", "kind": "issue", "state": "requested", "when": [{"fact": "labels", "op": "has", "value": "techdocs/request"}]} + ] + }, + "coverage": {"files": 0, "parsed": 0} + } +}