diff --git a/CHANGELOG.md b/CHANGELOG.md index e6f7e34174..4b36b59320 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,6 +73,15 @@ Hive did not historically maintain a complete changelog. This file starts a prag ### Fixed - release: cap GitHub Release notes at `RELEASE_NOTES_MAX_CHARS` (120000) before the SBOM/NOTICE trailer, cutting the changelog section at a bullet boundary and linking the tag's full `CHANGELOG.md` section, so a first-on-the-line release such as v6.0.0 no longer fails `gh release create` with HTTP 422 "body is too long" after the tag and image retags have landed. +## 2026-11-08 (v5.202.0) + +### Added + +- crux: turn signals, the fifth work service of the Crux work-services RFC ([hivecommons/crux#114](https://github.com/hivecommons/crux/issues/114) S5). Every contained run now keeps an append-only `/runs//signals.jsonl` of where its turn is and how it ended — `started` and `done` from the runner (`done` on every terminal path, with status, exit code and timed-out), `needs-input`, `input` and `blocked` from a gate opened with the new `run` field (`crux gate open --run`), and `thinking`, `tool`, `blocked`, `needs-input` or `input` posted by the run's owner. Read it with `GET /v1/runs/{id}/signals?since_seq=&limit=` or `crux --server … signal list`, post with `POST /v1/runs/{id}/signals` or `crux --server … signal emit`; each signal is also published as `run.signal` on `/v1/events`. The last kick outcome of every agent is saved under `/signals/agents/` before `agent.kick_outcome` is published, and `GET /v1/agents/{name}/kick-outcome` answers it with `settled_for_last_kick`, so a driver that missed the event learns from the record whether its turn ended. + +### Security + +- The CLI-memory drain now reaches each memory store by opening its directories one component at a time from the filesystem root, refusing any component that is a symlink and requiring each opened directory to be the inode `Lstat` saw. `cliMemoryDrainSources` already resolved stores with `EvalSymlinks` and kept only those under the agent's own home, but the drain still opened the store root by path, so an agent that swapped `.claude`, `projects` or a project slug for a symlink after that listing could have had another agent's store (or any hive-readable `memory/*.md` tree) drained under its own name and, with `truncate`, emptied. Such a store is now reported in `kept` and the drain error, never followed ([#17256](https://github.com/hivecommons/hive/issues/17256)). ## 2026-11-08 (v5.201.1) diff --git a/changelog.d/added-crux-s1-s2-followups.md b/changelog.d/added-crux-s1-s2-followups.md new file mode 100644 index 0000000000..58bc37f5a6 --- /dev/null +++ b/changelog.d/added-crux-s1-s2-followups.md @@ -0,0 +1 @@ +- crux: checkout requests are bounded by a server ceiling (`--checkout-max-bytes`, `CRUX_CHECKOUT_MAX_BYTES`), private repositories clone with `CRUX_CHECKOUT_TOKEN` through a credential helper that never logs the token, and the `job` run backend isolates each Job with a deny-all NetworkPolicy by default (`job_network: none|host|default`) diff --git a/changelog.d/added-crux-turn-signals.md b/changelog.d/added-crux-turn-signals.md deleted file mode 100644 index fafd5510c1..0000000000 --- a/changelog.d/added-crux-turn-signals.md +++ /dev/null @@ -1 +0,0 @@ -- crux: turn signals, the fifth work service of the Crux work-services RFC ([hivecommons/crux#114](https://github.com/hivecommons/crux/issues/114) S5). Every contained run now keeps an append-only `/runs//signals.jsonl` of where its turn is and how it ended — `started` and `done` from the runner (`done` on every terminal path, with status, exit code and timed-out), `needs-input`, `input` and `blocked` from a gate opened with the new `run` field (`crux gate open --run`), and `thinking`, `tool`, `blocked`, `needs-input` or `input` posted by the run's owner. Read it with `GET /v1/runs/{id}/signals?since_seq=&limit=` or `crux --server … signal list`, post with `POST /v1/runs/{id}/signals` or `crux --server … signal emit`; each signal is also published as `run.signal` on `/v1/events`. The last kick outcome of every agent is saved under `/signals/agents/` before `agent.kick_outcome` is published, and `GET /v1/agents/{name}/kick-outcome` answers it with `settled_for_last_kick`, so a driver that missed the event learns from the record whether its turn ended. diff --git a/changelog.d/added-maintainer-notes.md b/changelog.d/added-maintainer-notes.md new file mode 100644 index 0000000000..9949131cd5 --- /dev/null +++ b/changelog.d/added-maintainer-notes.md @@ -0,0 +1 @@ +- **Maintainer notes on the Activity Monitor.** With more than one maintainer running a hive, there was nowhere on the dashboard to leave a colleague a word about an item short of a GitHub comment everyone else could read. Each row now carries a 🗒 button with a count badge: click it for the item's maintainer notes — who wrote what, when — and a one-line composer (⌘/Ctrl+Enter). Notes are stored on the spoke in the append-only `/data/maintainer-notes.jsonl` and are never written to GitHub; every signed-in maintainer sees them, adding one takes write on the repo, deleting is author-or-owner, and the `maintainer-notes` SSE frame keeps the other browsers live. The scheduler types an item's notes into the agent's kick under `# Maintainer notes` (1 KB cap), so what a maintainer wrote on the row reaches whoever picks it up. `GET`/`POST /api/notes`, `DELETE /api/notes/{id}`; audited as `maintainer_note_add` / `maintainer_note_delete`. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index df871f57af..609ce23257 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -31431,6 +31431,278 @@ } } }, + "/api/notes": { + "get": { + "tags": [ + "Status" + ], + "summary": "List maintainer notes for one item, or every live note in the hive", + "description": "Maintainer notes are the private, per-item notes maintainers leave each other on Activity Monitor rows. They live in the spoke's append-only /data/maintainer-notes.jsonl and are never written to or read from GitHub; every signed-in maintainer of the hive sees them and the scheduler injects an item's notes into the agent kick under `# Maintainer notes` (1 KiB cap). Adds and deletes are broadcast on the dashboard event stream as the `maintainer-notes` SSE event {seq, repo, number, count, action}. With repo and number: that item's live notes, oldest first. With neither: every live note (the SPA's count badges). Requires a signed-in GitHub user or a verified owner session.", + "parameters": [ + { + "name": "repo", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "owner/name; must be given together with number" + }, + { + "name": "number", + "in": "query", + "required": false, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Notes", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "notes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "repo": { + "type": "string", + "description": "owner/name, lower-cased" + }, + "number": { + "type": "integer" + }, + "author": { + "type": "string", + "description": "GitHub login of the dashboard session that wrote it" + }, + "text": { + "type": "string", + "maxLength": 2000 + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": "string", + "format": "date-time", + "description": "Set on the tombstone a DELETE returns; live notes omit it" + }, + "deleted_by": { + "type": "string" + } + } + } + }, + "repo": { + "type": "string" + }, + "number": { + "type": "integer" + } + } + } + } + } + }, + "400": { + "description": "repo without number (or the reverse), or a malformed repo" + }, + "401": { + "description": "GitHub user session required" + } + } + }, + "post": { + "tags": [ + "Status" + ], + "summary": "Append a maintainer note to one issue or pull request", + "description": "Maintainer notes are the private, per-item notes maintainers leave each other on Activity Monitor rows. They live in the spoke's append-only /data/maintainer-notes.jsonl and are never written to or read from GitHub; every signed-in maintainer of the hive sees them and the scheduler injects an item's notes into the agent kick under `# Maintainer notes` (1 KiB cap). Adds and deletes are broadcast on the dashboard event stream as the `maintainer-notes` SSE event {seq, repo, number, count, action}. The author is the dashboard session's GitHub login, never a body field. Same authorisation as the hold toggle (owner, or GitHub write/maintain/admin on the repository) plus a signed-in user. Written to the audit log as maintainer_note_add.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "repo", + "number", + "text" + ], + "properties": { + "repo": { + "type": "string", + "description": "owner/name" + }, + "number": { + "type": "integer" + }, + "text": { + "type": "string", + "maxLength": 2000, + "description": "Plain text; trimmed, non-empty" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Note appended", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "note": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "repo": { + "type": "string", + "description": "owner/name, lower-cased" + }, + "number": { + "type": "integer" + }, + "author": { + "type": "string", + "description": "GitHub login of the dashboard session that wrote it" + }, + "text": { + "type": "string", + "maxLength": 2000 + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": "string", + "format": "date-time", + "description": "Set on the tombstone a DELETE returns; live notes omit it" + }, + "deleted_by": { + "type": "string" + } + } + } + } + } + } + } + }, + "400": { + "description": "Empty or over-long text, or a bad repo/number" + }, + "401": { + "description": "GitHub user session required" + }, + "403": { + "description": "Repository write permission required" + }, + "503": { + "description": "GitHub client unavailable for the permission check" + } + } + } + }, + "/api/notes/{id}": { + "delete": { + "tags": [ + "Status" + ], + "summary": "Delete (tombstone) a maintainer note", + "description": "Maintainer notes are the private, per-item notes maintainers leave each other on Activity Monitor rows. They live in the spoke's append-only /data/maintainer-notes.jsonl and are never written to or read from GitHub; every signed-in maintainer of the hive sees them and the scheduler injects an item's notes into the agent kick under `# Maintainer notes` (1 KiB cap). Adds and deletes are broadcast on the dashboard event stream as the `maintainer-notes` SSE event {seq, repo, number, count, action}. Only the note's author or a verified owner may delete; the store appends a tombstone rather than rewriting. Written to the audit log as maintainer_note_delete.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Note deleted", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "note": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "repo": { + "type": "string", + "description": "owner/name, lower-cased" + }, + "number": { + "type": "integer" + }, + "author": { + "type": "string", + "description": "GitHub login of the dashboard session that wrote it" + }, + "text": { + "type": "string", + "maxLength": 2000 + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": "string", + "format": "date-time", + "description": "Set on the tombstone a DELETE returns; live notes omit it" + }, + "deleted_by": { + "type": "string" + } + } + } + } + } + } + } + }, + "401": { + "description": "GitHub user session required" + }, + "403": { + "description": "Not the note's author and not an owner" + }, + "404": { + "description": "Unknown or already deleted note" + } + } + } + }, "/api/repos/{owner}/{repo}/items/{number}/decide-delegated": { "post": { "tags": [ diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index fe08e0e59b..8aa123d530 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -62,6 +62,7 @@ import ( "github.com/hivecommons/hive/pkg/ioscan" "github.com/hivecommons/hive/pkg/jev" "github.com/hivecommons/hive/pkg/knowledge" + "github.com/hivecommons/hive/pkg/maintainernotes" "github.com/hivecommons/hive/pkg/matrix" "github.com/hivecommons/hive/pkg/msteams" "github.com/hivecommons/hive/pkg/notify" @@ -3636,6 +3637,9 @@ func (b *boot) bootSupervision() { contributorClaimOverrideLookup(contributorClaimGuard.Load, claimsInflightLookup(b.issueClaims, b.cfg.Project.Org)), verifyOnceLookup(b.ctx, b.cfg.Project.Org, b.issueClaims, func() *github.Client { return b.ghClient }, b.logger), claimEscalationLookup(b.ctx, b.cfg, b.issueClaims, func() *github.Client { return b.ghClient }, b.logger))) + // Dashboard maintainer notes on a listed item ride its kick as private + // context (pkg/scheduler/kick_maintainer_notes.go). + b.sched.SetMaintainerNotesLookup(maintainernotes.Default().List) // #9584: close answered question issues unless the author objects (default off). b.questionAutoclose.Store(wireQuestionAutoclose(b.ctx, b.cfg, b.sched, func() *github.Client { return b.ghClient }, b.logger)) // The pr-request watcher's PR-opened hook (Linear session narration, the diff --git a/src/crux/checkout/checkout.go b/src/crux/checkout/checkout.go index 365ff6b303..15fdf58366 100644 --- a/src/crux/checkout/checkout.go +++ b/src/crux/checkout/checkout.go @@ -13,7 +13,14 @@ // transferring it, so the clone and worktree are measured after they land // and removed when they exceed the cap (ErrTooLarge). When they cannot be // measured the checkout is removed and the call fails with ErrUnsupported -// rather than delivering an uncapped copy. +// rather than delivering an uncapped copy. The operator's Config.MaxBytes +// is the ceiling a request's max_bytes may not exceed (ErrAboveCeiling) +// and the cap when the request names none. +// +// Private repositories: Config.Token, when set, reaches git only through a +// credential helper that reads it from the child's environment — never on +// the command line, never in a record, never in an error. Git is run with +// GIT_TERMINAL_PROMPT=0 so a missing credential fails instead of hanging. package checkout import ( @@ -31,6 +38,7 @@ import ( "strings" "time" + "github.com/hivecommons/hive/crux/logscrub" "github.com/hivecommons/hive/crux/sandbox" ) @@ -41,8 +49,15 @@ const ( IndexName = "index.jsonl" // IDPrefix starts every checkout id. IDPrefix = "chk_" - // DefaultMaxBytes is the size cap when a request names none: 5 GiB. + // DefaultMaxBytes is the server ceiling on a checkout's clone plus + // worktree, and the cap when a request names none: 5 GiB. DefaultMaxBytes int64 = 5 << 30 + // TokenUser is the username the credential helper pairs with + // Config.Token; GitHub and GitLab accept it for any token. + TokenUser = "x-access-token" + // tokenEnvVar carries Config.Token into the git child process for the + // credential helper to read; it is set on that process only. + tokenEnvVar = "CRUX_CHECKOUT_GIT_TOKEN" // DefaultMaxCheckouts bounds live worktrees under Dir. DefaultMaxCheckouts = 64 // MaxOwnerLen bounds the owner identifier. @@ -77,6 +92,9 @@ var ( ErrMismatch = errors.New("checkout: commit mismatch") // ErrTooLarge is a clone that exceeded max_bytes once measured. ErrTooLarge = errors.New("checkout: exceeds size cap") + // ErrAboveCeiling is a request whose max_bytes is above the server's + // Config.MaxBytes; it is also an ErrBadRequest. + ErrAboveCeiling = errors.New("checkout: max_bytes above the server ceiling") // ErrUnsupported is a cap the backend could not verify. ErrUnsupported = errors.New("checkout: cannot enforce size cap") // ErrGit is a git failure (clone, fetch, worktree). @@ -101,7 +119,15 @@ type Config struct { AllowedRepos []string // MaxCheckouts caps live worktrees; zero means DefaultMaxCheckouts. MaxCheckouts int - // Git runs git; nil uses os/exec. + // MaxBytes is the ceiling on a request's max_bytes and the cap when a + // request names none; zero means DefaultMaxBytes. + MaxBytes int64 + // Token authenticates https clones of private repositories. It is + // handed to git through a credential helper reading the child's + // environment and appears in no record, argument or error. + Token string + // Git runs git; nil uses os/exec. When Token is set the runner is + // wrapped so every git invocation carries the credential helper. Git Runner // Now is the clock; nil uses time.Now. Now func() time.Time @@ -165,11 +191,21 @@ func New(cfg Config) (*Service, error) { if cfg.MaxCheckouts <= 0 { cfg.MaxCheckouts = DefaultMaxCheckouts } - if cfg.Now == nil { - cfg.Now = time.Now + if cfg.MaxBytes < 0 { + return nil, fmt.Errorf("%w: max_bytes must not be negative", ErrBadRequest) + } + if cfg.MaxBytes == 0 { + cfg.MaxBytes = DefaultMaxBytes } + cfg.Token = strings.TrimSpace(cfg.Token) if cfg.Git == nil { - cfg.Git = execRunner + cfg.Git = execRunner(cfg.Token) + } + if cfg.Token != "" { + cfg.Git = withCredentialHelper(cfg.Git) + } + if cfg.Now == nil { + cfg.Now = time.Now } if cfg.DiskUsage == nil { cfg.DiskUsage = diskUsage @@ -333,6 +369,9 @@ func (s *Service) validate(req Request) (Record, error) { if req.MaxBytes < 0 || req.TTL < 0 { return Record{}, fmt.Errorf("%w: max_bytes and ttl must not be negative", ErrBadRequest) } + if req.MaxBytes > s.cfg.MaxBytes { + return Record{}, fmt.Errorf("%w: %w: request asks for %d bytes, this server allows at most %d", ErrBadRequest, ErrAboveCeiling, req.MaxBytes, s.cfg.MaxBytes) + } id, err := newID() if err != nil { return Record{}, err @@ -340,7 +379,7 @@ func (s *Service) validate(req Request) (Record, error) { now := s.cfg.Now().UTC() rec := Record{ID: id, Repo: repo, Commit: commit, Owner: owner, Branches: req.Branches == nil || *req.Branches, MaxBytes: req.MaxBytes, CreatedAt: now} if rec.MaxBytes == 0 { - rec.MaxBytes = DefaultMaxBytes + rec.MaxBytes = s.cfg.MaxBytes } if req.TTL > 0 { rec.TTL = req.TTL.String() @@ -406,14 +445,14 @@ func (s *Service) ensureSource(ctx context.Context, rec Record) error { args = append(args, "--", rec.Repo, rec.Source) if out, err := s.cfg.Git(ctx, s.cfg.Dir, "git", args...); err != nil { _ = os.RemoveAll(rec.Source) - return fmt.Errorf("%w: clone: %v: %s", ErrGit, err, strings.TrimSpace(string(out))) + return fmt.Errorf("%w: clone: %v: %s", ErrGit, err, gitOutput(out)) } } if _, err := s.cfg.Git(ctx, rec.Source, "git", "cat-file", "-e", rec.Commit+"^{commit}"); err == nil { return nil } if out, err := s.cfg.Git(ctx, rec.Source, "git", "fetch", "--quiet", "origin", rec.Commit); err != nil { - return fmt.Errorf("%w: commit %s is not in %s and could not be fetched: %s", ErrBadRequest, rec.Commit, rec.Repo, strings.TrimSpace(string(out))) + return fmt.Errorf("%w: commit %s is not in %s and could not be fetched: %s", ErrBadRequest, rec.Commit, rec.Repo, gitOutput(out)) } if _, err := s.cfg.Git(ctx, rec.Source, "git", "cat-file", "-e", rec.Commit+"^{commit}"); err != nil { return fmt.Errorf("%w: commit %s is not in %s", ErrBadRequest, rec.Commit, rec.Repo) @@ -458,10 +497,41 @@ func ValidID(id string) bool { return err == nil } -func execRunner(ctx context.Context, dir string, name string, args ...string) ([]byte, error) { - cmd := exec.CommandContext(ctx, name, args...) - cmd.Dir = dir - return cmd.CombinedOutput() +// execRunner is the os/exec Runner. Git never prompts, and token (when +// set) is in the child's environment for the credential helper alone. +func execRunner(token string) Runner { + return func(ctx context.Context, dir string, name string, args ...string) ([]byte, error) { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + if token != "" { + cmd.Env = append(cmd.Env, tokenEnvVar+"="+token) + } + return cmd.CombinedOutput() + } +} + +// credentialHelper is the inline helper git runs on an https challenge: it +// answers with TokenUser and the token from the child's environment, so +// the secret is never an argument. The leading "!" marks a shell snippet. +const credentialHelper = "!f() { echo username=" + TokenUser + "; echo \"password=$" + tokenEnvVar + "\"; }; f" + +// withCredentialHelper wraps inner so every git invocation first clears any +// configured helpers (a host-wide one could leak the operator's own +// credential into a caller's clone) and then installs credentialHelper. +func withCredentialHelper(inner Runner) Runner { + return func(ctx context.Context, dir string, name string, args ...string) ([]byte, error) { + if name == "git" { + args = append([]string{"-c", "credential.helper=", "-c", "credential.helper=" + credentialHelper}, args...) + } + return inner(ctx, dir, name, args...) + } +} + +// gitOutput is git's combined output as it may appear in an error: trimmed +// and scrubbed, in case a server ever echoes a credential back. +func gitOutput(out []byte) string { + return logscrub.ScrubString(strings.TrimSpace(string(out))) } // diskUsage sums regular file sizes under path. diff --git a/src/crux/checkout/checkout_test.go b/src/crux/checkout/checkout_test.go index 6629b43020..8632b07f02 100644 --- a/src/crux/checkout/checkout_test.go +++ b/src/crux/checkout/checkout_test.go @@ -324,7 +324,7 @@ func TestDeleteOwnershipAndInUse(t *testing.T) { func TestGitFailuresAreTyped(t *testing.T) { repo, shas := fixtureRepo(t) ctx := context.Background() - real := execRunner + real := execRunner("") // Clone fails: typed ErrGit and the half-made source removed. failClone := newTestService(t, repo, func(c *Config) { c.Git = func(ctx context.Context, dir, name string, args ...string) ([]byte, error) { @@ -533,3 +533,104 @@ func TestParseRepoRequiresCanonicalPath(t *testing.T) { } } } + +func TestServerCeilingBoundsTheRequestCap(t *testing.T) { + repo, shas := fixtureRepo(t) + ctx := context.Background() + svc := newTestService(t, repo, func(c *Config) { c.MaxBytes = 1 << 20 }) + // A request above the ceiling is refused before any clone. + _, err := svc.Create(ctx, Request{Repo: repo, Commit: shas[0], Owner: "o", MaxBytes: 2 << 20}) + if !errors.Is(err, ErrAboveCeiling) || !errors.Is(err, ErrBadRequest) || !strings.Contains(err.Error(), "at most 1048576") { + t.Fatalf("above ceiling = %v", err) + } + if entries, _ := os.ReadDir(filepath.Join(svc.cfg.Dir, sourceDirName)); len(entries) != 0 { + t.Fatalf("a refused request cloned: %v", entries) + } + // No request cap takes the ceiling; a smaller one is kept. + rec, err := svc.Create(ctx, Request{Repo: repo, Commit: shas[0], Owner: "o"}) + if err != nil || rec.MaxBytes != 1<<20 { + t.Fatalf("default cap = %+v, %v", rec, err) + } + rec, err = svc.Create(ctx, Request{Repo: repo, Commit: shas[1], Owner: "o", MaxBytes: 1 << 19}) + if err != nil || rec.MaxBytes != 1<<19 { + t.Fatalf("smaller cap = %+v, %v", rec, err) + } + if _, err := New(Config{Dir: t.TempDir(), MaxBytes: -1}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("negative ceiling = %v", err) + } + if plain := newTestService(t, repo, nil); plain.cfg.MaxBytes != DefaultMaxBytes { + t.Fatalf("ceiling default = %d", plain.cfg.MaxBytes) + } +} + +func TestTokenReachesGitOnlyThroughTheCredentialHelper(t *testing.T) { + repo, shas := fixtureRepo(t) + ctx := context.Background() + const token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789" + real := execRunner("") + var calls [][]string + svc := newTestService(t, repo, func(c *Config) { + c.Token = " " + token + " " + c.Git = func(ctx context.Context, dir, name string, args ...string) ([]byte, error) { + calls = append(calls, append([]string{name}, args...)) + // Drop the helper config before running the real git, so the + // fixture (a file:// repo) is unaffected. + return real(ctx, dir, name, args[4:]...) + } + }) + rec, err := svc.Create(ctx, Request{Repo: repo, Commit: shas[0], Owner: "o"}) + if err != nil { + t.Fatal(err) + } + if len(calls) == 0 { + t.Fatal("git never ran") + } + for _, call := range calls { + if call[0] != "git" || call[1] != "-c" || call[2] != "credential.helper=" || call[3] != "-c" || call[4] != "credential.helper="+credentialHelper { + t.Fatalf("git call lacks the helper: %q", call) + } + if strings.Contains(strings.Join(call, " "), token) { + t.Fatalf("token on the command line: %q", call) + } + } + if !strings.Contains(credentialHelper, "username="+TokenUser) || !strings.Contains(credentialHelper, "$"+tokenEnvVar) || strings.Contains(credentialHelper, token) { + t.Fatalf("helper = %q", credentialHelper) + } + // Records and the index never carry it. + data, _ := os.ReadFile(filepath.Join(svc.cfg.Dir, rec.ID+".json")) + index, _ := os.ReadFile(filepath.Join(svc.cfg.Dir, IndexName)) + if strings.Contains(string(data), token) || strings.Contains(string(index), token) { + t.Fatal("token written to disk") + } + // Git output in an error is scrubbed, in case a server echoes it. + leaky := newTestService(t, repo, func(c *Config) { + c.Git = func(context.Context, string, string, ...string) ([]byte, error) { + return []byte("fatal: Authentication failed for 'https://x-access-token:" + token + "@github.com/o/r'"), errors.New("exit 128") + } + }) + _, err = leaky.Create(ctx, Request{Repo: repo, Commit: shas[0], Owner: "o"}) + if !errors.Is(err, ErrGit) || strings.Contains(err.Error(), token) || !strings.Contains(err.Error(), "Authentication failed") { + t.Fatalf("leaky clone error = %v", err) + } + // A service without a token runs plain git. + plain := newTestService(t, repo, func(c *Config) { + c.Git = func(ctx context.Context, dir, name string, args ...string) ([]byte, error) { + if args[0] == "-c" { + t.Fatalf("helper configured without a token: %q", args) + } + return real(ctx, dir, name, args...) + } + }) + if _, err := plain.Create(ctx, Request{Repo: repo, Commit: shas[0], Owner: "o"}); err != nil { + t.Fatal(err) + } + // The default runner never prompts and carries the token for the helper. + out, err := execRunner(token)(ctx, t.TempDir(), "sh", "-c", "printf '%s|%s' \"$GIT_TERMINAL_PROMPT\" \"$"+tokenEnvVar+"\"") + if err != nil || string(out) != "0|"+token { + t.Fatalf("exec env = %q, %v", out, err) + } + out, err = execRunner("")(ctx, t.TempDir(), "sh", "-c", "printf '%s' \"${"+tokenEnvVar+"-unset}\"") + if err != nil || string(out) != "unset" { + t.Fatalf("exec env without token = %q, %v", out, err) + } +} diff --git a/src/crux/cli/checkout.go b/src/crux/cli/checkout.go index 7ee6bf09ca..1624a84b13 100644 --- a/src/crux/cli/checkout.go +++ b/src/crux/cli/checkout.go @@ -6,6 +6,7 @@ import ( "flag" "fmt" "os" + "strconv" "strings" "text/tabwriter" "time" @@ -70,20 +71,24 @@ func checkoutRecordToAPI(rec checkout.Record) api.Checkout { // newCheckoutService builds the service from the flag or environment // allowlist; nil with no error means no allowlist was given, so the -// service stays off. inUse is the contained-run service's hook that keeps -// a checkout with live runs from being deleted; nil means never in use. -func newCheckoutService(allow, dir, workDir string, inUse func(id string) bool) (*checkout.Service, error) { +// service stays off. maxBytes is the byte ceiling (zero reads +// CRUX_CHECKOUT_MAX_BYTES, then the package default); the private-repo +// token is read from CRUX_CHECKOUT_TOKEN only. inUse is the contained-run +// service's hook that keeps a checkout with live runs from being deleted; +// nil means never in use. +func newCheckoutService(allow, dir string, maxBytes int64, workDir string, inUse func(id string) bool) (*checkout.Service, error) { if allow == "" { allow = os.Getenv(config.CheckoutAllowlistEnvVar) } if strings.TrimSpace(allow) == "" { return nil, nil } - if dir == "" { - dir = os.Getenv(config.CheckoutDirEnvVar) - } - if dir == "" { - dir = checkout.DefaultDir(workDir) + dir = checkoutDirFor(dir, workDir) + if maxBytes == 0 { + var err error + if maxBytes, err = checkoutMaxBytesFromEnv(); err != nil { + return nil, err + } } var prefixes []string for _, p := range strings.Split(allow, ",") { @@ -91,7 +96,21 @@ func newCheckoutService(allow, dir, workDir string, inUse func(id string) bool) prefixes = append(prefixes, p) } } - return checkout.New(checkout.Config{Dir: dir, AllowedRepos: prefixes, InUse: inUse}) + return checkout.New(checkout.Config{Dir: dir, AllowedRepos: prefixes, MaxBytes: maxBytes, Token: os.Getenv(config.CheckoutTokenEnvVar), InUse: inUse}) +} + +// checkoutMaxBytesFromEnv parses CRUX_CHECKOUT_MAX_BYTES; unset is zero, +// which the service turns into its default. +func checkoutMaxBytesFromEnv() (int64, error) { + raw := strings.TrimSpace(os.Getenv(config.CheckoutMaxBytesEnvVar)) + if raw == "" { + return 0, nil + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil || n <= 0 { + return 0, fmt.Errorf("%s must be a positive byte count, got %q", config.CheckoutMaxBytesEnvVar, raw) + } + return n, nil } // cmdCheckout is the local `crux checkout`: the service on . @@ -103,8 +122,9 @@ func (e *Env) cmdCheckout(ctx context.Context, opts globalOptions, args []string fs := e.subFlags("checkout " + args[0]) allow := fs.String("allow", "", "comma-separated repo URL prefixes this command may clone (default $"+config.CheckoutAllowlistEnvVar+")") dir := fs.String("dir", "", "where checkouts live (default $"+config.CheckoutDirEnvVar+", then /"+checkout.DirName+")") + ceiling := fs.Int64("max-bytes-ceiling", 0, "largest clone plus worktree this command may deliver (default $"+config.CheckoutMaxBytesEnvVar+", then 5 GiB)") return e.checkout(ctx, func() (checkoutClient, error) { - svc, err := newCheckoutService(*allow, *dir, opts.workDir, nil) + svc, err := newCheckoutService(*allow, *dir, *ceiling, opts.workDir, nil) if err == nil && svc == nil { // No allowlist: a service that refuses every clone but can // still list and remove what exists. diff --git a/src/crux/cli/checkout_test.go b/src/crux/cli/checkout_test.go index 7e32fd3c8c..66b0aad8a1 100644 --- a/src/crux/cli/checkout_test.go +++ b/src/crux/cli/checkout_test.go @@ -148,6 +148,23 @@ func TestCheckoutUsageErrors(t *testing.T) { if code := h.run("checkout", "add", "-allow", "ssh://bad", "-repo", "https://x/y", "-commit", strings.Repeat("a", 40)); code != ExitUsage || !strings.Contains(h.stderr.String(), "crux: checkout:") { t.Errorf("bad allowlist: %d %s", code, h.stderr) } + // The ceiling comes from the flag, then the environment, and must parse. + t.Setenv(config.CheckoutMaxBytesEnvVar, "lots") + h.stderr.Reset() + if code := h.run("checkout", "list", "-allow", "file:///", "-dir", t.TempDir()); code != ExitUsage || !strings.Contains(h.stderr.String(), config.CheckoutMaxBytesEnvVar) { + t.Errorf("bad ceiling env: %d %s", code, h.stderr) + } + if code := h.run("checkout", "list", "-allow", "file:///", "-dir", t.TempDir(), "-max-bytes-ceiling", "1024"); code != ExitOK { + t.Errorf("ceiling flag overrides a bad env: %d %s", code, h.stderr) + } + t.Setenv(config.CheckoutMaxBytesEnvVar, "2048") + if n, err := checkoutMaxBytesFromEnv(); err != nil || n != 2048 { + t.Errorf("ceiling env = %d, %v", n, err) + } + t.Setenv(config.CheckoutMaxBytesEnvVar, "-5") + if _, err := checkoutMaxBytesFromEnv(); err == nil { + t.Error("negative ceiling env accepted") + } // The control socket does not forward checkout. e := &Env{Stdout: h.stdout, Stderr: h.stderr} h.stderr.Reset() diff --git a/src/crux/cli/serve.go b/src/crux/cli/serve.go index 79dc4f1db1..cd39043aed 100644 --- a/src/crux/cli/serve.go +++ b/src/crux/cli/serve.go @@ -43,6 +43,7 @@ func (e *Env) cmdServe(ctx context.Context, opts globalOptions, args []string) i var checkoutAllow, checkoutDir string fs.StringVar(&checkoutAllow, "checkout-allow", "", "comma-separated repo URL prefixes the pinned-checkout service may clone (default $"+config.CheckoutAllowlistEnvVar+"; none disables the service)") fs.StringVar(&checkoutDir, "checkout-dir", "", "where pinned checkouts live (default $"+config.CheckoutDirEnvVar+", then /"+checkout.DirName+")") + checkoutMaxBytes := fs.Int64("checkout-max-bytes", 0, "ceiling on a checkout's clone plus worktree in bytes, and the cap when a request names none (default $"+config.CheckoutMaxBytesEnvVar+", then 5 GiB); the private-repo token is $"+config.CheckoutTokenEnvVar) fs.StringVar(&operatorName, "operator-name", "", "name of the principal behind the control token on work-services routes (default $"+config.ServeOperatorNameEnvVar+", then "+serve.DefaultOperatorName+")") fs.StringVar(&laneConfig, "lanes-config", "", "opt-in durable lane configuration file (default $CRUX_LANES_CONFIG)") var runsConfig string @@ -52,7 +53,7 @@ func (e *Env) cmdServe(ctx context.Context, opts globalOptions, args []string) i return code } if fs.NArg() != 0 { - fmt.Fprintln(e.Stderr, "usage: crux serve [-socket PATH] [-listen HOST:PORT] [-token T] [-hive-callback ADDR] [-lanes-config PATH] [-operator-name NAME] [-checkout-allow PREFIXES] [-checkout-dir DIR] [-runs-config PATH]") + fmt.Fprintln(e.Stderr, "usage: crux serve [-socket PATH] [-listen HOST:PORT] [-token T] [-hive-callback ADDR] [-lanes-config PATH] [-operator-name NAME] [-checkout-allow PREFIXES] [-checkout-dir DIR] [-checkout-max-bytes N] [-runs-config PATH]") return ExitUsage } if cfg.Token == "" { @@ -126,7 +127,7 @@ func (e *Env) cmdServe(ctx context.Context, opts globalOptions, args []string) i srv.Runs = runSvc // S1 and S2 are wired both ways: a run may execute in a checkout, and a // checkout with a live run refuses deletion. - if checkouts, err := newCheckoutService(checkoutAllow, checkoutDir, opts.workDir, runSvc.InUse); err != nil { + if checkouts, err := newCheckoutService(checkoutAllow, checkoutDir, *checkoutMaxBytes, opts.workDir, runSvc.InUse); err != nil { fmt.Fprintln(e.Stderr, "crux: checkouts:", err) return ExitUsage } else if checkouts != nil { diff --git a/src/crux/config/serve.go b/src/crux/config/serve.go index 063f93a9d0..93664e24cb 100644 --- a/src/crux/config/serve.go +++ b/src/crux/config/serve.go @@ -36,6 +36,15 @@ const ( // CheckoutDirEnvVar overrides where pinned checkouts live (default // /checkouts). CheckoutDirEnvVar = "CRUX_CHECKOUT_DIR" + // CheckoutMaxBytesEnvVar is the server ceiling, in bytes, on a + // checkout's clone plus worktree and the cap when a request names none + // (default 5 GiB). + CheckoutMaxBytesEnvVar = "CRUX_CHECKOUT_MAX_BYTES" + // CheckoutTokenEnvVar is the token the pinned-checkout service hands to + // git, through a credential helper, for private https repositories. + // There is no flag: a token on the command line is visible to every + // process on the host. + CheckoutTokenEnvVar = "CRUX_CHECKOUT_TOKEN" // ServeSocketName is the socket file name under ServeSocketDir. ServeSocketName = "crux.sock" // ServeSocketDirName is the per-user directory under $XDG_RUNTIME_DIR or diff --git a/src/crux/kubejob/kubejob.go b/src/crux/kubejob/kubejob.go index 42d4b6a9fd..5a7001bc59 100644 --- a/src/crux/kubejob/kubejob.go +++ b/src/crux/kubejob/kubejob.go @@ -83,8 +83,12 @@ const ( jobLabelKey = "job-name" // managedByLabel marks Jobs this launcher created so an operator (or a // future sweeper) can list them without guessing at name prefixes. - managedByLabel = "app.kubernetes.io/managed-by" - managedByValue = "hive-kubejob" + managedByLabel = "app.kubernetes.io/managed-by" + managedByValue = "hive-kubejob" + // jobLabel marks a Job's pods with the Job name so a per-Job + // NetworkPolicy can select them without relying on the controller's + // own job-name label, whose key changed across Kubernetes releases. + jobLabel = "hive.kubestellar.io/job" agentLabel = "hive.kubestellar.io/agent" namePrefix = "hive-kick-" restartNever = "Never" @@ -124,10 +128,22 @@ type Options struct { ExtraVolumes []VolumeMount // TTLSeconds is the Job's ttlSecondsAfterFinished (default one hour). TTLSeconds int + // Network is NetworkDefault, NetworkNone or NetworkHost; empty is + // NetworkDefault so the agent sandbox, which needs the network, is + // unchanged. The contained-run backend sets NetworkNone by default. + Network string // PollInterval overrides how often the Job status is read (tests). PollInterval time.Duration } +// network is Options.Network with the empty default applied. +func (o Options) network() string { + if o.Network == "" { + return NetworkDefault + } + return o.Network +} + // Toleration mirrors the subset of corev1.Toleration an operator writes in YAML. type Toleration struct { Key string `json:"key,omitempty"` @@ -151,6 +167,21 @@ type VolumeMount struct { ReadOnly bool `json:"read_only,omitempty"` } +// Network modes, Options.Network. +const ( + // NetworkDefault leaves the pod on the cluster network with whatever + // policies the namespace already has. The empty string means this. + NetworkDefault = "default" + // NetworkNone creates a deny-all NetworkPolicy selecting the Job's pods + // before the Job and removes it with the Job; the run is refused when + // the policy cannot be created. Enforcement is the CNI's: a cluster + // whose network plugin ignores NetworkPolicy isolates nothing, and the + // launcher cannot tell. + NetworkNone = "none" + // NetworkHost runs the pod with hostNetwork. + NetworkHost = "host" +) + // Launcher implements sandbox.Launcher by running the kick as a Job. type Launcher struct { Options Options @@ -182,6 +213,11 @@ func (o Options) Validate() error { return fmt.Errorf("kubejob: volumes[%d] needs both claim and mount_path", i) } } + switch o.network() { + case NetworkDefault, NetworkNone, NetworkHost: + default: + return fmt.Errorf("kubejob: network must be %q, %q or %q, got %q", NetworkNone, NetworkHost, NetworkDefault, o.Network) + } return nil } @@ -217,7 +253,24 @@ func (l *Launcher) Run(ctx context.Context, spec sandbox.LaunchSpec) (sandbox.Re return res, err } jobsPath := fmt.Sprintf("/apis/batch/v1/namespaces/%s/jobs", ns) + policyPath := "" + if l.Options.network() == NetworkNone { + // The policy exists before any pod can: a Job created first could + // start its pod in the window before the policy lands. + policiesPath := fmt.Sprintf("/apis/networking.k8s.io/v1/namespaces/%s/networkpolicies", ns) + policy, err := json.Marshal(denyAllPolicy(ns, name)) + if err != nil { + return res, err + } + if _, err := l.do(ctx, http.MethodPost, policiesPath, policy); err != nil { + return res, fmt.Errorf("kubejob: network %q: creating the deny-all NetworkPolicy for %s: %w", NetworkNone, name, err) + } + policyPath = policiesPath + "/" + name + } if _, err := l.do(ctx, http.MethodPost, jobsPath, body); err != nil { + if policyPath != "" { + _ = l.delete(ctx, policyPath) + } return res, fmt.Errorf("kubejob: creating job %s: %w", name, err) } jobPath := jobsPath + "/" + name @@ -255,9 +308,13 @@ func (l *Launcher) Run(ctx context.Context, spec sandbox.LaunchSpec) (sandbox.Re // Context ended (kick timeout or cancel). The Job would otherwise // keep running the workload on the accelerator node; stop it. _ = l.delete(live(), jobPath) + l.deletePolicy(live(), policyPath) return res, waitErr } if !done.succeeded { + // The Job stays for inspection; its pods are finished, so the + // policy has nothing left to isolate and goes. + l.deletePolicy(live(), policyPath) res.Stderr = done.reason return res, fmt.Errorf("kubejob: job %s failed: %s", name, done.reason) } @@ -269,9 +326,35 @@ func (l *Launcher) Run(ctx context.Context, spec sandbox.LaunchSpec) (sandbox.Re // Collection may have expired the context even on success; the fresh // context ensures the finished Job is still removed immediately. _ = l.delete(live(), jobPath) + l.deletePolicy(live(), policyPath) return res, nil } +// deletePolicy removes the per-Job NetworkPolicy when one was created. +func (l *Launcher) deletePolicy(ctx context.Context, policyPath string) { + if policyPath != "" { + _ = l.delete(ctx, policyPath) + } +} + +// denyAllPolicy is a networking.k8s.io/v1 NetworkPolicy named after the +// Job that selects its pods and allows no ingress and no egress. +func denyAllPolicy(ns, job string) map[string]any { + return map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": map[string]any{ + "name": job, + "namespace": ns, + "labels": map[string]string{managedByLabel: managedByValue, jobLabel: job}, + }, + "spec": map[string]any{ + "podSelector": map[string]any{"matchLabels": map[string]string{jobLabel: job}}, + "policyTypes": []string{"Ingress", "Egress"}, + }, + } +} + type jobOutcome struct { succeeded bool reason string @@ -502,7 +585,11 @@ func (l *Launcher) manifest(ns, name, subPath string, spec sandbox.LaunchSpec) m if l.Options.SchedulerName != "" { podSpec["schedulerName"] = l.Options.SchedulerName } - labels := map[string]string{managedByLabel: managedByValue} + if l.Options.network() == NetworkHost { + podSpec["hostNetwork"] = true + podSpec["dnsPolicy"] = "ClusterFirstWithHostNet" + } + labels := map[string]string{managedByLabel: managedByValue, jobLabel: name} if spec.Name != "" { labels[agentLabel] = sanitizeLabel(spec.Name) } diff --git a/src/crux/kubejob/kubejob_test.go b/src/crux/kubejob/kubejob_test.go index 51f0488e07..a7ce49835b 100644 --- a/src/crux/kubejob/kubejob_test.go +++ b/src/crux/kubejob/kubejob_test.go @@ -33,12 +33,16 @@ type fakeAPI struct { exitCode int noPod bool logBody string - podStatus string // "terminated" or "running" - failCode int // when >0, every request fails with this status - createErr int // when >0, POST fails with this status - onJobGet func() // called (under mu) on every GET job, after it is counted - onPodLogAfterComplete func() // called (under mu) on pod log request after Job Complete - jobCompleted bool // tracks whether job status shows Complete + podStatus string // "terminated" or "running" + failCode int // when >0, every request fails with this status + createErr int // when >0, POST fails with this status + onJobGet func() // called (under mu) on every GET job, after it is counted + onPodLogAfterComplete func() // called (under mu) on pod log request after Job Complete + jobCompleted bool // tracks whether job status shows Complete + policy map[string]any // the NetworkPolicy manifest, when one was created + policyErr int // when >0, the NetworkPolicy POST fails with this status + policyDeleted bool + order []string // "policy", "job" in creation order } func newFakeAPI() *fakeAPI { @@ -55,6 +59,24 @@ func (f *fakeAPI) handler(t *testing.T) http.HandlerFunc { return } switch { + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/networkpolicies"): + if f.policyErr > 0 { + w.WriteHeader(f.policyErr) + _, _ = w.Write([]byte(`{"kind":"Status","message":"networkpolicies.networking.k8s.io is forbidden"}`)) + return + } + body, _ := io.ReadAll(r.Body) + var m map[string]any + if err := json.Unmarshal(body, &m); err != nil { + t.Errorf("policy is not JSON: %v", err) + } + f.policy = m + f.order = append(f.order, "policy") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write(body) + case r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/networkpolicies/"): + f.policyDeleted = true + _, _ = w.Write([]byte(`{"kind":"Status","status":"Success"}`)) case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/jobs"): if f.createErr > 0 { w.WriteHeader(f.createErr) @@ -67,6 +89,7 @@ func (f *fakeAPI) handler(t *testing.T) http.HandlerFunc { t.Errorf("manifest is not JSON: %v", err) } f.created = m + f.order = append(f.order, "job") w.WriteHeader(http.StatusCreated) _, _ = w.Write(body) case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/jobs/"): @@ -310,6 +333,7 @@ func TestRunValidation(t *testing.T) { {"no claim", Options{WorkspaceClaim: " "}, specFor("/data/x"), "workspace_claim"}, {"negative ttl", Options{WorkspaceClaim: "c", TTLSeconds: -1}, specFor("/data/x"), "ttl_seconds"}, {"bad volume", Options{WorkspaceClaim: "c", ExtraVolumes: []VolumeMount{{Claim: "x"}}}, specFor("/data/x"), "volumes[0]"}, + {"bad network", Options{WorkspaceClaim: "c", Network: "bridge"}, specFor("/data/x"), "network must be"}, {"no image", Options{WorkspaceClaim: "c"}, sandbox.LaunchSpec{Workspace: "/data/x"}, "image"}, {"no workspace", Options{WorkspaceClaim: "c"}, sandbox.LaunchSpec{Image: "i"}, "workspace is required"}, {"workspace outside claim", Options{WorkspaceClaim: "c"}, specFor("/tmp/elsewhere"), "not under the workspace claim mount"}, @@ -668,3 +692,104 @@ func TestManifestCopiesAllowlistedEnv(t *testing.T) { } } } + +func TestNetworkNoneWrapsTheJobInADenyAllPolicy(t *testing.T) { + api := newFakeAPI() + api.statuses = []string{statusPending, statusComplete} + srv := httptest.NewServer(api.handler(t)) + defer srv.Close() + l := newLauncher(srv, Options{Network: NetworkNone}) + if _, err := l.Run(context.Background(), specFor("/data/agents/sandbox/deps-123")); err != nil { + t.Fatalf("Run: %v", err) + } + if strings.Join(api.order, ",") != "policy,job" { + t.Fatalf("creation order = %v, want the policy before the job", api.order) + } + if !api.deleted || !api.policyDeleted { + t.Fatalf("after success job deleted=%v policy deleted=%v", api.deleted, api.policyDeleted) + } + name := api.created["metadata"].(map[string]any)["name"].(string) + meta := api.policy["metadata"].(map[string]any) + spec := api.policy["spec"].(map[string]any) + if api.policy["kind"] != "NetworkPolicy" || meta["name"] != name || meta["namespace"] != "hive" { + t.Fatalf("policy = %+v", api.policy) + } + selector := spec["podSelector"].(map[string]any)["matchLabels"].(map[string]any) + if selector[jobLabel] != name { + t.Fatalf("podSelector = %+v, want %s=%s", selector, jobLabel, name) + } + types := spec["policyTypes"].([]any) + if len(types) != 2 || types[0] != "Ingress" || types[1] != "Egress" || spec["ingress"] != nil || spec["egress"] != nil { + t.Fatalf("policy spec = %+v, want deny-all ingress and egress", spec) + } + template := api.created["spec"].(map[string]any)["template"].(map[string]any) + labels := template["metadata"].(map[string]any)["labels"].(map[string]any) + if labels[jobLabel] != name { + t.Fatalf("pod labels = %+v lack %s", labels, jobLabel) + } + if podSpec := template["spec"].(map[string]any); podSpec["hostNetwork"] != nil { + t.Fatalf("network none set hostNetwork: %+v", podSpec) + } +} + +func TestNetworkNoneRefusesToRunWithoutItsPolicy(t *testing.T) { + api := newFakeAPI() + api.policyErr = http.StatusForbidden + srv := httptest.NewServer(api.handler(t)) + defer srv.Close() + l := newLauncher(srv, Options{Network: NetworkNone}) + _, err := l.Run(context.Background(), specFor("/data/agents/sandbox/deps-123")) + if err == nil || !strings.Contains(err.Error(), "deny-all NetworkPolicy") || !strings.Contains(err.Error(), "forbidden") { + t.Fatalf("Run = %v, want the policy refusal", err) + } + if api.created != nil { + t.Fatal("the Job was created without its policy") + } +} + +func TestNetworkNonePolicyIsRemovedWhenTheJobCannotBeCreatedOrFails(t *testing.T) { + api := newFakeAPI() + api.createErr = http.StatusForbidden + srv := httptest.NewServer(api.handler(t)) + defer srv.Close() + l := newLauncher(srv, Options{Network: NetworkNone}) + if _, err := l.Run(context.Background(), specFor("/data/agents/sandbox/deps-123")); err == nil { + t.Fatal("Run succeeded without a Job") + } + if api.policy == nil || !api.policyDeleted { + t.Fatalf("policy created=%v deleted=%v after a failed job create", api.policy != nil, api.policyDeleted) + } + + api = newFakeAPI() + api.statuses = []string{statusFailed} + srv2 := httptest.NewServer(api.handler(t)) + defer srv2.Close() + l = newLauncher(srv2, Options{Network: NetworkNone}) + if _, err := l.Run(context.Background(), specFor("/data/agents/sandbox/deps-123")); err == nil { + t.Fatal("failed Job reported success") + } + if api.deleted || !api.policyDeleted { + t.Fatalf("failed job deleted=%v (want kept) policy deleted=%v (want gone)", api.deleted, api.policyDeleted) + } +} + +func TestNetworkHostAndDefaultManifests(t *testing.T) { + for _, network := range []string{NetworkHost, NetworkDefault, ""} { + api := newFakeAPI() + api.statuses = []string{statusComplete} + srv := httptest.NewServer(api.handler(t)) + l := newLauncher(srv, Options{Network: network}) + _, err := l.Run(context.Background(), specFor("/data/agents/sandbox/deps-123")) + srv.Close() + if err != nil { + t.Fatalf("network %q: %v", network, err) + } + if api.policy != nil { + t.Fatalf("network %q created a policy", network) + } + podSpec := api.created["spec"].(map[string]any)["template"].(map[string]any)["spec"].(map[string]any) + if host := network == NetworkHost; (podSpec["hostNetwork"] == true) != host || (podSpec["dnsPolicy"] == "ClusterFirstWithHostNet") != host { + t.Fatalf("network %q: hostNetwork=%v dnsPolicy=%v", network, podSpec["hostNetwork"], podSpec["dnsPolicy"]) + } + } +} diff --git a/src/crux/runs/backend.go b/src/crux/runs/backend.go index 8b2aea2a57..f43b984cf1 100644 --- a/src/crux/runs/backend.go +++ b/src/crux/runs/backend.go @@ -69,15 +69,22 @@ func BackendFromConfig(cfg Config) (*Backend, error) { return nil, fmt.Errorf("%w: backend %q needs a job block", ErrConfig, BackendJob) } opts := jobOptions(*cfg.Job) + // The default is the contained run's, not the launcher's: a Config + // that skipped Defaults still isolates. + opts.Network = cfg.JobNetwork + if opts.Network == "" { + opts.Network = kubejob.NetworkNone + } if err := opts.Validate(); err != nil { return nil, fmt.Errorf("%w: %v", ErrConfig, err) } return &Backend{ Name: BackendJob, Launcher: &kubejob.Launcher{Options: opts}, - // The Job manifest carries no network mode; only an operator's - // NetworkPolicy can enforce one, and only "none" is claimable. - Capabilities: Capabilities{NetworkNone: cfg.JobNetworkPolicy}, + // "none" is claimable when the launcher isolates each run with + // its own NetworkPolicy (job_network none) or the operator + // asserts one of theirs does; "restricted" never is. + Capabilities: Capabilities{NetworkNone: opts.Network == kubejob.NetworkNone || cfg.JobNetworkPolicy}, }, nil } return nil, fmt.Errorf("%w: unknown backend %q", ErrConfig, cfg.Backend) diff --git a/src/crux/runs/config.go b/src/crux/runs/config.go index ff472c8674..b8760ba825 100644 --- a/src/crux/runs/config.go +++ b/src/crux/runs/config.go @@ -19,10 +19,11 @@ import ( "os" "strings" - "github.com/hivecommons/hive/crux/checkout" "time" + "github.com/hivecommons/hive/crux/checkout" "github.com/hivecommons/hive/crux/config" + "github.com/hivecommons/hive/crux/kubejob" ) // Backend names, Config.Backend. @@ -62,11 +63,17 @@ type Config struct { // Job holds the Kubernetes Job settings when Backend is BackendJob; // the same shape as the agent sandbox's job block. Job *config.SandboxJobConfig `json:"job,omitempty"` - // JobNetworkPolicy is the operator's assertion that a NetworkPolicy in - // the Job namespace denies egress for pods labelled - // app.kubernetes.io/managed-by=hive-kubejob. The Job launcher cannot - // set a network mode itself, so without this assertion a request for - // network "none" on the job backend is refused. + // JobNetwork is how a Job's pod reaches the network: "none" (default) + // has the launcher create a per-run deny-all NetworkPolicy before the + // Job and refuse the run if it cannot; "host" runs the pod with + // hostNetwork; "default" leaves the pod on the cluster network. Only + // "none" lets the backend claim the network "none" capability on its + // own — and only as far as the cluster's CNI enforces NetworkPolicy. + JobNetwork string `json:"job_network,omitempty"` + // JobNetworkPolicy is the operator's assertion that a NetworkPolicy of + // their own in the Job namespace already denies egress for pods + // labelled app.kubernetes.io/managed-by=hive-kubejob. It lets a + // job_network of "host" or "default" still claim network "none". JobNetworkPolicy bool `json:"job_network_policy,omitempty"` // NetworkRestricted is the operator's assertion that a container // network named "restricted" exists on the podman host; without it a @@ -118,6 +125,9 @@ func (c *Config) Defaults() { if c.Backend == "" { c.Backend = BackendPodman } + if c.Backend == BackendJob && c.JobNetwork == "" { + c.JobNetwork = kubejob.NetworkNone + } if c.DefaultTimeoutMs <= 0 { c.DefaultTimeoutMs = DefaultTimeout.Milliseconds() } @@ -143,6 +153,11 @@ func (c Config) Validate() error { if c.Job == nil { return fmt.Errorf("%w: backend %q needs a job block", ErrConfig, BackendJob) } + switch c.JobNetwork { + case kubejob.NetworkNone, kubejob.NetworkHost, kubejob.NetworkDefault: + default: + return fmt.Errorf("%w: job_network must be %q, %q or %q", ErrConfig, kubejob.NetworkNone, kubejob.NetworkHost, kubejob.NetworkDefault) + } default: return fmt.Errorf("%w: backend must be %q or %q", ErrConfig, BackendPodman, BackendJob) } diff --git a/src/crux/runs/config_test.go b/src/crux/runs/config_test.go index ed08832811..14cb165fb9 100644 --- a/src/crux/runs/config_test.go +++ b/src/crux/runs/config_test.go @@ -23,6 +23,8 @@ func TestLoadConfig(t *testing.T) { }{ {"podman defaults", `{"image":"img"}`, ""}, {"job", `{"backend":"job","image":"img","job":{"workspace_claim":"pvc"}}`, ""}, + {"job host network", `{"backend":"job","image":"img","job":{"workspace_claim":"pvc"},"job_network":"host"}`, ""}, + {"job bad network", `{"backend":"job","image":"img","job":{"workspace_claim":"pvc"},"job_network":"bridge"}`, "job_network must be"}, {"unknown field", `{"image":"img","bogus":1}`, "bogus"}, {"no image", `{"backend":"podman"}`, "image is required"}, {"bad backend", `{"backend":"docker","image":"img"}`, "backend must be"}, @@ -45,6 +47,12 @@ func TestLoadConfig(t *testing.T) { if cfg.DefaultTimeoutMs != DefaultTimeout.Milliseconds() || cfg.MaxOutputBytesCap != DefaultMaxOutputCap { t.Fatalf("defaults not applied: %+v", cfg) } + if tc.name == "job" && cfg.JobNetwork != kubejob.NetworkNone { + t.Fatalf("job_network default = %q, want none", cfg.JobNetwork) + } + if tc.name == "job host network" && cfg.JobNetwork != kubejob.NetworkHost { + t.Fatalf("job_network = %q", cfg.JobNetwork) + } return } if err == nil || !errors.Is(err, ErrConfig) || !strings.Contains(err.Error(), tc.err) { @@ -103,15 +111,24 @@ func TestBackendFromConfig(t *testing.T) { if kube.Teardown != nil || kube.Name != BackendJob { t.Fatalf("job backend = %+v", kube) } - if what, ok := kube.Supports(api.RunNetworkNone); ok || !strings.Contains(what, `cannot enforce network "none"`) { - t.Fatalf("job none without a policy: %q %v", what, ok) + // Unset job_network is "none": the launcher isolates each run itself. + if _, ok := kube.Supports(api.RunNetworkNone); !ok { + t.Fatal("job none by default is not claimed") } opts := kube.Launcher.(*kubejob.Launcher).Options if opts.WorkspaceClaim != "pvc" || opts.TTLSeconds != 60 || len(opts.Tolerations) != 1 || opts.Tolerations[0].Key != "k" || - len(opts.ExtraVolumes) != 1 || opts.ExtraVolumes[0].MountPath != "/cache" || !opts.ExtraVolumes[0].ReadOnly { + len(opts.ExtraVolumes) != 1 || opts.ExtraVolumes[0].MountPath != "/cache" || !opts.ExtraVolumes[0].ReadOnly || opts.Network != kubejob.NetworkNone { t.Fatalf("job options = %+v", opts) } - policy, _ := BackendFromConfig(Config{Backend: BackendJob, Image: "img", Job: job, JobNetworkPolicy: true}) + // On the cluster network only the operator's own policy can claim it. + open, _ := BackendFromConfig(Config{Backend: BackendJob, Image: "img", Job: job, JobNetwork: kubejob.NetworkDefault}) + if what, ok := open.Supports(api.RunNetworkNone); ok || !strings.Contains(what, `cannot enforce network "none"`) { + t.Fatalf("job default without a policy: %q %v", what, ok) + } + if open.Launcher.(*kubejob.Launcher).Options.Network != kubejob.NetworkDefault { + t.Fatal("job_network default not passed through") + } + policy, _ := BackendFromConfig(Config{Backend: BackendJob, Image: "img", Job: job, JobNetwork: kubejob.NetworkHost, JobNetworkPolicy: true}) if _, ok := policy.Supports(api.RunNetworkNone); !ok { t.Fatal("job_network_policy ignored") } @@ -122,6 +139,7 @@ func TestBackendFromConfig(t *testing.T) { for name, cfg := range map[string]Config{ "job without block": {Backend: BackendJob, Image: "img"}, "job invalid": {Backend: BackendJob, Image: "img", Job: &config.SandboxJobConfig{}}, + "job bad network": {Backend: BackendJob, Image: "img", Job: job, JobNetwork: "bridge"}, "unknown": {Backend: "docker", Image: "img"}, } { if _, err := BackendFromConfig(cfg); !errors.Is(err, ErrConfig) { diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 8a32391e72..87decaa9b2 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -33,17 +33,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)); 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/health` | Public | Basic health probe | `pkg/dashboard/server.go:1817` | -| `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:1818` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1819` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1825` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1830` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1831` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1834` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1835` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1836` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1837` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1838` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1823` | +| `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:1824` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1825` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1831` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1836` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1837` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1840` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1841` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1842` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1843` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1844` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | @@ -86,7 +86,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1912` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1918` | | `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` | @@ -114,9 +114,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1839` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1840` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1841` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1845` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1846` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1847` | ## Configuration @@ -189,17 +189,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go: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:389` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:390` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:391` | -| `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:381` | -| `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:382` | -| `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:383` | -| `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:384` | -| `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:385` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:386` | -| `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:387` | -| `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:564` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:394` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:395` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:396` | +| `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:386` | +| `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:387` | +| `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:388` | +| `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:389` | +| `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:390` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:391` | +| `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:392` | +| `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:569` | | `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` | @@ -208,8 +208,8 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go: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:560` | -| `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:561` | +| `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:565` | +| `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:566` | | `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` | @@ -261,17 +261,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go: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:535` | -| `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:538` | -| `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:539` | -| `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:543` | +| `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:540` | +| `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:543` | +| `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:544` | +| `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:548` | | `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:547` | -| `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:548` | -| `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:551` | -| `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:553` | -| `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:556` | -| `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:557` | +| `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:552` | +| `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:553` | +| `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: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:558` | +| `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:561` | +| `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:562` | | `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` | @@ -318,12 +318,12 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `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` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park}, notes, error}`); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:583`, `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:376`, `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:377` | -| `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:378` | -| `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:380`, `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:369`, `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:588`, `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:381`, `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:382` | +| `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:383` | +| `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:385`, `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:374`, `pkg/dashboard/api_issue_release.go` | ## Cost, tokens, telemetry @@ -347,37 +347,37 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `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:396` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:397` | -| `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:406` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:398` | -| `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:399` | -| `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:400` | -| `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:401` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:407` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:408` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:409` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:410` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:411` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:412` | -| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:413` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:414` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:420` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:421` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:422` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:423` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:424` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:425` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:426` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:427` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:428` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:429` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:430` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:431` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:432` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:433` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:434` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:435` | +| `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:401` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:402` | +| `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:411` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:403` | +| `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:404` | +| `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:405` | +| `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:406` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:412` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:413` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:417` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:418` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:426` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:427` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:428` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:429` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:430` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:431` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:432` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:433` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:434` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:435` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:436` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:437` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:438` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:439` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:440` | | `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` | @@ -385,34 +385,34 @@ 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:445` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:446` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:447` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:448` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:449` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:450` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:451` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:452` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:453` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:418` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:419` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:450` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:451` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:453` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:454` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:455` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:456` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:459` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:460` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:423` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:424` | | `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:445` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:446` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:447` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:448` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:449` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:450` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:451` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:452` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:453` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:418` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:419` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:450` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:451` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:453` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:454` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:455` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:456` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:459` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:460` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:423` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:424` | | `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` | @@ -523,70 +523,70 @@ 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:490` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:491` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:492` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:493` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:494` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:496` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:497` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:498` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:499` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:500` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:501` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:502` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:503` | -| `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:504` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:505` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:506` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:507` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:508` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:509` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:510` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:511` | -| `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:514` | -| `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:515` | -| `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:516` | -| `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:517` | -| `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:495` | -| `POST` | `/api/nous/artifacts/sync` | Owner only | Nous Artifact Sync | `pkg/dashboard/api.go:512` | -| `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:513` | +| `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:495` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:496` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:497` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:498` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:499` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:501` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:502` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:503` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:504` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:505` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:506` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:508` | +| `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:509` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:510` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:511` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:512` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:515` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:516` | +| `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:519` | +| `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:520` | +| `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:521` | +| `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:522` | +| `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:500` | +| `POST` | `/api/nous/artifacts/sync` | Owner only | Nous Artifact Sync | `pkg/dashboard/api.go:517` | +| `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:518` | ## Inception | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:460` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:461` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:462` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:463` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:464` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:465` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:466` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:467` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:468` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:469` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:470` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:471` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:472` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:473` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:465` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:466` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:467` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:469` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:470` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:471` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:473` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:474` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:475` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:477` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:478` | ## Beads | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:519` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:520` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:521` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:522` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:523` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:524` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:525` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:526` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:527` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:528` | ## 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:530` | +| `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:535` | | `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` | @@ -600,11 +600,11 @@ always resolved server-side from the validated token. | `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:478` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:481` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:482` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:484` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:485` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:483` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:486` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:487` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:489` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:490` | | `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` | @@ -620,11 +620,11 @@ always resolved server-side from the validated token. | `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:394` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:457` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:458` | -| `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:487` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:525` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:399` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:462` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:463` | +| `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:492` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:530` | | `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` | @@ -652,7 +652,7 @@ always resolved server-side from the validated token. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:389` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:390` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:391` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1846` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1852` | ## Hub SaaS 102 routes — see [api-reference/hub-saas.md](api-reference/hub-saas.md). diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index 67e7e45e96..793eaa305c 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -23,15 +23,15 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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:535` | -| `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:538` | -| `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:539` | -| `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:543` | +| `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:540` | +| `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:543` | +| `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:544` | +| `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:548` | | `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:547` | -| `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:548` | -| `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:553` | -| `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:556` | +| `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:552` | +| `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:553` | +| `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:558` | +| `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:561` | | `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` | diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 6c2430bdc2..322b6c8637 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1839` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1840` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1841` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1845` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1846` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1847` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index 24ae80785e..7e4559dc3f 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:519` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:520` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:521` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:522` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:523` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:524` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:525` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:526` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:527` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:528` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 0b0b2b0c10..b78d651735 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -75,17 +75,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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:389` | -| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:390` | -| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:391` | -| `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:381` | -| `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:382` | -| `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:383` | -| `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:384` | -| `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:385` | -| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:386` | -| `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:387` | -| `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:564` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:394` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:395` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:396` | +| `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:386` | +| `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:387` | +| `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:388` | +| `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:389` | +| `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:390` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:391` | +| `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:392` | +| `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:569` | | `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` | @@ -94,8 +94,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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:560` | -| `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:561` | +| `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:565` | +| `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:566` | | `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` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 523b1137b9..6d4952da55 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -25,7 +25,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:63` | -| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:530` | +| `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:535` | | `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` | @@ -39,19 +39,19 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `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:478` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:481` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:482` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:484` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:485` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:483` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:486` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:487` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:489` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:490` | | `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:574` | -| `GET` | `/api/close-on-merge/wrong-closes` | Owner (verified owner role; 403 otherwise) | Read-only report of issues close-on-merge closed on a PR that did not close them (projectbluefin/utah-packages#490): for each watched repo, issues closed in the last `?days=N` (default 30, 1–90) whose hive "Fixed by #N" comment names a merged PR that only references the issue (`Refs`/`Part of`) or says it stays open (`reason: pr_leaves_issue_open`), or that carries `hive/verified-open` / `hive/partially-addressed` and was closed by a PR with no closing keyword for it (`reason: issue_marked_open`). The scan reads GitHub on the installation token, so it runs under a 60 s deadline, inspects at most 500 closed issues (`truncated: true` with a `note` past that) and caches each window's answer for 10 minutes (`cached_at` on a cached answer; a failed scan is not cached). GitHub's issue-list `since` filters on `updated_at`, so the close time is checked locally. Returns `{since, days, items[], inspected, truncated, complete, note?, error?, cached_at?}`, each item `{repo, issue, title, url, pr, closed_at, reason}`. Maintainers reopen what they agree with; the hive reopens nothing | `pkg/dashboard/api.go:571` | +| `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:579` | +| `GET` | `/api/close-on-merge/wrong-closes` | Owner (verified owner role; 403 otherwise) | Read-only report of issues close-on-merge closed on a PR that did not close them (projectbluefin/utah-packages#490): for each watched repo, issues closed in the last `?days=N` (default 30, 1–90) whose hive "Fixed by #N" comment names a merged PR that only references the issue (`Refs`/`Part of`) or says it stays open (`reason: pr_leaves_issue_open`), or that carries `hive/verified-open` / `hive/partially-addressed` and was closed by a PR with no closing keyword for it (`reason: issue_marked_open`). The scan reads GitHub on the installation token, so it runs under a 60 s deadline, inspects at most 500 closed issues (`truncated: true` with a `note` past that) and caches each window's answer for 10 minutes (`cached_at` on a cached answer; a failed scan is not cached). GitHub's issue-list `since` filters on `updated_at`, so the close time is checked locally. Returns `{since, days, items[], inspected, truncated, complete, note?, error?, cached_at?}`, each item `{repo, issue, title, url, pr, closed_at, reason}`. Maintainers reopen what they agree with; the hive reopens nothing | `pkg/dashboard/api.go:576` | | `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` | @@ -61,11 +61,11 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `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` | | `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:394` | -| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:457` | -| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:458` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:487` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:525` | +| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:399` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:462` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:463` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:492` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:530` | | `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` | @@ -88,7 +88,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:389` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:390` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:391` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1846` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1852` | ### Activity observation provenance diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index d56f1dc1c2..db31850517 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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/health` | Public | Basic health probe | `pkg/dashboard/server.go:1817` | -| `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:1818` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1819` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1825` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `code_scanning` `{enabled, repos[], notices[]}` is the code scanning sweep's picture, absent while the sweep is off everywhere — per repo `{repo, security_url, checked_at, open_alerts, by_severity{critical,high,medium,low,note}, qualifying, below_threshold, excluded, tracked, tracked_closed, untracked, open_issues, filed, updated, closed, truncated, notice, notice_kind, error}`, where `tracked` is open alerts listed on an open hive issue and `notice_kind` is `missing_permission` (the App lacks Code scanning alerts: Read) or `not_enabled` (see `docs/code-scanning.md`); `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1830` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1831` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1834` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1835` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1836` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1837` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1838` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1823` | +| `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:1824` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1825` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1831` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `code_scanning` `{enabled, repos[], notices[]}` is the code scanning sweep's picture, absent while the sweep is off everywhere — per repo `{repo, security_url, checked_at, open_alerts, by_severity{critical,high,medium,low,note}, qualifying, below_threshold, excluded, tracked, tracked_closed, untracked, open_issues, filed, updated, closed, truncated, notice, notice_kind, error}`, where `tracked` is open alerts listed on an open hive issue and `notice_kind` is `missing_permission` (the App lacks Code scanning alerts: Read) or `not_enabled` (see `docs/code-scanning.md`); `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1836` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1837` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1840` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1841` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1842` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1843` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1844` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 08b9f31319..25b2dffa1b 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:460` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:461` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:462` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:463` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:464` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:465` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:466` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:467` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:468` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:469` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:470` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:471` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:472` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:473` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:465` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:466` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:467` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:469` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:470` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:471` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:473` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:474` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:475` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:477` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:478` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index b72a005bcf..13ea40724f 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:396` | -| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:397` | -| `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:406` | -| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:398` | -| `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:399` | -| `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:400` | -| `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:401` | -| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:407` | -| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:408` | -| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:409` | -| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:410` | -| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:411` | -| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:412` | -| `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:403` | -| `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:413` | -| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:414` | -| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:420` | -| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:421` | -| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:422` | -| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:423` | -| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:424` | -| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:425` | -| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:426` | -| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:427` | -| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:428` | -| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:429` | -| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:430` | -| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:431` | -| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:432` | -| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:433` | -| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:434` | -| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:435` | +| `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:401` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:402` | +| `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:411` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:403` | +| `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:404` | +| `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:405` | +| `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:406` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:412` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:413` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:417` | +| `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:408` | +| `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:418` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:425` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:426` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:427` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:428` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:429` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:430` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:431` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:432` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:433` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:434` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:435` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:436` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:437` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:438` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:439` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:440` | | `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,19 +46,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/knowledge/agent-scopes` | Owner only | Replace `knowledge.agent_scopes` after validating layer and state names; persisted and audited as `config_knowledge_agent_scopes` | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/pipeline` | Owner only | Scalar bead synthesizer, curator, code map and primer settings, plus the read-only engine, vault paths and primer merge strategy ([docs](../settings.md#knowledge)) | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/pipeline` | Owner only | Update those settings after `config.ValidateKnowledgePipeline`; 0 or empty restores the default; the bead synthesizer switch applies at once, the rest after a restart; audited as `config_knowledge_pipeline` | `pkg/dashboard/api.go` | -| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:445` | -| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:446` | -| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:447` | -| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:448` | -| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:449` | -| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:450` | -| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:451` | -| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:452` | -| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:453` | -| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:454` | -| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:455` | -| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:418` | -| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:419` | +| `GET` | `/api/knowledge/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:450` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:451` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:452` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:453` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:454` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:455` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:456` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:457` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:458` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:459` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:460` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:423` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:424` | | `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 d1d7f60552..c754debb7c 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:490` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:491` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:492` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:493` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:494` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:496` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:497` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:498` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:499` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:500` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:501` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:502` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:503` | -| `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:504` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:505` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:506` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:507` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:508` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:509` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:510` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:511` | -| `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:514` | -| `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:515` | -| `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:516` | -| `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:517` | +| `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:495` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:496` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:497` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:498` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:499` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:501` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:502` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:503` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:504` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:505` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:506` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:508` | +| `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:509` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:510` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:511` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:512` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:515` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:516` | +| `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:519` | +| `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:520` | +| `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:521` | +| `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:522` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 09d359992f..9ae636c7bf 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -18,13 +18,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `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:370`, `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:371`, `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:372`, `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:371`, `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:372` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/handoff` | Same as `…/hold`, signed-in GitHub user | With a workflows blocker, verified App permission and capable lane, records the decision, clears the park and routes the issue to that lane; rejects held or ineligible issues | `pkg/dashboard/api.go:373` | -| `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:374` | -| `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:583`, `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:376`, `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:377` | -| `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:378` | -| `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:380`, `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:376`, `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:377` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/handoff` | Same as `…/hold`, signed-in GitHub user | With a workflows blocker, verified App permission and capable lane, records the decision, clears the park and routes the issue to that lane; rejects held or ineligible issues | `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:379` | +| `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:588`, `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:381`, `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:382` | +| `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:383` | +| `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:385`, `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 68beeccb57..e99d4e8efe 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1912` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1918` | | `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` | diff --git a/src/docs/crux-serve.md b/src/docs/crux-serve.md index 40e9beba36..b6cdba81c3 100644 --- a/src/docs/crux-serve.md +++ b/src/docs/crux-serve.md @@ -36,6 +36,8 @@ runtime and every agent must arrive as a definition on `POST /v1/agents`. | `--operator-name NAME`, `CRUX_OPERATOR_NAME` | the name the control token's caller is recorded under on work-services routes (see [Caller principals](#caller-principals)). Default `operator`. | | `--checkout-allow PREFIX,…`, `CRUX_CHECKOUT_ALLOWLIST` | repository URL prefixes `POST /v1/checkouts` may clone; unset means no checkout service ([design](design/crux-work-services.md)). | | `--checkout-dir PATH`, `CRUX_CHECKOUT_DIR` | where pinned checkouts live. Default `/checkouts`. | +| `--checkout-max-bytes N`, `CRUX_CHECKOUT_MAX_BYTES` | ceiling on a checkout request's `max_bytes`; asking for more is `400`, asking for nothing gets the ceiling. Default 5 GiB. | +| `CRUX_CHECKOUT_TOKEN` | HTTPS token for private repositories, passed to git via a credential helper and never logged ([design](design/crux-work-services.md)). | | `--lanes-config PATH`, `CRUX_LANES_CONFIG` | opt into [durable event/work lanes](crux-lanes.md) on this same server, backed by NATS JetStream. Lane project credentials are separate from agent-control credentials. | | `--runs-config PATH`, `CRUX_RUNS_CONFIG` | contained-run configuration file that supplies the sandbox backend for `POST /v1/runs`. Without it the server still serves saved run records under `/runs` (`GET /v1/runs/{id}`), and `POST /v1/runs` answers `501`; runs left in flight by an earlier process are marked unfinished at startup ([design](design/crux-work-services.md)). | | `--hive-callback ADDR`, `CRUX_HIVE_SOCKET` (+ `CRUX_HIVE_TOKEN`) | dial hive's callback endpoint (`crux/api/callback`) for the capabilities hive owns — scoped GitHub tokens, PR creation, Linear credentials, text/canary scanners, conditions — and feed the runtime's seams from it instead of leaving them nil. Health reports it under `hive_callback`; an unreachable endpoint raises the `hive_callback_unavailable` condition. (#14246) When the runtime is a manager it also polls hive's host policy from the same endpoint; see [Host policy from hive](#host-policy-from-hive-14138-stage-4). | diff --git a/src/docs/dashboard.md b/src/docs/dashboard.md index cab60f6e27..3d2ede2497 100644 --- a/src/docs/dashboard.md +++ b/src/docs/dashboard.md @@ -1094,6 +1094,44 @@ The **Hive activity monitor** section (sidebar, Dashboard group; expanded by def The endpoint returns `stages` (the stage table with `short`, `branch_from`, configured dwell and `falls_to` — the lower same-kind stages a move to which is a regression per the stage engine, so the event line says "fell back to" only for those; 015 → 010 triage accepted, 085 → 080 decision made and 072 → 070 author resuming read "moved to"), `items` (one per open issue/PR represented by the status snapshot, including actionable and held items plus display-only non-actionable issues, drafts, and exempt PRs: `labels`, `created_at`, `updated_at`, `bucket`, `bucket_reason`, stage, `stage_since`, humanised `reason`/`caption`, `actor`, `modifiers`, `author_kind` + `author_kind_source` (`label`, `inferred`, or `registry` — the author has a contributor-hub profile on this hive, so their clanker pushed it; the row icon, tooltip and claimant all read this one value), `lane`, `tier`, `linked_pr`, `linked_prs` (number, title, url, author, author kind, stage, `stage_since`, `caption` and `modifiers` of each open covering PR — enough to draw the nested sub-row without a second lookup), `nested_under` (on a PR: the issue it is listed under), nudge info and the last eight `history` hops from the stage store) and `author_kind_labels`. It answers `{"status":"initializing"}` until the first scan. +### Maintainer notes + +Each row (and each PR sub-row under an issue) carries a small **🗒** button +beside its decision controls — the item's **maintainer notes**: short notes +one maintainer leaves for the others ("waiting on legal", "don't merge before +the v5 cut", "asked the author about the test on Discord"), the way the +decision badge records what was decided. A count rides on the button once +the item has any (`🗒 2`), the row's hover tooltip repeats it, and clicking +opens an inline expander listing every note (author avatar and login, +relative time, text) over a one-line composer — **Add note**, or +⌘/Ctrl+Enter. The author is always the dashboard session's GitHub login. + +What they are, and are not: + +- **Private to the hive's maintainers.** Notes are stored on the spoke in + the append-only `/data/maintainer-notes.jsonl` next to the decision + ledgers and are **never written to GitHub** — no comment, no label, no + mention. Anyone signed in to the dashboard sees them; adding one takes + write on the repository (the same check as the hold chip and the decision + buttons); a note is deleted by its author or an owner, and a delete is a + tombstone record, not a rewrite. +- **Shared live.** Every add or delete is broadcast on the dashboard event + stream as a `maintainer-notes` frame, so the other maintainers' rows + update without a reload. A draft a maintainer is typing survives the + monitor's own refreshes. +- **Read by the agents.** The scheduler types an item's live notes into the + agent's kick under a `# Maintainer notes` heading (newest first, capped at + 1 KB with "… and N more note(s) on the dashboard"), so what a maintainer + wrote on the row reaches whoever picks the item up — the same seam that + injects decisions and in-flight context ([Kick size and the list + caps](operator-reference/sweeps-and-operations.md#kick-size-and-the-list-caps)). + Write them as instructions to a colleague, not as GitHub prose. + +API: `GET /api/notes?repo=&number=`, `POST /api/notes` `{repo, number, +text}` (≤ 2000 characters), `DELETE /api/notes/{id}` — see the +[REST reference](api-reference/packs-and-acmm.md). Audit log actions: +`maintainer_note_add`, `maintainer_note_delete`. + ## Code activity reader The code activity reader is a kiosk view at `?kiosk=1&view=reader` that shows diff --git a/src/docs/design/crux-work-services.md b/src/docs/design/crux-work-services.md index 6aab328614..366a073f0e 100644 --- a/src/docs/design/crux-work-services.md +++ b/src/docs/design/crux-work-services.md @@ -66,6 +66,8 @@ status. |---|---| | `--checkout-allow PREFIX,…`, `CRUX_CHECKOUT_ALLOWLIST` | repository URL prefixes `POST /v1/checkouts` may clone. **Unset means no checkout service.** | | `--checkout-dir PATH`, `CRUX_CHECKOUT_DIR` | where checkouts live. Default `/checkouts`. | +| `--checkout-max-bytes N`, `CRUX_CHECKOUT_MAX_BYTES` | server ceiling on `max_bytes`: a request asking for more is 400 `bad_request`; a request naming none gets the ceiling. Default 5 GiB. | +| `CRUX_CHECKOUT_TOKEN` (env only) | HTTPS token for private repositories, handed to git through a credential helper. Never on a command line, in a record or in an error. | ## Semantics @@ -80,9 +82,21 @@ and each request URL must be `https://` or `file://`, have a host (or a path, for `file`), and carry no userinfo, query or fragment; the request URL must start with an entry. An empty allowlist refuses everything. This is the shape of hive's `nousdeps` trust rules, ported without the -per-package specifics. Private repositories therefore work only through -whatever the server's own git credential helper provides; the API never -accepts a credential. +per-package specifics. The API never accepts a credential. + +**Private repositories.** The server may carry one HTTPS token, +`CRUX_CHECKOUT_TOKEN` (`checkout.Config.Token`). It reaches git through a +credential helper the service configures per invocation (`-c +credential.helper=` to drop any host-wide helper, then an inline helper +that answers `username=x-access-token` and the password from the child's +`CRUX_CHECKOUT_GIT_TOKEN` environment), so the token is never an argument, +never in the remote URL and never in a record; git failure output is +passed through `logscrub` before it reaches an error. Every git child runs +with `GIT_TERMINAL_PROMPT=0`, so a missing or wrong token fails the clone +instead of hanging on a prompt. The helper answers only when a server +asks, so public and `file://` repositories are unaffected. One token per +server: scoping it per owner or minting it from hive's callback is left to +a later slice. **Ownership via S0.** `owner` is recorded on every checkout. The caller's [principal](../crux-serve.md#caller-principals) decides what it may name: @@ -109,7 +123,7 @@ is no pre-flight size query across the transports we allow. The cap is therefore *post-hoc*: the service clones (`--no-checkout`, plus `--single-branch` when `branches` is false), adds the worktree, then walks the regular files of the shared clone and the worktree and sums their -sizes. Over `max_bytes` (default 5 GiB) it removes the worktree and +sizes. Over `max_bytes` it removes the worktree and answers 413 `too_large` with both numbers; if the measurement itself fails it answers 501 `unsupported`. The bytes were already transferred and the shared clone is kept (a later request for the same repo reuses @@ -118,6 +132,15 @@ smaller but would also make the worktree need network at checkout time; that trade is not taken here and is deferred. The record stores both `max_bytes` and the measured `bytes`. +The server bounds what a request may ask for: `checkout.Config.MaxBytes` +(`--checkout-max-bytes`, `CRUX_CHECKOUT_MAX_BYTES`, default +`DefaultMaxBytes` = 5 GiB) is a ceiling. A request whose `max_bytes` +exceeds it is refused before any clone with 400 `bad_request` +(`checkout.ErrAboveCeiling`, which also matches `ErrBadRequest`), naming +both numbers; a request with no `max_bytes` gets the ceiling as its cap. +A caller therefore cannot opt out of the operator's bound by asking for +more. + **Bound on live worktrees.** `checkout.Config.MaxCheckouts` (default 64) is the `sandbox.WorktreeManager` cap, counted as `.git` entries under the runs directory. @@ -152,6 +175,25 @@ does: a run is owned by the principal that created it, and only the owner or the operator may read or cancel it. While a run is live its checkout cannot be deleted (409 `conflict`); once the run settles, it can. +**Kubernetes Job network (S2 follow-up).** The `job` backend takes +`job_network: none | host | default` in the runs config. The default is +`none`: before each Job the launcher creates a `NetworkPolicy` in the Job +namespace, named after the Job and selecting its pod by the +`hive.kubestellar.io/job=` label, with `policyTypes: [Ingress, +Egress]` and no rules — deny all, both ways — and deletes it when the +Job is deleted (success, timeout, failed Job create) or when the Job is +left behind for inspection. If the policy cannot be created the run is +refused rather than started open. `host` sets `hostNetwork: true` (with +`dnsPolicy: ClusterFirstWithHostNet`); `default` is the pod network with +nothing added. The backend claims the `none` capability when +`job_network` is `none` or the operator asserts `job_network_policy` +(their own policy already denies egress). As with any NetworkPolicy, the +isolation is only as real as the cluster's CNI: on a CNI that ignores +policies the Job still has network, and the capability claim is the +operator's to make honestly. `kubejob.Launcher` itself, shared with +hive's agent sandbox, keeps `default` when `Network` is empty; only the +contained-run backend defaults to `none`. + ## S3. Human gate A driver asks a person to decide something before it continues; the @@ -397,7 +439,10 @@ a run's signals live and die with the run dir. ## Deliberately not in S1 - TTL sweeper (recorded, not enforced). -- `--filter=blob:limit=` partial clones; the cap is post-hoc only. +- `--filter=blob:limit=` partial clones; the cap is post-hoc only (the + server ceiling bounds what may be asked, not what git transfers). +- Per-owner or callback-minted checkout tokens; one `CRUX_CHECKOUT_TOKEN` + per server. - A per-owner allowlist; one list per server. - `ssh://` and `http://` repositories; `git@` syntax. - Anything about the hivecommons/crux repository or the publish path: @@ -414,7 +459,9 @@ for runs are deferred and not scheduled. | Path | Role | |---|---| -| `src/crux/checkout/` | `Service`, `Config`, `Record`, typed sentinels (`ErrBadRequest`, `ErrForbidden`, `ErrNotFound`, `ErrInUse`, `ErrMismatch`, `ErrTooLarge`, `ErrUnsupported`, `ErrGit`); store and index | +| `src/crux/checkout/` | `Service`, `Config` (`MaxBytes` ceiling, `Token`), `Record`, typed sentinels (`ErrBadRequest`, `ErrAboveCeiling`, `ErrForbidden`, `ErrNotFound`, `ErrInUse`, `ErrMismatch`, `ErrTooLarge`, `ErrUnsupported`, `ErrGit`); store and index; credential-helper runner | +| `src/crux/kubejob/` | `Options.Network` (`NetworkNone`, `NetworkHost`, `NetworkDefault`), per-Job deny-all `NetworkPolicy` lifecycle | +| `src/crux/runs/config.go` | `job_network` (default `none` for the `job` backend), `job_network_policy` | | `src/crux/api/checkouts.go` | `PathCheckouts`, `CodeTooLarge`, `CodeUnsupported`, `CodeUpstream`, request/response types, `Client.{Create,List,Get,Delete}Checkout` | | `src/crux/serve/checkouts.go` | routes, ownership checks, error mapping; registered from `Server.Handler` after the runtime families and marked a work service for S0 | | `src/crux/serve/principal.go` | S0: `Principal`, `CallerFrom`, work-service gating | diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 2b57f739d5..941e315dab 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -69,6 +69,8 @@ The reference is organized into the sections below. Existing links to this page - [Scheduled-upgrade progress and history](operator-reference/sweeps-and-operations.md#scheduled-upgrade-progress-and-history) - [Governor cadence and budget](operator-reference/sweeps-and-operations.md#governor-cadence-and-budget) + +- [Maintainer notes](dashboard.md#maintainer-notes) — private per-item notes maintainers share on the Activity Monitor rows (`/data/maintainer-notes.jsonl`, never GitHub; injected into kicks) - [Kick size and the list caps](operator-reference/sweeps-and-operations.md#kick-size-and-the-list-caps) diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 266c91efb4..5bbf9e9502 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -896,6 +896,8 @@ level=INFO msg="knowledge: injected 3900 bytes from 7 entries (skipped 3 for cap `injected_bytes` / `entries` are the rendered `# Relevant Knowledge` block; `skipped_for_cap` counts relevant facts dropped whole because they did not fit `knowledge.primer.max_bytes` (`cap_bytes`); `agents_md_bytes` and `skills_bytes` are the repository `AGENTS.md` block and the requested-skills block that share the kick. A zero line (`primed=true`, 0 entries) means priming ran and found nothing relevant — the signal that the store lacks entries for that lane's work. The line is not emitted when knowledge is disabled or there was nothing to prime, so a hive without a knowledge store does not log a zero on every kick. Read it against `src/docs/knowledge-entries.md` when deciding whether a fact belongs in `AGENTS.md` (paid on every kick) or in a scoped entry (paid only when it matches). +**Maintainer notes in the kick.** When a maintainer has left [notes](../dashboard.md#maintainer-notes) on an item the kick lists, the scheduler appends one `# Maintainer notes` section — a `## owner/repo#N` block per noted item, newest note first, each capped at 1 KiB with "… and N more note(s) on the dashboard" when the rest did not fit. The notes come from the spoke's `/data/maintainer-notes.jsonl`, never from GitHub, and the section is omitted entirely when no listed item has any, so an unused feature costs no bytes. + ### What consumes tokens while agents are paused Pausing agents (including the navbar fleet breaker) does not take the Hive instance down: the dashboard, governor scans, GitHub polling, token scanners, repo-cost collectors, telemetry/heartbeats, and provider-headroom probes can keep running. Those components should not make model calls by themselves. Model usage is expected from agent sessions reached through governor/manual/CEL/resume kicks; those kick paths share the same pause and budget gates. Knowledge priming reads configured knowledge stores and attaches facts to kicks; it does not independently call the model while every agent is paused. Provider-budget probes are the exception by design: after a provider spend-limit rebuff, Hive may release one kick after `governor.provider_budget.probe_interval_s` to test recovery. diff --git a/src/internal/testutil/dashboard_import_allowlist.txt b/src/internal/testutil/dashboard_import_allowlist.txt index 5aa121a8bc..ad84e68b32 100644 --- a/src/internal/testutil/dashboard_import_allowlist.txt +++ b/src/internal/testutil/dashboard_import_allowlist.txt @@ -69,6 +69,7 @@ github.com/hivecommons/hive/pkg/hubbackup github.com/hivecommons/hive/pkg/inferencehealth github.com/hivecommons/hive/pkg/ioscan github.com/hivecommons/hive/pkg/knowledge +github.com/hivecommons/hive/pkg/maintainernotes github.com/hivecommons/hive/pkg/mention github.com/hivecommons/hive/pkg/mergelane github.com/hivecommons/hive/pkg/modelfamily diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 2b5ef0fbf0..63137f8b87 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -365,6 +365,11 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}", s.handleRepoItemDetail) s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/hold", s.recordOperatorAction(s.handleRepoItemHold)) s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decision", s.recordOperatorAction(s.handleRepoItemDecision)) + // Per-item maintainer notes shared across the hive's maintainers + // (api_maintainer_notes.go); never written to GitHub. + s.mux.HandleFunc("GET /api/notes", s.handleMaintainerNotesList) + s.mux.HandleFunc("POST /api/notes", s.handleMaintainerNotesAdd) + s.mux.HandleFunc("DELETE /api/notes/{id}", s.handleMaintainerNotesDelete) s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.recordOperatorAction(s.handleRepoItemDecideDelegated)) s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/issues/{number}/release", s.recordOperatorAction(s.handleRepoIssueRelease)) s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.handleRepoItemDecideDelegatedStatus) diff --git a/src/pkg/dashboard/api_maintainer_notes.go b/src/pkg/dashboard/api_maintainer_notes.go new file mode 100644 index 0000000000..525bcaaca7 --- /dev/null +++ b/src/pkg/dashboard/api_maintainer_notes.go @@ -0,0 +1,187 @@ +package dashboard + +import ( + "encoding/json" + "errors" + "net/http" + "strconv" + "strings" + + "github.com/hivecommons/hive/pkg/maintainernotes" +) + +// Per-item maintainer notes (owner request, multi-maintainer hives). A note +// is private context one maintainer leaves on an Activity-monitor row for +// the others — it is stored on the spoke (maintainernotes.DefaultPath), +// never posted to GitHub, shown to every signed-in maintainer of the hive +// and typed into agent kicks for the item (scheduler kick_maintainer_notes.go). +// +// - GET /api/notes?repo=owner/repo&number=N the item's live notes; +// without repo+number, every live note (the SPA's count badges) +// - POST /api/notes {repo, number, text} append; author is the +// session's GitHub login; needs write on the repo (canToggleRepoHold) +// - DELETE /api/notes/{id} the author, or a verified owner +// +// Each write broadcasts a `maintainer-notes` SSE frame naming the item so +// other maintainers' browsers refresh the row live. +const ( + maintainerNotesSSEEvent = "maintainer-notes" + maintainerNotesMaxBody = 16 << 10 + + auditMaintainerNoteAdd = "maintainer_note_add" + auditMaintainerNoteDelete = "maintainer_note_delete" +) + +type maintainerNoteRequest struct { + Repo string `json:"repo"` + Number int `json:"number"` + Text string `json:"text"` +} + +type maintainerNotesResponse struct { + OK bool `json:"ok"` + Notes []maintainernotes.Note `json:"notes"` +} + +type maintainerNoteResponse struct { + OK bool `json:"ok"` + Note maintainernotes.Note `json:"note"` +} + +// maintainerNotesSSEPayload is the data of a `maintainer-notes` frame. +type maintainerNotesSSEPayload struct { + Seq uint64 `json:"seq"` + Repo string `json:"repo"` + Number int `json:"number"` + Count int `json:"count"` + Action string `json:"action"` +} + +func (s *Server) maintainerNotesStore() *maintainernotes.Store { + if s != nil && s.maintainerNotes != nil { + return s.maintainerNotes + } + return maintainernotes.Default() +} + +// maintainerNotesSession is the signed-in identity a notes request acts +// as: the GitHub login, and whether the session carries the verified owner +// role (which may read and delete everything). +func maintainerNotesSession(r *http.Request) (login string, owner bool) { + owner = isOwnerRole(r.Header.Get("X-Hive-Role")) && r.Header.Get(ownerRoleVerifiedHeader) == "true" + return strings.TrimSpace(r.Header.Get("X-Hive-User")), owner +} + +func maintainerNotesSSEFrame(p maintainerNotesSSEPayload) string { + data, _ := json.Marshal(p) + return "event: " + maintainerNotesSSEEvent + "\ndata: " + string(data) + "\n\n" +} + +func (s *Server) broadcastMaintainerNotes(repo string, number int, action string) { + count := len(s.maintainerNotesStore().List(repo, number)) + s.broadcastFrame(maintainerNotesSSEFrame(maintainerNotesSSEPayload{ + Seq: s.maintainerNotesSeq.Add(1), Repo: repo, Number: number, Count: count, Action: action, + })) +} + +func (s *Server) handleMaintainerNotesList(w http.ResponseWriter, r *http.Request) { + login, owner := maintainerNotesSession(r) + if login == "" && !owner { + jsonError(w, "GitHub user session required", http.StatusUnauthorized) + return + } + store := s.maintainerNotesStore() + repoParam := strings.TrimSpace(r.URL.Query().Get("repo")) + numParam := strings.TrimSpace(r.URL.Query().Get("number")) + if repoParam == "" && numParam == "" { + notes := store.All() + if notes == nil { + notes = []maintainernotes.Note{} + } + jsonResponse(w, maintainerNotesResponse{OK: true, Notes: notes}) + return + } + repo, ok := maintainernotes.NormalizeRepo(repoParam) + number, err := strconv.Atoi(numParam) + if !ok || err != nil || number <= 0 { + jsonError(w, "repo must be owner/repo and number a positive integer", http.StatusBadRequest) + return + } + notes := store.List(repo, number) + if notes == nil { + notes = []maintainernotes.Note{} + } + jsonResponse(w, maintainerNotesResponse{OK: true, Notes: notes}) +} + +func (s *Server) handleMaintainerNotesAdd(w http.ResponseWriter, r *http.Request) { + login, _ := maintainerNotesSession(r) + if login == "" { + jsonError(w, "GitHub user session required to leave a note", http.StatusUnauthorized) + return + } + var body maintainerNoteRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maintainerNotesMaxBody)).Decode(&body); err != nil { + jsonError(w, "invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + repo, ok := maintainernotes.NormalizeRepo(body.Repo) + if !ok || body.Number <= 0 { + jsonError(w, "repo must be owner/repo and number a positive integer", http.StatusBadRequest) + return + } + text, err := maintainernotes.ValidateText(body.Text) + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + owner, name, _ := strings.Cut(repo, "/") + if allowed, status, msg := s.canToggleRepoHold(r, owner, name); !allowed { + jsonError(w, msg, status) + return + } + note, err := s.maintainerNotesStore().Add(repo, body.Number, login, text) + if err != nil { + jsonError(w, err.Error(), http.StatusInternalServerError) + return + } + if s.audit != nil { + s.audit.LogRecord(login, auditMaintainerNoteAdd, auditDetail("repo", repo, "number", strconv.Itoa(body.Number), "id", note.ID), "", repo, body.Number) + } + s.broadcastMaintainerNotes(repo, body.Number, "added") + jsonStatusResponse(w, http.StatusCreated, maintainerNoteResponse{OK: true, Note: note}) +} + +func (s *Server) handleMaintainerNotesDelete(w http.ResponseWriter, r *http.Request) { + login, owner := maintainerNotesSession(r) + if login == "" && !owner { + jsonError(w, "GitHub user session required", http.StatusUnauthorized) + return + } + id := strings.TrimSpace(r.PathValue("id")) + if id == "" { + jsonError(w, "note id required", http.StatusBadRequest) + return + } + note, err := s.maintainerNotesStore().Delete(id, login, owner) + switch { + case errors.Is(err, maintainernotes.ErrNotFound): + jsonError(w, "note not found", http.StatusNotFound) + return + case errors.Is(err, maintainernotes.ErrForbidden): + jsonError(w, "only the note's author or an owner may delete it", http.StatusForbidden) + return + case err != nil: + jsonError(w, err.Error(), http.StatusInternalServerError) + return + } + actor := login + if actor == "" { + actor = "owner" + } + if s.audit != nil { + s.audit.LogRecord(actor, auditMaintainerNoteDelete, auditDetail("repo", note.Repo, "number", strconv.Itoa(note.Number), "id", note.ID, "author", note.Author), "", note.Repo, note.Number) + } + s.broadcastMaintainerNotes(note.Repo, note.Number, "deleted") + jsonResponse(w, maintainerNoteResponse{OK: true, Note: note}) +} diff --git a/src/pkg/dashboard/api_maintainer_notes_test.go b/src/pkg/dashboard/api_maintainer_notes_test.go new file mode 100644 index 0000000000..e605ea8036 --- /dev/null +++ b/src/pkg/dashboard/api_maintainer_notes_test.go @@ -0,0 +1,167 @@ +package dashboard + +import ( + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/maintainernotes" +) + +func newMaintainerNotesServer(t *testing.T) (*Server, chan []byte) { + t.Helper() + ghSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/collaborators/writer/permission"): + _, _ = io.WriteString(w, `{"permission":"write"}`) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/collaborators/reader/permission"): + _, _ = io.WriteString(w, `{"permission":"read"}`) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(ghSrv.Close) + srv := newFullServer(t) + srv.deps.GHClient = github.NewClient("token", "testorg", []string{"testrepo"}, slog.Default(), ghSrv.URL) + srv.maintainerNotes = maintainernotes.New("") + frames := make(chan []byte, 16) + srv.sseMu.Lock() + srv.sseClients[frames] = struct{}{} + srv.sseMu.Unlock() + return srv, frames +} + +func maintainerNotesDo(srv *Server, method, target, user, body string, owner bool) *httptest.ResponseRecorder { + var rd io.Reader + if body != "" { + rd = strings.NewReader(body) + } + req := httptest.NewRequest(method, target, rd) + req.Header.Set("Content-Type", "application/json") + if user != "" { + req.Header.Set("X-Hive-User", user) + } + if owner { + req.Header.Set("X-Hive-Role", "owner") + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + w := httptest.NewRecorder() + srv.mux.ServeHTTP(w, req) + return w +} + +func TestMaintainerNotesAPIAuthAndValidation(t *testing.T) { + srv, _ := newMaintainerNotesServer(t) + const body = `{"repo":"testorg/testrepo","number":7,"text":"waiting on legal"}` + + if w := maintainerNotesDo(srv, http.MethodGet, "/api/notes?repo=testorg/testrepo&number=7", "", "", false); w.Code != http.StatusUnauthorized { + t.Fatalf("anonymous list: code=%d want 401: %s", w.Code, w.Body) + } + if w := maintainerNotesDo(srv, http.MethodPost, "/api/notes", "", body, false); w.Code != http.StatusUnauthorized { + t.Fatalf("anonymous add: code=%d want 401: %s", w.Code, w.Body) + } + if w := maintainerNotesDo(srv, http.MethodPost, "/api/notes", "reader", body, false); w.Code != http.StatusForbidden { + t.Fatalf("reader add: code=%d want 403: %s", w.Code, w.Body) + } + for name, bad := range map[string]string{ + "no slash": `{"repo":"testorg","number":7,"text":"x"}`, + "number 0": `{"repo":"testorg/testrepo","number":0,"text":"x"}`, + "empty": `{"repo":"testorg/testrepo","number":7,"text":" "}`, + "too long": `{"repo":"testorg/testrepo","number":7,"text":"` + strings.Repeat("a", maintainernotes.MaxTextLen+1) + `"}`, + "not json": `{`, + "bad query": "", + } { + var w *httptest.ResponseRecorder + if name == "bad query" { + w = maintainerNotesDo(srv, http.MethodGet, "/api/notes?repo=testorg&number=x", "writer", "", false) + } else { + w = maintainerNotesDo(srv, http.MethodPost, "/api/notes", "writer", bad, false) + } + if w.Code != http.StatusBadRequest { + t.Errorf("%s: code=%d want 400: %s", name, w.Code, w.Body) + } + } + if got := len(srv.maintainerNotes.All()); got != 0 { + t.Fatalf("rejected requests must store nothing, have %d", got) + } +} + +func TestMaintainerNotesAPIAddListDeleteBroadcast(t *testing.T) { + srv, frames := newMaintainerNotesServer(t) + + w := maintainerNotesDo(srv, http.MethodPost, "/api/notes", "writer", `{"repo":"TestOrg/TestRepo","number":7,"text":"owner wants this after v6"}`, false) + if w.Code != http.StatusCreated { + t.Fatalf("add: code=%d: %s", w.Code, w.Body) + } + var added maintainerNoteResponse + if err := json.Unmarshal(w.Body.Bytes(), &added); err != nil || !added.OK || added.Note.ID == "" { + t.Fatalf("add response: %v %s", err, w.Body) + } + if added.Note.Author != "writer" || added.Note.Repo != "testorg/testrepo" { + t.Fatalf("author/repo must come from the session and be normalised: %+v", added.Note) + } + + select { + case f := <-frames: + s := string(f) + if !strings.HasPrefix(s, "event: "+maintainerNotesSSEEvent+"\n") || !strings.Contains(s, `"repo":"testorg/testrepo"`) || !strings.Contains(s, `"number":7`) || !strings.Contains(s, `"count":1`) || !strings.Contains(s, `"action":"added"`) { + t.Fatalf("add frame = %q", s) + } + default: + t.Fatal("add must broadcast a maintainer-notes SSE frame") + } + + // Any signed-in maintainer reads the list, including the un-filtered + // one the badges use. + w = maintainerNotesDo(srv, http.MethodGet, "/api/notes?repo=testorg/testrepo&number=7", "reader", "", false) + var list maintainerNotesResponse + if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil || w.Code != http.StatusOK || len(list.Notes) != 1 || list.Notes[0].Text != "owner wants this after v6" { + t.Fatalf("list: code=%d err=%v body=%s", w.Code, err, w.Body) + } + w = maintainerNotesDo(srv, http.MethodGet, "/api/notes", "reader", "", false) + if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil || len(list.Notes) != 1 { + t.Fatalf("list all: err=%v body=%s", err, w.Body) + } + + // Delete: a different login is refused, the author (or an owner) succeeds. + if w := maintainerNotesDo(srv, http.MethodDelete, "/api/notes/"+added.Note.ID, "reader", "", false); w.Code != http.StatusForbidden { + t.Fatalf("other user delete: code=%d want 403: %s", w.Code, w.Body) + } + if w := maintainerNotesDo(srv, http.MethodDelete, "/api/notes/"+added.Note.ID, "writer", "", false); w.Code != http.StatusOK { + t.Fatalf("author delete: code=%d: %s", w.Code, w.Body) + } + select { + case f := <-frames: + if s := string(f); !strings.Contains(s, `"count":0`) || !strings.Contains(s, `"action":"deleted"`) { + t.Fatalf("delete frame = %q", s) + } + default: + t.Fatal("delete must broadcast a maintainer-notes SSE frame") + } + if w := maintainerNotesDo(srv, http.MethodDelete, "/api/notes/"+added.Note.ID, "", "", true); w.Code != http.StatusNotFound { + t.Fatalf("deleted twice: code=%d want 404: %s", w.Code, w.Body) + } + + // An owner-role session deletes another author's note. + w = maintainerNotesDo(srv, http.MethodPost, "/api/notes", "writer", `{"repo":"testorg/testrepo","number":8,"text":"second"}`, false) + if err := json.Unmarshal(w.Body.Bytes(), &added); err != nil || w.Code != http.StatusCreated { + t.Fatalf("add #2: code=%d err=%v", w.Code, err) + } + <-frames + if w := maintainerNotesDo(srv, http.MethodDelete, "/api/notes/"+added.Note.ID, "", "", true); w.Code != http.StatusOK { + t.Fatalf("owner delete: code=%d: %s", w.Code, w.Body) + } + actions := map[string]bool{} + for _, e := range srv.GetAudit().Recent(20) { + actions[e.Action] = true + } + if !actions[auditMaintainerNoteAdd] || !actions[auditMaintainerNoteDelete] { + t.Fatalf("audit must record add and delete, got %v", actions) + } +} diff --git a/src/pkg/dashboard/import_count_test.go b/src/pkg/dashboard/import_count_test.go index 2243a37ff2..5a67cebfda 100644 --- a/src/pkg/dashboard/import_count_test.go +++ b/src/pkg/dashboard/import_count_test.go @@ -63,8 +63,17 @@ func TestDashboardInternalImportCountRatchet(t *testing.T) { // surface the dashboard holds instead of *agent.Manager; pkg/agent stays // for the audit, trailer, provider-status and agent-mode helpers the // Runtime does not cover, and leaves when those move behind the boundary - // (hivecommons/hive#13536). - const maxDashboardInternalImports = 66 + // (hivecommons/hive#13536), plus pkg/hubactivity, the leaf wire contract + // (ceilings, urgency order, sanitiser) the spoke's heartbeat activity + // digest is built against from the dashboard's own stage tracker + // (hivecommons/hive#15963), plus pkg/webassets, the browser-asset + // packages (tracker view, kiosk call-to-action badge) shared verbatim by + // the spoke dashboard and the hub's public Fleet page so the two kiosk + // 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 entries, err := os.ReadDir(".") if err != nil { diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 7e165a06de..13ef8e152f 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -35,6 +35,7 @@ import ( "github.com/hivecommons/hive/pkg/hiveadvisor" spoke "github.com/hivecommons/hive/pkg/hub/spoke" "github.com/hivecommons/hive/pkg/knowledge" + "github.com/hivecommons/hive/pkg/maintainernotes" "github.com/hivecommons/hive/pkg/planning" "github.com/hivecommons/hive/pkg/review/autoscale" "github.com/hivecommons/hive/pkg/runtimeobs" @@ -243,6 +244,11 @@ type Server struct { repoRescanLast ReposRescanResult repoHoldPermMu sync.Mutex repoHoldPermCache map[string]repoHoldPermissionCacheEntry + // maintainerNotes is the per-item note store /api/notes serves; nil + // means the process-wide maintainernotes.Default(). + maintainerNotes *maintainernotes.Store + // maintainerNotesSeq numbers the `maintainer-notes` SSE frames. + maintainerNotesSeq atomic.Uint64 // delegatedJobs tracks "Let hive decide" jobs by repo#number // (api_repo_item_decide_delegated.go). delegatedJobs delegatedDecisionJobs diff --git a/src/pkg/dashboard/stage_tracker_maintainer_notes_test.go b/src/pkg/dashboard/stage_tracker_maintainer_notes_test.go new file mode 100644 index 0000000000..8d375f5e98 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_maintainer_notes_test.go @@ -0,0 +1,151 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// Maintainer notes on the Activity Monitor rows: the markup, CSS and SSE +// wiring are in the page, and the pure renderers behave (count badge only +// when ≥1, nothing for a signed-out visitor, Delete only for the author +// or an owner, composer only with write on the repo) — executed under node. +func TestStageTrackerMaintainerNotesWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `class="ham-notes-btn${n ? ' ham-notes-has' : ''}" data-action="hamNotesToggle" data-arg-types="e,t"`, + `${n}`, + `stageTrackerNotesButtonHtml(item, hamNotesCtx(item))`, + `stageTrackerNotesButtonHtml(pr, hamNotesCtx(pr))`, + `stageTrackerNotesPanelHtml(item, hamNotesCtx(item))`, + `stageTrackerNotesPanelHtml(pr, hamNotesCtx(pr))`, + `'), 'draft kept: ' + p); + +// Empty, open: the empty line with the ref. +_hamNotesOpen.add('hivecommons/hive#44'); +p = stageTrackerNotesPanelHtml({ repo: 'hivecommons/hive', number: 44 }, hamNotesCtx(item)); +assert.ok(p.includes('No maintainer notes on hivecommons/hive#44 yet.'), p); +`, + }, "\n") + runStageTrackerRowActionsScript(t, script) +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index d856a26544..8f1403b768 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -545,6 +545,26 @@ .ham-superseded-note { color: var(--muted); font-size: var(--fs-xs); flex: 0 0 auto; white-space: nowrap; } .ham-review-notes { color: var(--muted); font-size: var(--fs-xs); margin-top: var(--sp-1); } .ham-review-notes a { color: inherit; } + /* ---- Maintainer notes (CSS) — see the JS block of the same name. + Tokens only (ADR-0018); the phone tier below lifts the button and + the composer to --tap-target. */ + .ham-notes-btn { display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-2); border: var(--line-width) solid var(--line-strong); border-radius: var(--r-pill); background: var(--panel); color: var(--muted); font: inherit; font-size: var(--fs-xs); line-height: 1.5; cursor: pointer; } + .ham-notes-btn:hover, .ham-notes-btn:focus-visible, .ham-notes-btn[aria-expanded="true"] { color: var(--text); border-color: var(--accent); } + .ham-notes-btn.ham-notes-has { color: var(--text); } + .ham-notes-count { font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; } + .ham-notes { margin-top: var(--sp-2); padding: var(--sp-2) var(--sp-3); border: var(--line-width) solid var(--line); border-radius: var(--r-sm); background: var(--panel); font-size: var(--fs-xs); color: var(--text); } + .ham-notes-head, .ham-notes-empty { margin: 0 0 var(--sp-2); color: var(--muted); } + .ham-notes-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--sp-2); } + .ham-note-meta { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; } + .ham-note-avatar { width: var(--sp-4); height: var(--sp-4); border-radius: var(--r-pill); flex: 0 0 auto; } + .ham-note-author { font-weight: var(--fw-semibold); } + .ham-note-when { color: var(--muted); } + .ham-note-del { margin-left: auto; padding: 0 var(--sp-2); border: 0; border-radius: var(--r-sm); background: transparent; color: var(--muted); font: inherit; font-size: var(--fs-xs); cursor: pointer; } + .ham-note-del:hover, .ham-note-del:focus-visible { color: var(--red); background: var(--panel-strong); } + .ham-note-text { margin-top: var(--sp-1); white-space: pre-wrap; overflow-wrap: anywhere; } + .ham-notes-add { display: flex; align-items: flex-start; gap: var(--sp-2); margin-top: var(--sp-2); } + .ham-notes-input { flex: 1 1 auto; min-width: 0; resize: vertical; padding: var(--sp-1) var(--sp-2); border: var(--line-width) solid var(--line-strong); border-radius: var(--r-sm); background: var(--bg); color: var(--text); font: inherit; font-size: var(--fs-xs); } + .ham-notes-submit { flex: 0 0 auto; white-space: nowrap; } .ham-adopted-from { color: var(--muted); text-decoration: none; } /* The Let hive decide preview. One decision, readable in three seconds (operator feedback on the dialog, issue 15397): subject line, @@ -1164,9 +1184,16 @@ #activity-monitor-section .ham-toolbar .ham-chip, #activity-monitor-section .ham-labels .ham-chip, #activity-monitor-section .ham-selbar .ham-chip, #activity-monitor-section .ham-compact .ham-chip, #activity-monitor-section .ham-select, #activity-monitor-section .ham-input, #activity-monitor-section .ham-merged-count, #activity-monitor-section .ham-queue-chip, - #activity-monitor-section .ham-repo-chip, #activity-monitor-section .cue-event-ico, #activity-monitor-section .ham-lead-act, #activity-monitor-section .ham-badge-mod[data-action] { + #activity-monitor-section .ham-repo-chip, #activity-monitor-section .cue-event-ico, #activity-monitor-section .ham-lead-act, #activity-monitor-section .ham-badge-mod[data-action], + #activity-monitor-section .ham-notes-btn, #activity-monitor-section .ham-note-del, #activity-monitor-section .ham-notes-submit, #activity-monitor-section .ham-notes-input { box-sizing: border-box; min-height: var(--tap-target); min-width: var(--tap-target); } + #activity-monitor-section .ham-notes-btn { font-size: var(--tap-glyph); padding-top: var(--sp-2); padding-bottom: var(--sp-2); } + /* A card keeps its two-line head and its density (#17161): the 🗒 + shows on a phone only once the item has notes; the row's ⋯ menu + carries "Maintainer notes…" for the rest. */ + #activity-monitor-section .ham-notes-btn:not(.ham-notes-has) { display: none; } + #activity-monitor-section .ham-notes-add { flex-wrap: wrap; } #activity-monitor-section .ham-toolbar .ham-chip, #activity-monitor-section .ham-labels .ham-chip, #activity-monitor-section .ham-selbar .ham-chip, #activity-monitor-section .ham-repo-chip, #activity-monitor-section .ham-lead-act { padding-top: var(--sp-2); padding-bottom: var(--sp-2); } #activity-monitor-section .ham-select, #activity-monitor-section .ham-input { height: var(--tap-target); padding-top: 0; padding-bottom: 0; } #activity-monitor-section .ham-repo-filter { min-height: var(--tap-target); align-items: center; } diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 92f1037d29..7960aa07c7 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -95,6 +95,15 @@ noteSSEFrame(); if (_stageTrackerSig || _stageTrackerEtag) stageTrackerNudge(); }); + // Another maintainer added or deleted a note on an item: refetch + // that item's notes so the row's badge and open expander follow. + source.addEventListener('maintainer-notes', (e) => { + noteSSEFrame(); + try { + const p = JSON.parse(e.data || '{}'); + if (p && p.repo && p.number) hamNotesLoad(hamNotesKey(p.repo, p.number)); + } catch (err) { hamNotesLoad(); } + }); source.addEventListener('agent-status', (e) => { noteSSEFrame(); diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index e759808ca0..cb1fa958d3 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -448,6 +448,7 @@ return [ { id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }, { id: 'copy', label: 'Copy link', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }, + ...(ctx.user && typeof stageTrackerNotesMenuItem === 'function' ? [stageTrackerNotesMenuItem(item)] : []), ]; } const mods = Array.isArray(item.modifiers) ? item.modifiers : []; @@ -501,6 +502,7 @@ if (item.kind === 'issue' && String(item.state || '').toLowerCase() !== 'closed') out.push(Object.assign({ id: 'decide:close-issue', label: 'Close issue…', danger: true, hint: 'only this issue · completed' }, stageTrackerActionAllowed('decide:close-issue', ctx))); out.push({ id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link', sep: true }); out.push({ id: 'copy', label: 'Copy link', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }); + if (ctx.user && typeof stageTrackerNotesMenuItem === 'function') out.push(stageTrackerNotesMenuItem(item)); return out; } // Pure: the one action a row leads with, rendered inline on the row @@ -2649,6 +2651,12 @@ showToast(id === 'blocker:wait' ? 'Left as is — the row stays blocked until the permission is granted or a person acts.' : 'Not available: the hive has no identity that may push workflow files.', 'info'); return { toasts: [], pending: [] }; } + if (id === 'notes') { + // The phone tier's way in (the row's 🗒 only shows there once the + // item has notes): open the first selected row's expander. + if (items[0]) hamNotesOpenFor(items[0]); + return { toasts: [], pending: [] }; + } if (id === 'copy') { try { const links = items.map(stageTrackerCopyLink); diff --git a/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js b/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js index 95be137f82..dafebb3065 100644 --- a/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js +++ b/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js @@ -23,6 +23,7 @@ if (text === _stageTrackerSig) { stageTrackerTickClock(); return; } _stageTrackerSig = text; renderStageTracker(JSON.parse(text)); + if (!_hamNotesLoaded && typeof hamNotesLoad === 'function') hamNotesLoad(); dashboardSetInterval('stage-tracker-clock', stageTrackerTickClock, STAGE_TRACKER_CLOCK_MS); } catch (e) { // Network failure or an aborted body: keep the previous render but diff --git a/src/pkg/dashboard/static-src/js/tracker-filter.js b/src/pkg/dashboard/static-src/js/tracker-filter.js index 3615229738..eccd82b658 100644 --- a/src/pkg/dashboard/static-src/js/tracker-filter.js +++ b/src/pkg/dashboard/static-src/js/tracker-filter.js @@ -304,6 +304,181 @@ return rank(item && item.finisher); } + /* ---- Maintainer notes (JS) -------------------------------------------- + Private per-item notes maintainers leave for each other on a row + (/api/notes, api_maintainer_notes.go). They never reach GitHub; every + signed-in maintainer of the hive sees them, and the scheduler types + them into the item's agent kicks. The row's 🗒 button opens an inline + expander (list + one-line composer, ⌘/Ctrl+Enter adds). Pure helpers + (…Html, hamNotesIndex) run under node in + stage_tracker_maintainer_notes_test.go; the handlers below fetch. */ + const MAINTAINER_NOTES_MAX = 2000; + const MAINTAINER_NOTES_GLYPH = '🗒'; + const MAINTAINER_NOTES_AVATAR_PX = 32; + const MAINTAINER_NOTES_PRIVACY = 'Private to this hive\u2019s maintainers \u2014 not posted to GitHub; included in agent kicks for the item.'; + var _hamNotes = {}; + var _hamNotesOpen = new Set(); + var _hamNotesDraft = {}; + var _hamNotesLoaded = false; + var _hamNotesBusy = new Set(); + + function hamNotesKey(repo, number) { return String(repo || '').toLowerCase() + '#' + (Number(number) || 0); } + function hamNotesPanelId(key) { return 'ham-notes-' + String(key || '').replace(/[^a-z0-9]+/gi, '-'); } + // Pure: a /api/notes list → { 'owner/repo#n': [notes, oldest first] }. + function hamNotesIndex(notes) { + const out = {}; + for (const n of (Array.isArray(notes) ? notes : [])) { + if (!n || !n.repo || !(Number(n.number) > 0)) continue; + const k = hamNotesKey(n.repo, n.number); + (out[k] = out[k] || []).push(n); + } + for (const k of Object.keys(out)) out[k].sort((a, b) => (Date.parse(a.created_at || '') || 0) - (Date.parse(b.created_at || '') || 0)); + return out; + } + function hamNotesFor(item) { return (item && _hamNotes[hamNotesKey(item.repo, item.number)]) || []; } + function hamNotesCount(item) { return hamNotesFor(item).length; } + // The identity the notes UI draws for: signed in, login, write on the + // repo (null = not known yet), verified owner (may delete any note). + function hamNotesCtx(item) { + const base = typeof stageTrackerActionCtx === 'function' && item ? (stageTrackerActionCtx(item.repo) || {}) : {}; + const role = (typeof window !== 'undefined' && window._hiveRole) || 'read'; + const owner = typeof dashboardRoleAtLeast === 'function' && dashboardRoleAtLeast(role, 'owner'); + return { user: !!base.user, login: String(base.login || ''), canHold: base.canHold, owner: !!owner }; + } + // Pure: the row's notes affordance — nothing for a signed-out visitor + // (the notes are the maintainers' own), a count badge once the item + // has any. Sits with the row's decision controls. + // The phone card tier (hivecommons/hive#17161) renders the badge + // only once an item has notes, so an unnoted row keeps its two-line + // head; the ⋯ menu's "Maintainer notes…" is the way in there. + function hamNotesPhoneTier() { + return typeof matchMedia === 'function' && matchMedia('(max-width: 640px), ((pointer: coarse) and (max-width: 820px))').matches; + } + function stageTrackerNotesButtonHtml(item, ctx) { + if (!item || !ctx || !ctx.user) return ''; + const key = hamNotesKey(item.repo, item.number); + const n = hamNotesCount(item); + if (!n && hamNotesPhoneTier()) return ''; + const open = _hamNotesOpen.has(key); + const ref = stageTrackerRefOf(item); + const tip = (n ? n + ' maintainer note' + (n === 1 ? '' : 's') + '. ' : 'Leave a note for other maintainers. ') + MAINTAINER_NOTES_PRIVACY; + return ``; + } + // Pure: one note — avatar, login, relative time (ticked in place by + // stageTrackerCueAgeSync via .cue-event-age), Delete for its author + // or an owner, then the text (plain, pre-wrapped). + function stageTrackerNoteHtml(n, ctx) { + const login = String(n.author || ''); + const ms = Date.parse(n.created_at || '') || 0; + const mine = !!(ctx && ctx.login) && login.toLowerCase() === String(ctx.login).toLowerCase(); + const canDelete = mine || !!(ctx && ctx.owner); + return `
  • @${esc(login)}${canDelete ? `` : ''}
    ${esc(n.text || '')}
  • `; + } + // Pure: the open expander — the notes, then the composer (a signed-in + // user without write on the repo reads but cannot add). '' when the + // row's expander is closed. + function stageTrackerNotesPanelHtml(item, ctx) { + if (!item || !ctx || !ctx.user) return ''; + const key = hamNotesKey(item.repo, item.number); + if (!_hamNotesOpen.has(key)) return ''; + const notes = hamNotesFor(item); + const ref = stageTrackerRefOf(item); + const draft = _hamNotesDraft[key] || ''; + const list = notes.length + ? `
      ${notes.map(n => stageTrackerNoteHtml(n, ctx)).join('')}
    ` + : `

    No maintainer notes on ${esc(ref)} yet.

    `; + const add = ctx.canHold !== false + ? `
    ` + : `

    ${esc(STAGE_TRACKER_WHY_WRITE)} to add a note.

    `; + return `
    ${esc(MAINTAINER_NOTES_PRIVACY)}
    ${list}${add}
    `; + } + function hamNotesKeyOf(el) { const p = el && el.closest ? el.closest('[data-ham-notes-key]') : null; return p ? p.getAttribute('data-ham-notes-key') || '' : ''; } + function hamNotesSplitKey(key) { const i = String(key).lastIndexOf('#'); return { repo: String(key).slice(0, i), number: Number(String(key).slice(i + 1)) || 0 }; } + // Loads every live note once a maintainer is signed in (the count + // badges), or one item's after its `maintainer-notes` SSE frame. + async function hamNotesLoad(key) { + const role = window._hiveRole || 'read'; + if (!window._hiveUser && !(typeof dashboardRoleAtLeast === 'function' && dashboardRoleAtLeast(role, 'owner'))) return; + try { + const q = key ? hamNotesSplitKey(key) : null; + const r = await fetch(q ? '/api/notes?repo=' + encodeURIComponent(q.repo) + '&number=' + q.number : '/api/notes'); + if (!r.ok) return; + const d = await r.json(); + const idx = hamNotesIndex(d && d.notes); + if (q) { if (idx[key]) _hamNotes[key] = idx[key]; else delete _hamNotes[key]; } + else { _hamNotes = idx; _hamNotesLoaded = true; } + renderStageTracker(); + } catch (e) { /* keep the previous notes; the next poll or frame retries */ } + } + // Pure: the row menu's entry — the count in its label once there are notes. + function stageTrackerNotesMenuItem(item) { + const n = hamNotesCount(item); + return { id: 'notes', label: 'Maintainer notes' + (n ? ' (' + n + ')' : '') + '\u2026', hint: 'private', enabled: true, why: '' }; + } + function hamNotesOpenFor(item) { + const key = hamNotesKey(item.repo, item.number); + _hamNotesOpen.add(key); + renderStageTracker(); + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + if (ta) ta.focus(); else if (p && p.focus) { p.setAttribute('tabindex', '-1'); p.focus(); } + if (!_hamNotesLoaded) hamNotesLoad(); + } + function hamNotesToggle(e, btn) { + const key = btn && btn.getAttribute ? btn.getAttribute('data-ham-notes-key') : ''; + if (!key) return; + if (_hamNotesOpen.has(key)) _hamNotesOpen.delete(key); else _hamNotesOpen.add(key); + renderStageTracker(); + if (_hamNotesOpen.has(key)) { + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + if (ta) ta.focus(); + if (!_hamNotesLoaded) hamNotesLoad(); + } + } + function hamNotesDraft(e, ta) { const key = hamNotesKeyOf(ta); if (key && ta) _hamNotesDraft[key] = ta.value; } + function hamNotesKeydown(e, ta) { if (e && e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); hamNoteAdd(e, ta); } } + async function hamNoteAdd(e, el) { + const key = hamNotesKeyOf(el); + if (!key || _hamNotesBusy.has(key)) return; + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + const text = String(ta ? ta.value : (_hamNotesDraft[key] || '')).trim(); + if (!text) { if (ta) ta.focus(); return; } + if (text.length > MAINTAINER_NOTES_MAX) { showToast('A note is at most ' + MAINTAINER_NOTES_MAX + ' characters', 'error'); return; } + const q = hamNotesSplitKey(key); + _hamNotesBusy.add(key); + try { + const r = await fetch('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repo: q.repo, number: q.number, text }) }); + const d = await r.json().catch(() => ({})); + if (!r.ok) { showToast('Could not add the note: ' + (d && d.error ? d.error : 'HTTP ' + r.status), 'error'); return; } + delete _hamNotesDraft[key]; + if (d && d.note) { const cur = (_hamNotes[key] || []).filter(n => n.id !== d.note.id); cur.push(d.note); _hamNotes[key] = cur; } + renderStageTracker(); + const p2 = document.getElementById(hamNotesPanelId(key)); + const ta2 = p2 && p2.querySelector('.ham-notes-input'); + if (ta2) ta2.focus(); + } catch (err) { + showToast('Could not add the note: ' + (err && err.message ? err.message : 'network error'), 'error'); + } finally { _hamNotesBusy.delete(key); } + } + async function hamNoteDelete(e, btn) { + const li = btn && btn.closest ? btn.closest('.ham-note[data-ham-note-id]') : null; + const id = li ? li.getAttribute('data-ham-note-id') : ''; + const key = hamNotesKeyOf(btn); + if (!id || !key) return; + try { + const r = await fetch('/api/notes/' + encodeURIComponent(id), { method: 'DELETE' }); + const d = await r.json().catch(() => ({})); + if (!r.ok) { showToast('Could not delete the note: ' + (d && d.error ? d.error : 'HTTP ' + r.status), 'error'); return; } + _hamNotes[key] = (_hamNotes[key] || []).filter(n => n.id !== id); + if (!_hamNotes[key].length) delete _hamNotes[key]; + renderStageTracker(); + } catch (err) { + showToast('Could not delete the note: ' + (err && err.message ? err.message : 'network error'), 'error'); + } + } + // The canonical tracker count (owner): rows of the default view — every // item on its own row except a PR drawn on a listed issue's row. function stageTrackerRowCount(items, ctx) { diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index eb4b99af11..10147310b2 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -815,6 +815,7 @@ const src = stageTrackerRowSrcKey(r.html); const moved = stageTrackerRowHasMove(r.html); if (prev && !moved && stageTrackerRowSrcOf(prev) === src) { place(prev); out.kept++; continue; } + if (prev && !moved && typeof stageTrackerRowHoldsComposer === 'function' && stageTrackerRowHoldsComposer(prev)) { place(prev); out.kept++; continue; } if (prev && !moved && stageTrackerRowAnimating(prev)) { place(prev); out.deferred++; continue; } const node = stageTrackerRowNode(r.key, r.html); if (prev) { el.replaceChild(node, prev); out.replaced++; } @@ -823,6 +824,12 @@ } return out; } + // A maintainer typing a note in this row: the refresh keeps the node + // (and the draft, and the caret); the row catches up on the next one. + function stageTrackerRowHoldsComposer(node) { + const a = typeof document !== 'undefined' ? document.activeElement : null; + return !!(a && a.classList && a.classList.contains('ham-notes-input') && node && typeof node.contains === 'function' && node.contains(a)); + } // A refresh that found a row mid-move re-renders once the move has // settled, so the row's incidental changes still land. function stageTrackerScheduleSettle() { diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 4d4e9ff5e7..60343b6d0c 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -264,14 +264,14 @@ return `
    ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''}
    - ${stageTrackerHeadColsHtml([ref], '', stageTrackerActedBadgeHtml(pr, nowMs) + stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : ''))} + ${stageTrackerHeadColsHtml([ref], '', stageTrackerActedBadgeHtml(pr, nowMs) + stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : '') + (typeof stageTrackerNotesButtonHtml === 'function' ? stageTrackerNotesButtonHtml(pr, hamNotesCtx(pr)) : ''))}
    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(pr, stages, ctx) : ''}
      ${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}
    ${stageTrackerSinceHtml(pr, nowMs)}${typeof stageTrackerPillHtml === 'function' ? stageTrackerPillHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx) : ''}
    - ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''}${typeof stageTrackerNotesPanelHtml === 'function' ? stageTrackerNotesPanelHtml(pr, hamNotesCtx(pr)) : ''}
    `; } 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 dbb3088157..0f909c631d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -173,13 +173,13 @@ return `
    ${stageTrackerRowToolsHtml(item)}
    - ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerActedBadgeHtml(item, nowMs) + stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : ''), prTargetKey)} + ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerActedBadgeHtml(item, nowMs) + stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : '') + (typeof stageTrackerNotesButtonHtml === 'function' ? stageTrackerNotesButtonHtml(item, hamNotesCtx(item)) : ''), prTargetKey)}
    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''}
      ${stageTrackerStripItems(shown, stages, range, nowMs, 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) : ''}${subs} +
    ${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-row-strip.js b/src/pkg/dashboard/static-src/js/tracker-row-strip.js index ec27c08e49..766d694f4b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -811,6 +811,7 @@ if (mods.indexOf('hold') >= 0 && typeof stageTrackerHoldPill === 'function' && stageTrackerHoldPill(item)) lines.push(stageTrackerHoldPill(item)); if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); + if (typeof hamNotesCount === 'function') { const nn = hamNotesCount(item); if (nn) lines.push(nn + ' maintainer note' + (nn === 1 ? '' : 's') + ' (private to this hive)'); } // Say it once: a line the caption already said is not repeated (hivecommons/hive#15394). return lines.filter((l, i) => l && lines.indexOf(l) === i).join('\n'); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 537c9fc77d..df7ebc9bcd 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1890,6 +1890,26 @@ .ham-superseded-note { color: var(--muted); font-size: var(--fs-xs); flex: 0 0 auto; white-space: nowrap; } .ham-review-notes { color: var(--muted); font-size: var(--fs-xs); margin-top: var(--sp-1); } .ham-review-notes a { color: inherit; } + /* ---- Maintainer notes (CSS) — see the JS block of the same name. + Tokens only (ADR-0018); the phone tier below lifts the button and + the composer to --tap-target. */ + .ham-notes-btn { display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-2); border: var(--line-width) solid var(--line-strong); border-radius: var(--r-pill); background: var(--panel); color: var(--muted); font: inherit; font-size: var(--fs-xs); line-height: 1.5; cursor: pointer; } + .ham-notes-btn:hover, .ham-notes-btn:focus-visible, .ham-notes-btn[aria-expanded="true"] { color: var(--text); border-color: var(--accent); } + .ham-notes-btn.ham-notes-has { color: var(--text); } + .ham-notes-count { font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; } + .ham-notes { margin-top: var(--sp-2); padding: var(--sp-2) var(--sp-3); border: var(--line-width) solid var(--line); border-radius: var(--r-sm); background: var(--panel); font-size: var(--fs-xs); color: var(--text); } + .ham-notes-head, .ham-notes-empty { margin: 0 0 var(--sp-2); color: var(--muted); } + .ham-notes-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--sp-2); } + .ham-note-meta { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; } + .ham-note-avatar { width: var(--sp-4); height: var(--sp-4); border-radius: var(--r-pill); flex: 0 0 auto; } + .ham-note-author { font-weight: var(--fw-semibold); } + .ham-note-when { color: var(--muted); } + .ham-note-del { margin-left: auto; padding: 0 var(--sp-2); border: 0; border-radius: var(--r-sm); background: transparent; color: var(--muted); font: inherit; font-size: var(--fs-xs); cursor: pointer; } + .ham-note-del:hover, .ham-note-del:focus-visible { color: var(--red); background: var(--panel-strong); } + .ham-note-text { margin-top: var(--sp-1); white-space: pre-wrap; overflow-wrap: anywhere; } + .ham-notes-add { display: flex; align-items: flex-start; gap: var(--sp-2); margin-top: var(--sp-2); } + .ham-notes-input { flex: 1 1 auto; min-width: 0; resize: vertical; padding: var(--sp-1) var(--sp-2); border: var(--line-width) solid var(--line-strong); border-radius: var(--r-sm); background: var(--bg); color: var(--text); font: inherit; font-size: var(--fs-xs); } + .ham-notes-submit { flex: 0 0 auto; white-space: nowrap; } .ham-adopted-from { color: var(--muted); text-decoration: none; } /* The Let hive decide preview. One decision, readable in three seconds (operator feedback on the dialog, issue 15397): subject line, @@ -2509,9 +2529,16 @@ #activity-monitor-section .ham-toolbar .ham-chip, #activity-monitor-section .ham-labels .ham-chip, #activity-monitor-section .ham-selbar .ham-chip, #activity-monitor-section .ham-compact .ham-chip, #activity-monitor-section .ham-select, #activity-monitor-section .ham-input, #activity-monitor-section .ham-merged-count, #activity-monitor-section .ham-queue-chip, - #activity-monitor-section .ham-repo-chip, #activity-monitor-section .cue-event-ico, #activity-monitor-section .ham-lead-act, #activity-monitor-section .ham-badge-mod[data-action] { + #activity-monitor-section .ham-repo-chip, #activity-monitor-section .cue-event-ico, #activity-monitor-section .ham-lead-act, #activity-monitor-section .ham-badge-mod[data-action], + #activity-monitor-section .ham-notes-btn, #activity-monitor-section .ham-note-del, #activity-monitor-section .ham-notes-submit, #activity-monitor-section .ham-notes-input { box-sizing: border-box; min-height: var(--tap-target); min-width: var(--tap-target); } + #activity-monitor-section .ham-notes-btn { font-size: var(--tap-glyph); padding-top: var(--sp-2); padding-bottom: var(--sp-2); } + /* A card keeps its two-line head and its density (#17161): the 🗒 + shows on a phone only once the item has notes; the row's ⋯ menu + carries "Maintainer notes…" for the rest. */ + #activity-monitor-section .ham-notes-btn:not(.ham-notes-has) { display: none; } + #activity-monitor-section .ham-notes-add { flex-wrap: wrap; } #activity-monitor-section .ham-toolbar .ham-chip, #activity-monitor-section .ham-labels .ham-chip, #activity-monitor-section .ham-selbar .ham-chip, #activity-monitor-section .ham-repo-chip, #activity-monitor-section .ham-lead-act { padding-top: var(--sp-2); padding-bottom: var(--sp-2); } #activity-monitor-section .ham-select, #activity-monitor-section .ham-input { height: var(--tap-target); padding-top: 0; padding-bottom: 0; } #activity-monitor-section .ham-repo-filter { min-height: var(--tap-target); align-items: center; } @@ -19518,6 +19545,7 @@

    Where to get help

    if (mods.indexOf('hold') >= 0 && typeof stageTrackerHoldPill === 'function' && stageTrackerHoldPill(item)) lines.push(stageTrackerHoldPill(item)); if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); + if (typeof hamNotesCount === 'function') { const nn = hamNotesCount(item); if (nn) lines.push(nn + ' maintainer note' + (nn === 1 ? '' : 's') + ' (private to this hive)'); } // Say it once: a line the caption already said is not repeated (hivecommons/hive#15394). return lines.filter((l, i) => l && lines.indexOf(l) === i).join('\n'); } @@ -20417,14 +20445,14 @@

    Where to get help

    return `
    ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''}
    - ${stageTrackerHeadColsHtml([ref], '', stageTrackerActedBadgeHtml(pr, nowMs) + stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : ''))} + ${stageTrackerHeadColsHtml([ref], '', stageTrackerActedBadgeHtml(pr, nowMs) + stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : '') + (typeof stageTrackerNotesButtonHtml === 'function' ? stageTrackerNotesButtonHtml(pr, hamNotesCtx(pr)) : ''))}
    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(pr, stages, ctx) : ''}
      ${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}
    ${stageTrackerSinceHtml(pr, nowMs)}${typeof stageTrackerPillHtml === 'function' ? stageTrackerPillHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx) : ''}
    - ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''}${typeof stageTrackerNotesPanelHtml === 'function' ? stageTrackerNotesPanelHtml(pr, hamNotesCtx(pr)) : ''}
    `; } @@ -20735,13 +20763,13 @@

    Where to get help

    return `
    ${stageTrackerRowToolsHtml(item)}
    - ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerActedBadgeHtml(item, nowMs) + stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : ''), prTargetKey)} + ${stageTrackerHeadColsHtml(prRefs, leadHtml, stageTrackerActedBadgeHtml(item, nowMs) + stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : '') + (typeof stageTrackerNotesButtonHtml === 'function' ? stageTrackerNotesButtonHtml(item, hamNotesCtx(item)) : ''), prTargetKey)}
    ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''}
      ${stageTrackerStripItems(shown, stages, range, nowMs, 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) : ''}${subs} +
    ${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} `; } @@ -21573,6 +21601,7 @@

    Where to get help

    const src = stageTrackerRowSrcKey(r.html); const moved = stageTrackerRowHasMove(r.html); if (prev && !moved && stageTrackerRowSrcOf(prev) === src) { place(prev); out.kept++; continue; } + if (prev && !moved && typeof stageTrackerRowHoldsComposer === 'function' && stageTrackerRowHoldsComposer(prev)) { place(prev); out.kept++; continue; } if (prev && !moved && stageTrackerRowAnimating(prev)) { place(prev); out.deferred++; continue; } const node = stageTrackerRowNode(r.key, r.html); if (prev) { el.replaceChild(node, prev); out.replaced++; } @@ -21581,6 +21610,12 @@

    Where to get help

    } return out; } + // A maintainer typing a note in this row: the refresh keeps the node + // (and the draft, and the caret); the row catches up on the next one. + function stageTrackerRowHoldsComposer(node) { + const a = typeof document !== 'undefined' ? document.activeElement : null; + return !!(a && a.classList && a.classList.contains('ham-notes-input') && node && typeof node.contains === 'function' && node.contains(a)); + } // A refresh that found a row mid-move re-renders once the move has // settled, so the row's incidental changes still land. function stageTrackerScheduleSettle() { @@ -21893,6 +21928,181 @@

    Where to get help

    return rank(item && item.finisher); } + /* ---- Maintainer notes (JS) -------------------------------------------- + Private per-item notes maintainers leave for each other on a row + (/api/notes, api_maintainer_notes.go). They never reach GitHub; every + signed-in maintainer of the hive sees them, and the scheduler types + them into the item's agent kicks. The row's 🗒 button opens an inline + expander (list + one-line composer, ⌘/Ctrl+Enter adds). Pure helpers + (…Html, hamNotesIndex) run under node in + stage_tracker_maintainer_notes_test.go; the handlers below fetch. */ + const MAINTAINER_NOTES_MAX = 2000; + const MAINTAINER_NOTES_GLYPH = '🗒'; + const MAINTAINER_NOTES_AVATAR_PX = 32; + const MAINTAINER_NOTES_PRIVACY = 'Private to this hive\u2019s maintainers \u2014 not posted to GitHub; included in agent kicks for the item.'; + var _hamNotes = {}; + var _hamNotesOpen = new Set(); + var _hamNotesDraft = {}; + var _hamNotesLoaded = false; + var _hamNotesBusy = new Set(); + + function hamNotesKey(repo, number) { return String(repo || '').toLowerCase() + '#' + (Number(number) || 0); } + function hamNotesPanelId(key) { return 'ham-notes-' + String(key || '').replace(/[^a-z0-9]+/gi, '-'); } + // Pure: a /api/notes list → { 'owner/repo#n': [notes, oldest first] }. + function hamNotesIndex(notes) { + const out = {}; + for (const n of (Array.isArray(notes) ? notes : [])) { + if (!n || !n.repo || !(Number(n.number) > 0)) continue; + const k = hamNotesKey(n.repo, n.number); + (out[k] = out[k] || []).push(n); + } + for (const k of Object.keys(out)) out[k].sort((a, b) => (Date.parse(a.created_at || '') || 0) - (Date.parse(b.created_at || '') || 0)); + return out; + } + function hamNotesFor(item) { return (item && _hamNotes[hamNotesKey(item.repo, item.number)]) || []; } + function hamNotesCount(item) { return hamNotesFor(item).length; } + // The identity the notes UI draws for: signed in, login, write on the + // repo (null = not known yet), verified owner (may delete any note). + function hamNotesCtx(item) { + const base = typeof stageTrackerActionCtx === 'function' && item ? (stageTrackerActionCtx(item.repo) || {}) : {}; + const role = (typeof window !== 'undefined' && window._hiveRole) || 'read'; + const owner = typeof dashboardRoleAtLeast === 'function' && dashboardRoleAtLeast(role, 'owner'); + return { user: !!base.user, login: String(base.login || ''), canHold: base.canHold, owner: !!owner }; + } + // Pure: the row's notes affordance — nothing for a signed-out visitor + // (the notes are the maintainers' own), a count badge once the item + // has any. Sits with the row's decision controls. + // The phone card tier (hivecommons/hive#17161) renders the badge + // only once an item has notes, so an unnoted row keeps its two-line + // head; the ⋯ menu's "Maintainer notes…" is the way in there. + function hamNotesPhoneTier() { + return typeof matchMedia === 'function' && matchMedia('(max-width: 640px), ((pointer: coarse) and (max-width: 820px))').matches; + } + function stageTrackerNotesButtonHtml(item, ctx) { + if (!item || !ctx || !ctx.user) return ''; + const key = hamNotesKey(item.repo, item.number); + const n = hamNotesCount(item); + if (!n && hamNotesPhoneTier()) return ''; + const open = _hamNotesOpen.has(key); + const ref = stageTrackerRefOf(item); + const tip = (n ? n + ' maintainer note' + (n === 1 ? '' : 's') + '. ' : 'Leave a note for other maintainers. ') + MAINTAINER_NOTES_PRIVACY; + return ``; + } + // Pure: one note — avatar, login, relative time (ticked in place by + // stageTrackerCueAgeSync via .cue-event-age), Delete for its author + // or an owner, then the text (plain, pre-wrapped). + function stageTrackerNoteHtml(n, ctx) { + const login = String(n.author || ''); + const ms = Date.parse(n.created_at || '') || 0; + const mine = !!(ctx && ctx.login) && login.toLowerCase() === String(ctx.login).toLowerCase(); + const canDelete = mine || !!(ctx && ctx.owner); + return `
  • @${esc(login)}${canDelete ? `` : ''}
    ${esc(n.text || '')}
  • `; + } + // Pure: the open expander — the notes, then the composer (a signed-in + // user without write on the repo reads but cannot add). '' when the + // row's expander is closed. + function stageTrackerNotesPanelHtml(item, ctx) { + if (!item || !ctx || !ctx.user) return ''; + const key = hamNotesKey(item.repo, item.number); + if (!_hamNotesOpen.has(key)) return ''; + const notes = hamNotesFor(item); + const ref = stageTrackerRefOf(item); + const draft = _hamNotesDraft[key] || ''; + const list = notes.length + ? `
      ${notes.map(n => stageTrackerNoteHtml(n, ctx)).join('')}
    ` + : `

    No maintainer notes on ${esc(ref)} yet.

    `; + const add = ctx.canHold !== false + ? `
    ` + : `

    ${esc(STAGE_TRACKER_WHY_WRITE)} to add a note.

    `; + return `
    ${esc(MAINTAINER_NOTES_PRIVACY)}
    ${list}${add}
    `; + } + function hamNotesKeyOf(el) { const p = el && el.closest ? el.closest('[data-ham-notes-key]') : null; return p ? p.getAttribute('data-ham-notes-key') || '' : ''; } + function hamNotesSplitKey(key) { const i = String(key).lastIndexOf('#'); return { repo: String(key).slice(0, i), number: Number(String(key).slice(i + 1)) || 0 }; } + // Loads every live note once a maintainer is signed in (the count + // badges), or one item's after its `maintainer-notes` SSE frame. + async function hamNotesLoad(key) { + const role = window._hiveRole || 'read'; + if (!window._hiveUser && !(typeof dashboardRoleAtLeast === 'function' && dashboardRoleAtLeast(role, 'owner'))) return; + try { + const q = key ? hamNotesSplitKey(key) : null; + const r = await fetch(q ? '/api/notes?repo=' + encodeURIComponent(q.repo) + '&number=' + q.number : '/api/notes'); + if (!r.ok) return; + const d = await r.json(); + const idx = hamNotesIndex(d && d.notes); + if (q) { if (idx[key]) _hamNotes[key] = idx[key]; else delete _hamNotes[key]; } + else { _hamNotes = idx; _hamNotesLoaded = true; } + renderStageTracker(); + } catch (e) { /* keep the previous notes; the next poll or frame retries */ } + } + // Pure: the row menu's entry — the count in its label once there are notes. + function stageTrackerNotesMenuItem(item) { + const n = hamNotesCount(item); + return { id: 'notes', label: 'Maintainer notes' + (n ? ' (' + n + ')' : '') + '\u2026', hint: 'private', enabled: true, why: '' }; + } + function hamNotesOpenFor(item) { + const key = hamNotesKey(item.repo, item.number); + _hamNotesOpen.add(key); + renderStageTracker(); + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + if (ta) ta.focus(); else if (p && p.focus) { p.setAttribute('tabindex', '-1'); p.focus(); } + if (!_hamNotesLoaded) hamNotesLoad(); + } + function hamNotesToggle(e, btn) { + const key = btn && btn.getAttribute ? btn.getAttribute('data-ham-notes-key') : ''; + if (!key) return; + if (_hamNotesOpen.has(key)) _hamNotesOpen.delete(key); else _hamNotesOpen.add(key); + renderStageTracker(); + if (_hamNotesOpen.has(key)) { + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + if (ta) ta.focus(); + if (!_hamNotesLoaded) hamNotesLoad(); + } + } + function hamNotesDraft(e, ta) { const key = hamNotesKeyOf(ta); if (key && ta) _hamNotesDraft[key] = ta.value; } + function hamNotesKeydown(e, ta) { if (e && e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); hamNoteAdd(e, ta); } } + async function hamNoteAdd(e, el) { + const key = hamNotesKeyOf(el); + if (!key || _hamNotesBusy.has(key)) return; + const p = document.getElementById(hamNotesPanelId(key)); + const ta = p && p.querySelector('.ham-notes-input'); + const text = String(ta ? ta.value : (_hamNotesDraft[key] || '')).trim(); + if (!text) { if (ta) ta.focus(); return; } + if (text.length > MAINTAINER_NOTES_MAX) { showToast('A note is at most ' + MAINTAINER_NOTES_MAX + ' characters', 'error'); return; } + const q = hamNotesSplitKey(key); + _hamNotesBusy.add(key); + try { + const r = await fetch('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repo: q.repo, number: q.number, text }) }); + const d = await r.json().catch(() => ({})); + if (!r.ok) { showToast('Could not add the note: ' + (d && d.error ? d.error : 'HTTP ' + r.status), 'error'); return; } + delete _hamNotesDraft[key]; + if (d && d.note) { const cur = (_hamNotes[key] || []).filter(n => n.id !== d.note.id); cur.push(d.note); _hamNotes[key] = cur; } + renderStageTracker(); + const p2 = document.getElementById(hamNotesPanelId(key)); + const ta2 = p2 && p2.querySelector('.ham-notes-input'); + if (ta2) ta2.focus(); + } catch (err) { + showToast('Could not add the note: ' + (err && err.message ? err.message : 'network error'), 'error'); + } finally { _hamNotesBusy.delete(key); } + } + async function hamNoteDelete(e, btn) { + const li = btn && btn.closest ? btn.closest('.ham-note[data-ham-note-id]') : null; + const id = li ? li.getAttribute('data-ham-note-id') : ''; + const key = hamNotesKeyOf(btn); + if (!id || !key) return; + try { + const r = await fetch('/api/notes/' + encodeURIComponent(id), { method: 'DELETE' }); + const d = await r.json().catch(() => ({})); + if (!r.ok) { showToast('Could not delete the note: ' + (d && d.error ? d.error : 'HTTP ' + r.status), 'error'); return; } + _hamNotes[key] = (_hamNotes[key] || []).filter(n => n.id !== id); + if (!_hamNotes[key].length) delete _hamNotes[key]; + renderStageTracker(); + } catch (err) { + showToast('Could not delete the note: ' + (err && err.message ? err.message : 'network error'), 'error'); + } + } + // The canonical tracker count (owner): rows of the default view — every // item on its own row except a PR drawn on a listed issue's row. function stageTrackerRowCount(items, ctx) { @@ -23177,6 +23387,7 @@

    All labels

    if (text === _stageTrackerSig) { stageTrackerTickClock(); return; } _stageTrackerSig = text; renderStageTracker(JSON.parse(text)); + if (!_hamNotesLoaded && typeof hamNotesLoad === 'function') hamNotesLoad(); dashboardSetInterval('stage-tracker-clock', stageTrackerTickClock, STAGE_TRACKER_CLOCK_MS); } catch (e) { // Network failure or an aborted body: keep the previous render but @@ -23772,6 +23983,7 @@

    All labels

    return [ { id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }, { id: 'copy', label: 'Copy link', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }, + ...(ctx.user && typeof stageTrackerNotesMenuItem === 'function' ? [stageTrackerNotesMenuItem(item)] : []), ]; } const mods = Array.isArray(item.modifiers) ? item.modifiers : []; @@ -23825,6 +24037,7 @@

    All labels

    if (item.kind === 'issue' && String(item.state || '').toLowerCase() !== 'closed') out.push(Object.assign({ id: 'decide:close-issue', label: 'Close issue…', danger: true, hint: 'only this issue · completed' }, stageTrackerActionAllowed('decide:close-issue', ctx))); out.push({ id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link', sep: true }); out.push({ id: 'copy', label: 'Copy link', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }); + if (ctx.user && typeof stageTrackerNotesMenuItem === 'function') out.push(stageTrackerNotesMenuItem(item)); return out; } // Pure: the one action a row leads with, rendered inline on the row @@ -25973,6 +26186,12 @@

    All labels

    showToast(id === 'blocker:wait' ? 'Left as is — the row stays blocked until the permission is granted or a person acts.' : 'Not available: the hive has no identity that may push workflow files.', 'info'); return { toasts: [], pending: [] }; } + if (id === 'notes') { + // The phone tier's way in (the row's 🗒 only shows there once the + // item has notes): open the first selected row's expander. + if (items[0]) hamNotesOpenFor(items[0]); + return { toasts: [], pending: [] }; + } if (id === 'copy') { try { const links = items.map(stageTrackerCopyLink); @@ -56004,6 +56223,15 @@

    Configure LiteLLM

    noteSSEFrame(); if (_stageTrackerSig || _stageTrackerEtag) stageTrackerNudge(); }); + // Another maintainer added or deleted a note on an item: refetch + // that item's notes so the row's badge and open expander follow. + source.addEventListener('maintainer-notes', (e) => { + noteSSEFrame(); + try { + const p = JSON.parse(e.data || '{}'); + if (p && p.repo && p.number) hamNotesLoad(hamNotesKey(p.repo, p.number)); + } catch (err) { hamNotesLoad(); } + }); source.addEventListener('agent-status', (e) => { noteSSEFrame(); diff --git a/src/pkg/knowledge/climemory/main_test.go b/src/pkg/knowledge/climemory/main_test.go new file mode 100644 index 0000000000..5dcbf47fdc --- /dev/null +++ b/src/pkg/knowledge/climemory/main_test.go @@ -0,0 +1,24 @@ +package climemory + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +// TestMain points the temp dir at its symlink-free path. openMemoryStore +// refuses every symlinked ancestor, so on macOS, where $TMPDIR sits under +// /var -> /private/var, stores under a raw t.TempDir() could not be opened. +func TestMain(m *testing.M) { + resolved, err := filepath.EvalSymlinks(os.TempDir()) + if err != nil { + fmt.Fprintf(os.Stderr, "resolve temp dir: %v\n", err) + os.Exit(1) + } + if err := os.Setenv("TMPDIR", resolved); err != nil { + fmt.Fprintf(os.Stderr, "set TMPDIR: %v\n", err) + os.Exit(1) + } + os.Exit(m.Run()) +} diff --git a/src/pkg/knowledge/climemory/memstore.go b/src/pkg/knowledge/climemory/memstore.go index 044d953108..e378e7a244 100644 --- a/src/pkg/knowledge/climemory/memstore.go +++ b/src/pkg/knowledge/climemory/memstore.go @@ -6,6 +6,7 @@ import ( "io" "os" "path/filepath" + "strings" ) // errNotMemoryFile marks a listed path that is no longer a regular memory @@ -24,45 +25,112 @@ type memoryStore struct { } // openMemoryStore opens the store directory for path — path itself when it -// is a directory, its parent for a file store — and checks that the opened -// directory is the one Lstat sees at that path, so a store directory -// swapped for a symlink since memoryFiles listed it is refused rather than -// followed. +// is a directory, its parent for a file store. path is the store as the hive +// listed it with every symlink already resolved (the crux side resolves it +// with EvalSymlinks and keeps it only under the agent's own home), so no +// component of it may be a symlink by the time it is opened. The agent owns +// every directory from its home down and can swap any of them (`.claude`, +// `projects`, the project slug, the store itself) for a symlink after that +// listing; a path-based open would follow it to another agent's store or any +// hive-readable tree and drain, and with truncate empty, it under this +// agent's name. The directories are therefore opened one component at a time +// from the filesystem root, each refused when it is a symlink and checked to +// be the very inode Lstat saw, so the store root is reached without following +// a single symlink. func openMemoryStore(path string) (*memoryStore, error) { - base := path - lfi, err := os.Lstat(path) + if !filepath.IsAbs(path) { + return nil, fmt.Errorf("%w: %s is not an absolute path", errNotMemoryFile, path) + } + path = filepath.Clean(path) + dir, name := filepath.Split(path) + if name == "" { + return nil, fmt.Errorf("%w: %s is not a memory store", errNotMemoryFile, path) + } + parent, err := openDirNoFollow(filepath.Clean(dir)) if err != nil { return nil, err } - // memoryFiles never lists a symlinked store, so one here was swapped in - // after the listing; refuse it before the file-store fallback below - // would otherwise open its (real) parent directory and pass SameFile. - if lfi.Mode()&os.ModeSymlink != 0 { + lfi, err := parent.Lstat(name) + switch { + case err != nil: + parent.Close() + return nil, err + case lfi.IsDir(): + root, err := openChildDirNoFollow(parent, name, lfi) + parent.Close() + if err != nil { + return nil, err + } + return &memoryStore{root: root}, nil + case lfi.Mode()&os.ModeSymlink != 0: + // memoryFiles never lists a symlinked store, so one here was swapped + // in after the listing; refuse it rather than open its parent. + parent.Close() return nil, fmt.Errorf("%w: %s is a symlink", errNotMemoryFile, path) + default: + // A single-file store is opened through the directory holding it; + // open checks the file itself. + return &memoryStore{root: parent}, nil } - if !lfi.IsDir() { - base = filepath.Dir(path) - if lfi, err = os.Lstat(base); err != nil { +} + +// openDirNoFollow opens the absolute, clean directory dir by walking it from +// the filesystem root one component at a time with openChildDirNoFollow, so +// a symlink anywhere in dir is refused instead of followed. The returned +// root's Name is dir. +func openDirNoFollow(dir string) (*os.Root, error) { + vol := filepath.VolumeName(dir) + root, err := os.OpenRoot(vol + string(filepath.Separator)) + if err != nil { + return nil, err + } + rest := strings.Trim(dir[len(vol):], string(filepath.Separator)) + if rest == "" { + return root, nil + } + for _, name := range strings.Split(rest, string(filepath.Separator)) { + lfi, err := root.Lstat(name) + if err != nil { + root.Close() + return nil, err + } + next, err := openChildDirNoFollow(root, name, lfi) + root.Close() + if err != nil { return nil, err } + root = next + } + return root, nil +} + +// openChildDirNoFollow opens name, an entry directly inside parent that +// Lstat reported as lfi, as a root. A symlink or non-directory is refused, +// and the opened directory must be the very inode Lstat saw: os.Root follows +// a symlink that stays inside parent, so a directory swapped for one between +// the two calls would otherwise be opened at its target. +func openChildDirNoFollow(parent *os.Root, name string, lfi os.FileInfo) (*os.Root, error) { + path := filepath.Join(parent.Name(), name) + if lfi.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("%w: %s is a symlink", errNotMemoryFile, path) } if !lfi.IsDir() { - return nil, fmt.Errorf("%w: %s is not a directory", errNotMemoryFile, base) + return nil, fmt.Errorf("%w: %s is not a directory", errNotMemoryFile, path) } - root, err := os.OpenRoot(base) + child, err := parent.OpenRoot(name) if err != nil { return nil, err } - rfi, err := root.Stat(".") + cfi, err := child.Stat(".") if err != nil { - root.Close() + child.Close() return nil, err } - if !os.SameFile(lfi, rfi) { - root.Close() - return nil, fmt.Errorf("%w: %s changed while being opened", errNotMemoryFile, base) + if !os.SameFile(lfi, cfi) { + child.Close() + return nil, fmt.Errorf("%w: %s changed while being opened", errNotMemoryFile, path) } - return &memoryStore{root: root}, nil + return child, nil } func (s *memoryStore) Close() error { diff --git a/src/pkg/knowledge/climemory/memstore_test.go b/src/pkg/knowledge/climemory/memstore_test.go index 51e3efed6b..70f9dab4f5 100644 --- a/src/pkg/knowledge/climemory/memstore_test.go +++ b/src/pkg/knowledge/climemory/memstore_test.go @@ -97,6 +97,47 @@ func TestOpenMemoryStoreRefusesSwappedStoreDirectory(t *testing.T) { } } +func TestTruncateDrainedNeverFollowsSymlinkedAncestorOfStore(t *testing.T) { + // The hive lists ~/.claude/projects//memory with every symlink + // resolved, but the agent owns and can swap it for a symlink to + // another agent's project before the drain opens the store. The store + // path itself still Lstats as a real directory, so only refusing the + // symlinked ancestor keeps the other agent's store from being emptied. + base, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + otherProject := filepath.Join(base, "other", ".claude", "projects", "-data-agents-other") + victim := filepath.Join(otherProject, "memory", "MEMORY.md") + // No "- " bullets: zero facts count as fully stored, so a truncate that + // followed the symlink would empty it. + writeFile(t, victim, "# another agent's index\n") + slug := filepath.Join(base, "scanner", ".claude", "projects", "-data-agents-scanner") + store := filepath.Join(slug, "memory") + writeFile(t, filepath.Join(store, "MEMORY.md"), "# own index\n") + if err := os.Rename(slug, slug+".moved"); err != nil { + t.Fatal(err) + } + if err := os.Symlink(otherProject, slug); err != nil { + t.Skip("symlinks unavailable") + } + + d := &Drainer{Dir: t.TempDir(), Now: fixedNow} + truncated, kept, err := d.TruncateDrained([]Source{{CLI: CLIClaude, Path: store}}) + if len(truncated) != 0 { + t.Fatalf("truncated %v through a symlinked ancestor", truncated) + } + if len(kept) != 1 || kept[0] != filepath.Join(store, "MEMORY.md") { + t.Fatalf("kept = %v, want the listed file", kept) + } + if err == nil || !errors.Is(err, errNotMemoryFile) { + t.Fatalf("err = %v, want errNotMemoryFile", err) + } + if b, _ := os.ReadFile(victim); !strings.Contains(string(b), "another agent's index") { + t.Fatalf("store behind the symlinked ancestor was truncated: %q", b) + } +} + func TestMemoryStoreOpenKeepsSingleFileStoreWorking(t *testing.T) { home := t.TempDir() gemini := filepath.Join(home, "GEMINI.md") diff --git a/src/pkg/maintainernotes/store.go b/src/pkg/maintainernotes/store.go new file mode 100644 index 0000000000..8f45039527 --- /dev/null +++ b/src/pkg/maintainernotes/store.go @@ -0,0 +1,354 @@ +// Package maintainernotes is the private, per-item scratchpad maintainers +// share through the dashboard's Activity monitor. A note is a short piece of +// context one maintainer leaves on an issue or pull request for the others +// — "waiting on legal", "owner wants this after the v6 cut" — that never +// goes to GitHub. The store is an append-only JSONL file on the spoke's +// durable data dir, next to the review decisions it complements; a deletion +// is a tombstone line, so the history is always recoverable. +// +// The scheduler reads the live notes for the items a kick lists and types +// them into the kick under "# Maintainer notes" (KickSection), capped, so an +// agent working the item sees what its maintainers already know. +package maintainernotes + +import ( + "bufio" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" +) + +const ( + // MaxTextLen bounds a note's text in runes. + MaxTextLen = 2000 + // KickSectionCap bounds the bytes of notes a kick carries per item. + KickSectionCap = 1024 + // KickSectionHeader opens the kick block. + KickSectionHeader = "# Maintainer notes" + // DefaultDataDir is the spoke's durable data dir, where the review + // decisions already live (pkg/review.DefaultDispatchStateDir). + DefaultDataDir = "/data" + // FileName is the JSONL file under DefaultDataDir. + FileName = "maintainer-notes.jsonl" + + idBytes = 12 + fileMode = 0o644 + dirMode = 0o755 + maxListAll = 5000 + scanBufInitial = 64 << 10 + scanBufMax = 1 << 20 + elidedTrail = "…" + kickDateLayout = "2006-01-02" +) + +// DefaultPath is where Default persists. A var so tests can point it elsewhere. +var DefaultPath = filepath.Join(DefaultDataDir, FileName) + +var ( + // ErrEmpty is returned for a note with no text once trimmed. + ErrEmpty = errors.New("maintainer note: text is empty") + // ErrTooLong is returned for a note over MaxTextLen runes. + ErrTooLong = fmt.Errorf("maintainer note: text exceeds %d characters", MaxTextLen) + // ErrBadItem is returned for a repo not of the form owner/repo or a + // non-positive number. + ErrBadItem = errors.New("maintainer note: repo must be owner/repo and number positive") + // ErrNoAuthor is returned when the author login is empty. + ErrNoAuthor = errors.New("maintainer note: author is required") + // ErrNotFound is returned when no live note has the id. + ErrNotFound = errors.New("maintainer note: not found") + // ErrForbidden is returned when the actor may not delete the note. + ErrForbidden = errors.New("maintainer note: only its author or an owner may delete a note") +) + +// Note is one maintainer note on an issue or pull request. +type Note struct { + ID string `json:"id"` + Repo string `json:"repo"` + Number int `json:"number"` + // Author is the GitHub login of the dashboard session that wrote it. + Author string `json:"author"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` + // DeletedAt and DeletedBy are set on the tombstone line only; List + // never returns a deleted note. + DeletedAt *time.Time `json:"deleted_at,omitempty"` + DeletedBy string `json:"deleted_by,omitempty"` +} + +// Store is the file-backed note store. A zero path keeps it in memory only. +// It is safe for concurrent use. +type Store struct { + path string + + mu sync.Mutex + loaded bool + notes []Note // live notes in creation order + byID map[string]int // id -> index into notes + idGen func() string + now func() time.Time +} + +// New returns a store persisted at path ("" for memory only). +func New(path string) *Store { + return &Store{path: path, idGen: newID, now: time.Now} +} + +var ( + defaultOnce sync.Once + defaultStore *Store +) + +// Default is the process-wide store at DefaultPath, shared by the dashboard +// API and the scheduler's kick seam. +func Default() *Store { + defaultOnce.Do(func() { defaultStore = New(DefaultPath) }) + return defaultStore +} + +func newID() string { + b := make([]byte, idBytes) + if _, err := rand.Read(b); err != nil { + return fmt.Sprintf("%x", time.Now().UnixNano()) + } + return hex.EncodeToString(b) +} + +// NormalizeRepo lower-cases an owner/repo reference and reports whether it +// has the right shape. +func NormalizeRepo(repo string) (string, bool) { + repo = strings.ToLower(strings.TrimSpace(repo)) + owner, name, ok := strings.Cut(repo, "/") + if !ok || owner == "" || name == "" || strings.ContainsAny(name, "/ \t\n") || strings.ContainsAny(owner, " \t\n") { + return "", false + } + return repo, true +} + +// ValidateText trims text and checks its length. +func ValidateText(text string) (string, error) { + text = strings.TrimSpace(text) + if text == "" { + return "", ErrEmpty + } + if utf8.RuneCountInString(text) > MaxTextLen { + return "", ErrTooLong + } + return text, nil +} + +// Add appends a note by author on repo#number and returns it. +func (s *Store) Add(repo string, number int, author, text string) (Note, error) { + repo, ok := NormalizeRepo(repo) + if !ok || number <= 0 { + return Note{}, ErrBadItem + } + author = strings.TrimSpace(author) + if author == "" { + return Note{}, ErrNoAuthor + } + text, err := ValidateText(text) + if err != nil { + return Note{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + n := Note{ID: s.idGen(), Repo: repo, Number: number, Author: author, Text: text, CreatedAt: s.now().UTC()} + if err := s.appendLine(n); err != nil { + return Note{}, err + } + s.byID[n.ID] = len(s.notes) + s.notes = append(s.notes, n) + return n, nil +} + +// List returns the live notes on repo#number, oldest first. +func (s *Store) List(repo string, number int) []Note { + repo, ok := NormalizeRepo(repo) + if !ok { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + var out []Note + for _, n := range s.notes { + if n.Repo == repo && n.Number == number { + out = append(out, n) + } + } + return out +} + +// All returns every live note, oldest first, capped so a runaway file +// cannot flood the dashboard. +func (s *Store) All() []Note { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + out := make([]Note, len(s.notes)) + copy(out, s.notes) + if len(out) > maxListAll { + out = out[len(out)-maxListAll:] + } + return out +} + +// Get returns the live note with id. +func (s *Store) Get(id string) (Note, bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + i, ok := s.byID[id] + if !ok { + return Note{}, false + } + return s.notes[i], true +} + +// Delete tombstones the note with id. actor must be its author unless +// admin is set. The deleted note is returned so a caller can say which +// item changed. +func (s *Store) Delete(id, actor string, admin bool) (Note, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + i, ok := s.byID[id] + if !ok { + return Note{}, ErrNotFound + } + n := s.notes[i] + if !admin && !strings.EqualFold(strings.TrimSpace(actor), n.Author) { + return Note{}, ErrForbidden + } + at := s.now().UTC() + tomb := Note{ID: n.ID, Repo: n.Repo, Number: n.Number, Author: n.Author, CreatedAt: n.CreatedAt, DeletedAt: &at, DeletedBy: strings.TrimSpace(actor)} + if err := s.appendLine(tomb); err != nil { + return Note{}, err + } + s.notes = append(s.notes[:i], s.notes[i+1:]...) + s.reindex() + return n, nil +} + +func (s *Store) reindex() { + s.byID = make(map[string]int, len(s.notes)) + for i, n := range s.notes { + s.byID[n.ID] = i + } +} + +// load replays the JSONL file once: a line with deleted_at removes the +// note it names; anything unparseable is skipped. +func (s *Store) load() { + if s.loaded { + return + } + s.loaded = true + s.byID = make(map[string]int) + if s.path == "" { + return + } + f, err := os.Open(s.path) + if err != nil { + return + } + defer f.Close() + sc := bufio.NewScanner(f) + sc.Buffer(make([]byte, 0, scanBufInitial), scanBufMax) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" { + continue + } + var n Note + if json.Unmarshal([]byte(line), &n) != nil || n.ID == "" { + continue + } + if n.DeletedAt != nil { + if i, ok := s.byID[n.ID]; ok { + s.notes = append(s.notes[:i], s.notes[i+1:]...) + s.reindex() + } + continue + } + if _, dup := s.byID[n.ID]; dup { + continue + } + s.byID[n.ID] = len(s.notes) + s.notes = append(s.notes, n) + } + sort.SliceStable(s.notes, func(i, j int) bool { return s.notes[i].CreatedAt.Before(s.notes[j].CreatedAt) }) + s.reindex() +} + +func (s *Store) appendLine(n Note) error { + if s.path == "" { + return nil + } + if err := os.MkdirAll(filepath.Dir(s.path), dirMode); err != nil { + return err + } + f, err := os.OpenFile(s.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, fileMode) + if err != nil { + return err + } + defer f.Close() + data, err := json.Marshal(n) + if err != nil { + return err + } + _, err = f.Write(append(data, '\n')) + return err +} + +// KickSection renders notes for a kick under KickSectionHeader, newest +// first, within capBytes (KickSectionCap when <= 0). A note that would +// cross the cap is cut with an ellipsis; later notes are counted in a +// closing "… and N more" line. Empty for no notes. +func KickSection(notes []Note, capBytes int) string { + if len(notes) == 0 { + return "" + } + if capBytes <= 0 { + capBytes = KickSectionCap + } + ordered := make([]Note, len(notes)) + copy(ordered, notes) + sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].CreatedAt.After(ordered[j].CreatedAt) }) + var b strings.Builder + b.WriteString(KickSectionHeader + "\n") + b.WriteString("Private context other maintainers left on this item (not on GitHub; do not quote it in comments):\n") + used := 0 + shown := 0 + for _, n := range ordered { + line := fmt.Sprintf("- @%s (%s): %s", n.Author, n.CreatedAt.UTC().Format(kickDateLayout), strings.ReplaceAll(strings.TrimSpace(n.Text), "\n", " ")) + room := capBytes - used + if room <= len(elidedTrail)+1 { + break + } + if len(line) > room { + cut := room - len(elidedTrail) - 1 + for cut > 0 && !utf8.RuneStart(line[cut]) { + cut-- + } + line = line[:cut] + elidedTrail + } + b.WriteString(line + "\n") + used += len(line) + 1 + shown++ + } + if rest := len(ordered) - shown; rest > 0 { + fmt.Fprintf(&b, "… and %d more note(s) on the dashboard.\n", rest) + } + return b.String() +} diff --git a/src/pkg/maintainernotes/store_test.go b/src/pkg/maintainernotes/store_test.go new file mode 100644 index 0000000000..82bee98b8f --- /dev/null +++ b/src/pkg/maintainernotes/store_test.go @@ -0,0 +1,265 @@ +package maintainernotes + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func fixedClock(start time.Time) func() time.Time { + t := start + return func() time.Time { + t = t.Add(time.Minute) + return t + } +} + +func TestStoreAppendListDeletePersists(t *testing.T) { + path := filepath.Join(t.TempDir(), "notes", "maintainer-notes.jsonl") + s := New(path) + s.now = fixedClock(time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)) + + a, err := s.Add("HiveCommons/Hive", 42, "alice", " waiting on legal ") + if err != nil { + t.Fatalf("add: %v", err) + } + if a.Repo != "hivecommons/hive" || a.Text != "waiting on legal" || a.ID == "" { + t.Fatalf("add normalised badly: %+v", a) + } + b, err := s.Add("hivecommons/hive", 42, "bob", "owner wants this after v6") + if err != nil { + t.Fatalf("add: %v", err) + } + if _, err := s.Add("hivecommons/hive", 7, "alice", "other item"); err != nil { + t.Fatalf("add: %v", err) + } + + got := s.List("hivecommons/hive", 42) + if len(got) != 2 || got[0].ID != a.ID || got[1].ID != b.ID { + t.Fatalf("list = %+v, want [a b]", got) + } + if all := s.All(); len(all) != 3 { + t.Fatalf("all = %d, want 3", len(all)) + } + + // Author check: bob may not delete alice's note; alice may; an owner + // may delete anyone's. + if _, err := s.Delete(a.ID, "bob", false); !errors.Is(err, ErrForbidden) { + t.Fatalf("bob deleting alice's note: err=%v, want ErrForbidden", err) + } + if _, err := s.Delete(a.ID, "Alice", false); err != nil { + t.Fatalf("alice deleting own note: %v", err) + } + if _, err := s.Delete(b.ID, "owner", true); err != nil { + t.Fatalf("owner deleting bob's note: %v", err) + } + if _, err := s.Delete(b.ID, "owner", true); !errors.Is(err, ErrNotFound) { + t.Fatalf("second delete: err=%v, want ErrNotFound", err) + } + if got := s.List("hivecommons/hive", 42); len(got) != 0 { + t.Fatalf("after deletes list = %+v, want empty", got) + } + + // Replay from disk: the tombstones hide both deleted notes, the third + // survives. + re := New(path) + if got := re.List("hivecommons/hive", 42); len(got) != 0 { + t.Fatalf("replayed list = %+v, want empty", got) + } + if got := re.List("hivecommons/hive", 7); len(got) != 1 || got[0].Text != "other item" { + t.Fatalf("replayed #7 = %+v", got) + } +} + +func TestStoreValidation(t *testing.T) { + s := New("") + cases := []struct { + repo string + number int + author string + text string + want error + }{ + {"hivecommons", 1, "a", "x", ErrBadItem}, + {"hivecommons/hive", 0, "a", "x", ErrBadItem}, + {"hivecommons/hive", 1, "", "x", ErrNoAuthor}, + {"hivecommons/hive", 1, "a", " ", ErrEmpty}, + {"hivecommons/hive", 1, "a", strings.Repeat("é", MaxTextLen+1), ErrTooLong}, + } + for _, c := range cases { + if _, err := s.Add(c.repo, c.number, c.author, c.text); !errors.Is(err, c.want) { + t.Errorf("Add(%q,%d,%q,len %d): err=%v want %v", c.repo, c.number, c.author, len(c.text), err, c.want) + } + } + if _, err := s.Add("hivecommons/hive", 1, "a", strings.Repeat("é", MaxTextLen)); err != nil { + t.Errorf("exactly MaxTextLen runes must be accepted: %v", err) + } +} + +func TestKickSectionCap(t *testing.T) { + base := time.Date(2026, 11, 8, 0, 0, 0, 0, time.UTC) + var notes []Note + for i := 0; i < 6; i++ { + notes = append(notes, Note{Author: "m" + string(rune('a'+i)), Text: strings.Repeat("x", 300), CreatedAt: base.Add(time.Duration(i) * time.Hour)}) + } + out := KickSection(notes, KickSectionCap) + if !strings.HasPrefix(out, KickSectionHeader+"\n") { + t.Fatalf("section must open with %q:\n%s", KickSectionHeader, out) + } + // Newest first. + if !strings.Contains(strings.SplitN(out, "\n", 3)[2], "- @mf (2026-11-08)") { + t.Fatalf("newest note must lead:\n%s", out) + } + body := out[strings.Index(out, "- @"):] + if i := strings.Index(body, "… and "); i >= 0 { + body = body[:i] + } + if len(body) > KickSectionCap { + t.Fatalf("notes body %d bytes exceeds cap %d", len(body), KickSectionCap) + } + if !strings.Contains(out, "more note(s) on the dashboard") { + t.Fatalf("overflow must be counted:\n%s", out) + } + if KickSection(nil, 0) != "" { + t.Fatal("no notes must render nothing") + } +} + +func TestStoreGetDefaultAndReplayEdgeCases(t *testing.T) { + path := filepath.Join(t.TempDir(), "maintainer-notes.jsonl") + at := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + // A file as it may be left after crashes and hand edits: a blank line, + // garbage, a note without an id, a duplicate append, a tombstone for a + // note nobody has seen, and notes out of order. + lines := []string{ + "", + "not json", + `{"repo":"acme/widget","number":1,"author":"x","text":"no id","created_at":"2026-11-08T12:00:00Z"}`, + `{"id":"n2","repo":"acme/widget","number":1,"author":"bob","text":"second","created_at":"2026-11-08T13:00:00Z"}`, + `{"id":"n1","repo":"acme/widget","number":1,"author":"alice","text":"first","created_at":"2026-11-08T12:00:00Z"}`, + `{"id":"n1","repo":"acme/widget","number":1,"author":"alice","text":"dup","created_at":"2026-11-08T12:00:00Z"}`, + `{"id":"ghost","repo":"acme/widget","number":1,"author":"a","deleted_at":"2026-11-08T12:00:00Z"}`, + } + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + s := New(path) + s.now = fixedClock(at) + got := s.List("acme/widget", 1) + if len(got) != 2 || got[0].ID != "n1" || got[0].Text != "first" || got[1].ID != "n2" { + t.Fatalf("replayed list = %+v, want [n1 first, n2]", got) + } + if n, ok := s.Get("n2"); !ok || n.Author != "bob" { + t.Fatalf("Get(n2) = %+v, %v", n, ok) + } + if _, ok := s.Get("ghost"); ok { + t.Fatal("a tombstoned-before-seen id must not resolve") + } + if s.List("not-a-repo", 1) != nil { + t.Fatal("a malformed repo lists nothing") + } + if _, err := s.Delete("missing", "alice", true); !errors.Is(err, ErrNotFound) { + t.Fatalf("delete missing: %v", err) + } + // The tombstone names who deleted and keeps the note's identity. + d, err := s.Delete("n2", " BOB ", false) + if err != nil || d.ID != "n2" { + t.Fatalf("author delete (case/space-insensitive): %+v, %v", d, err) + } + data, _ := os.ReadFile(path) + if !strings.Contains(string(data), `"deleted_by":"BOB"`) || !strings.Contains(string(data), `"deleted_at":"2026-11-08T12:00:00Z"`) { + t.Fatalf("tombstone not appended:\n%s", data) + } + if New(path).List("acme/widget", 1)[0].ID != "n1" || len(New(path).List("acme/widget", 1)) != 1 { + t.Fatal("replay must honour the tombstone") + } + + // Default() is one process-wide store at DefaultPath. + first := Default() + if second := Default(); first != second || first.path != DefaultPath { + t.Fatalf("Default() must be the singleton at %s", DefaultPath) + } + if len(newID()) != idBytes*2 { + t.Fatalf("newID() = %q, want %d hex chars", newID(), idBytes*2) + } +} + +func TestStoreAppendFailureLeavesMemoryUnchanged(t *testing.T) { + dir := t.TempDir() + blocker := filepath.Join(dir, "file") + if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + // The parent "directory" is a regular file: MkdirAll fails. + s := New(filepath.Join(blocker, "notes.jsonl")) + if _, err := s.Add("acme/widget", 1, "alice", "hello"); err == nil { + t.Fatal("Add must surface the write error") + } + if len(s.All()) != 0 { + t.Fatal("a failed append must not be remembered") + } + // An in-memory note whose tombstone cannot be written stays live. + m := New("") + n, err := m.Add("acme/widget", 1, "alice", "hello") + if err != nil { + t.Fatal(err) + } + m.path = filepath.Join(blocker, "notes.jsonl") + if _, err := m.Delete(n.ID, "alice", false); err == nil { + t.Fatal("Delete must surface the write error") + } + if _, ok := m.Get(n.ID); !ok { + t.Fatal("a note whose tombstone failed to persist must stay live") + } +} + +func TestNormalizeRepo(t *testing.T) { + for _, c := range []struct { + in string + want string + ok bool + }{ + {" HiveCommons/Hive ", "hivecommons/hive", true}, + {"hive", "", false}, + {"/hive", "", false}, + {"owner/", "", false}, + {"owner/a/b", "", false}, + {"own er/repo", "", false}, + {"owner/re po", "", false}, + } { + got, ok := NormalizeRepo(c.in) + if got != c.want || ok != c.ok { + t.Errorf("NormalizeRepo(%q) = %q,%v want %q,%v", c.in, got, ok, c.want, c.ok) + } + } +} + +func TestKickSectionDefaultCapAndTinyRoom(t *testing.T) { + at := time.Date(2026, 11, 8, 0, 0, 0, 0, time.UTC) + notes := []Note{ + {Author: "alice", Text: "line one\nline two", CreatedAt: at}, + {Author: "bob", Text: "héllo wörld, a note that is longer than the room left", CreatedAt: at.Add(time.Minute)}, + } + // capBytes <= 0 means the default; newlines inside a note fold to spaces. + out := KickSection(notes, 0) + if !strings.Contains(out, "- @alice (2026-11-08): line one line two\n") || strings.Contains(out, "more note(s)") { + t.Fatalf("default cap must type both notes whole:\n%s", out) + } + // A cap smaller than the first line cuts it on a rune boundary and + // counts the rest. + out = KickSection(notes, 30) + if !strings.Contains(out, "- @bob (2026-11-08): héll"+elidedTrail) && !strings.Contains(out, "- @bob (2026-11-08): hél"+elidedTrail) { + t.Fatalf("cut must land on a rune boundary with the ellipsis:\n%s", out) + } + if !strings.Contains(out, "… and 1 more note(s) on the dashboard.") { + t.Fatalf("the unshown note must be counted:\n%s", out) + } + // No room at all: header only, every note counted. + out = KickSection(notes, 2) + if strings.Contains(out, "- @") || !strings.Contains(out, "… and 2 more note(s)") { + t.Fatalf("tiny cap:\n%s", out) + } +} diff --git a/src/pkg/scheduler/kick_layout.go b/src/pkg/scheduler/kick_layout.go index a2ca9664c1..f6bdf489a2 100644 --- a/src/pkg/scheduler/kick_layout.go +++ b/src/pkg/scheduler/kick_layout.go @@ -32,6 +32,7 @@ import ( // 14. PR follow-up handoff dynamic (pr-followup/) // 15. guide flow line dynamic (guide only) // 16. in-flight note dynamic (session claims) +// 16a. maintainer notes dynamic (dashboard notes on listed items) // 17. question answer contract dynamic (scanner only) // 18. in-progress claim rule static, present whenever the kick lists issues // 19. closing instruction static, always last @@ -119,6 +120,7 @@ func (s *Scheduler) assembleKick(a kickAssembly, message string) string { message = s.addPRFollowUpHandoff(a.agent, message) message = s.addGuideFlow(a.agent, a.actionable, message) message = s.addInflightNote(message, a.issues) + message = s.addMaintainerNotes(message, a.issues) message = s.addQuestionAnswerContract(a.agent, message, a.issues) message = addInProgressClaimRule(message, a.issues) if a.idleReason == "" { diff --git a/src/pkg/scheduler/kick_maintainer_notes.go b/src/pkg/scheduler/kick_maintainer_notes.go new file mode 100644 index 0000000000..744805a1b6 --- /dev/null +++ b/src/pkg/scheduler/kick_maintainer_notes.go @@ -0,0 +1,62 @@ +package scheduler + +import ( + "strings" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/maintainernotes" +) + +// MaintainerNotesLookup returns the live maintainer notes on repo#number +// (maintainernotes.Store.List). +type MaintainerNotesLookup func(repo string, number int) []maintainernotes.Note + +// SetMaintainerNotesLookup installs (or with nil, removes) the notes lookup +// the kick seam reads. +func (s *Scheduler) SetMaintainerNotesLookup(fn MaintainerNotesLookup) { + s.mu.Lock() + defer s.mu.Unlock() + s.maintainerNotes = fn +} + +// maintainerNotesKickHeader opens the seam; the seam is skipped when the +// kick already carries it. +const maintainerNotesKickHeader = maintainernotes.KickSectionHeader + +// addMaintainerNotes appends, per kicked issue that has any, the notes its +// maintainers left on the dashboard (maintainernotes.KickSection, capped at +// maintainernotes.KickSectionCap bytes per item). Private context: the +// block tells the agent not to quote it on GitHub. Nothing is appended when +// no lookup is installed or no listed item has a note. +func (s *Scheduler) addMaintainerNotes(message string, issues []github.Issue) string { + if message == "" || strings.Contains(message, maintainerNotesKickHeader) { + return message + } + s.mu.RLock() + fn := s.maintainerNotes + s.mu.RUnlock() + if fn == nil { + return message + } + var b strings.Builder + for _, issue := range issues { + notes := fn(issue.Repo, issue.Number) + if len(notes) == 0 { + continue + } + section := maintainernotes.KickSection(notes, maintainernotes.KickSectionCap) + if section == "" { + continue + } + // One header for the block; each item's notes under its own ref. + if b.Len() == 0 { + b.WriteString(maintainerNotesKickHeader + "\n") + } + b.WriteString("\n## " + issueDisplayRef(issue) + "\n") + b.WriteString(strings.TrimPrefix(section, maintainerNotesKickHeader+"\n")) + } + if b.Len() == 0 { + return message + } + return appendKickSection(message, b.String()) +} diff --git a/src/pkg/scheduler/kick_maintainer_notes_test.go b/src/pkg/scheduler/kick_maintainer_notes_test.go new file mode 100644 index 0000000000..01c6bec092 --- /dev/null +++ b/src/pkg/scheduler/kick_maintainer_notes_test.go @@ -0,0 +1,71 @@ +package scheduler + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/maintainernotes" +) + +// Dashboard maintainer notes ride the kick for the items it lists, under +// one "# Maintainer notes" header, capped per item; no lookup or no notes +// adds nothing. +func TestKickMaintainerNotesInjectedAndCapped(t *testing.T) { + s := workTrackerScheduler(t, "linear", "BODY\n${ISSUE_LIST}\n${PR_LIST}") + issues := []github.Issue{ + {SourceType: "linear", Repo: "acme/widget", ExternalID: "ENG-42", Number: 42, Title: "noted one"}, + {SourceType: "linear", Repo: "acme/widget", ExternalID: "ENG-43", Number: 43, Title: "quiet one"}, + } + msg := s.BuildAgentMessage("quality", issues, &github.ActionableResult{}) + if strings.Contains(msg, maintainerNotesKickHeader) { + t.Fatalf("no lookup must add no notes block:\n%s", msg) + } + + at := time.Date(2026, 11, 8, 9, 0, 0, 0, time.UTC) + s.SetMaintainerNotesLookup(func(repo string, number int) []maintainernotes.Note { + if repo != "acme/widget" || number != 42 { + return nil + } + return []maintainernotes.Note{ + {Author: "dave", Text: strings.Repeat("long context ", 200), CreatedAt: at.Add(-time.Hour)}, + {Author: "alice", Text: "owner wants this after the v6 cut", CreatedAt: at}, + {Author: "bob", Text: "waiting on legal", CreatedAt: at.Add(time.Hour)}, + } + }) + msg = s.BuildAgentMessage("quality", issues, &github.ActionableResult{}) + i := strings.Index(msg, maintainerNotesKickHeader) + if i < 0 || strings.Count(msg, maintainerNotesKickHeader) != 1 { + t.Fatalf("notes block must appear exactly once:\n%s", msg) + } + block := msg[i:] + if end := strings.Index(block, "\n\n"); end >= 0 { + // The block runs to the next blank-line-separated seam; the + // per-item section itself has one blank line after the header. + rest := block[end+2:] + if j := strings.Index(rest, "\n\n"); j >= 0 { + block = block[:end+2+j] + } + } + if !strings.Contains(block, "## acme/widget#42") || !strings.Contains(block, "- @alice (2026-11-08): owner wants this after the v6 cut") { + t.Fatalf("noted item missing:\n%s", block) + } + if strings.Contains(block, "acme/widget#43") { + t.Fatalf("an item without notes must not be listed:\n%s", block) + } + // Newest first; the oldest, oversized note is cut at the cap rather + // than typed whole. + if !(strings.Index(block, "@bob") < strings.Index(block, "@alice") && strings.Index(block, "@alice") < strings.Index(block, "@dave")) { + t.Fatalf("notes must run newest first:\n%s", block) + } + if strings.Contains(block, strings.Repeat("long context ", 200)) || !strings.Contains(block, "…") { + t.Fatalf("note over the cap must be elided with an ellipsis:\n%s", block) + } + if len(block) > maintainernotes.KickSectionCap+256 { + t.Fatalf("per-item block %d bytes is not capped near %d", len(block), maintainernotes.KickSectionCap) + } + if !strings.Contains(block, "not on GitHub") { + t.Fatalf("block must tell the agent the notes are private:\n%s", block) + } +} diff --git a/src/pkg/scheduler/scheduler.go b/src/pkg/scheduler/scheduler.go index b8c5aa4f10..27edebea00 100644 --- a/src/pkg/scheduler/scheduler.go +++ b/src/pkg/scheduler/scheduler.go @@ -46,6 +46,7 @@ type Scheduler struct { // logged, so it is logged once per day. classifierQuotaWarnedDay string inflight InflightLookup + maintainerNotes MaintainerNotesLookup runAdmitter RunAdmitter triageCommenter TriageCommenter clarity clarityGateState