diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8aa6ec59c7..da8dc2e79e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -31,6 +31,13 @@ updates: open-pull-requests-limit: 10 commit-message: prefix: "🌱 build(deps)" + ignore: + # Pinned by the gh-aw compiler (gh-aw-compile.yml --pin) and written + # into the generated weekly-competitor-report.lock.yml and + # .github/aw/actions-lock.json; the compile guard regenerates both and + # reverts a hand bump, so Dependabot's PR for it can never go green. + # Bump the compiler pin and recompile instead. + - dependency-name: "github/gh-aw-actions/setup" - package-ecosystem: "docker" directory: "/src" diff --git a/.github/release-lines.yml b/.github/release-lines.yml index 67009f5b78..855448fbaa 100644 --- a/.github/release-lines.yml +++ b/.github/release-lines.yml @@ -188,6 +188,10 @@ pinned: # image is operator tooling, not a hive release channel, so it follows the # default branch rather than every release line; v4 is feature-frozen. stream-image.yml: [-v4, -v6] + # Advisory gremlins mutation report on changed Go packages (#17349). It is + # pull_request-only and never blocks, so it covers every line that takes Go + # PRs; surviving-mutant data is equally useful on v4 backports. + mutation-advisory.yml: [] # Workflows that deliberately do NOT pin to the release lines. Each must keep a # wildcard branch filter; if one is ever narrowed to a fixed list, the guard diff --git a/.github/scripts/ci-infra-signatures.tsv b/.github/scripts/ci-infra-signatures.tsv index 06e437543a..b25c9319fd 100644 --- a/.github/scripts/ci-infra-signatures.tsv +++ b/.github/scripts/ci-infra-signatures.tsv @@ -21,6 +21,10 @@ # upstream-download-5xx (2026-10-07, run 37638156130): a tool download from # github.com releases (curl -f in "Install just") got an HTTP 5xx - a transient # upstream outage. 4xx is deliberately NOT matched: a 404 is a wrong version pin. +# 2026-11-09 (#17351, release-asset 504 outage) added two shapes: curl inside +# `docker build`, where BuildKit prefixes each line with "# " (run +# 42568390991), and golangci-lint-action's "Unexpected HTTP response: 504" +# (run 42568320263). # # Every class below was observed on the self-hosted pool on 2026-09-29; the # fixtures under testdata/ci-infra/ are real excerpts from those jobs. @@ -47,7 +51,8 @@ toolcache-clobbered step : (npm|node|go): command not found$ runner-lost annotation The runner has received a shutdown signal test-list-empty step ^##\[error\]go test -list produced no test functions test-list-empty silent-step \bgo test\b.*\s-list\b -upstream-download-5xx step ^curl: \(22\) The requested URL returned error: 5\d\d$ +upstream-download-5xx step ^(?:#\d+ \d+(?:\.\d+)? )?curl: \(22\) The requested URL returned error: 5\d\d$ +upstream-download-5xx step ^##\[error\]Unexpected HTTP response: 5\d\d$ # Reserved class `derived`: the job failed only to REPORT that other jobs # failed (v2 Tests' shard gate). Keep these rows last. diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index 818a8d463f..3450a885d5 100644 --- a/.github/scripts/integration-governance.cjs +++ b/.github/scripts/integration-governance.cjs @@ -9,7 +9,7 @@ const MAX_COMMITS = 1000; const MAX_AUTHOR_BATCH = 50; // This literal is inside the enrolled .github closure. A caller-supplied // preparedBy.sourceSHA must never choose a new executable verifier tree. -const TRUSTED_SCRIPTS_TREE = '925f525d22d99042bf0c41778d8de837a79ac3e9'; +const TRUSTED_SCRIPTS_TREE = '7c365d4a9df3670491f8751464340e2dceb43e77'; const SOURCE = 'https://github.com/kubernetes-sigs/kubebuilder-release-tools/tree/012269a88fa4c034a0acf1ba84c26b195c0dbab4'; const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const git = (args, cwd = process.cwd()) => diff --git a/.github/scripts/pr-overlap.sh b/.github/scripts/pr-overlap.sh index 85ac5bc1a7..f5fdaa2692 100755 --- a/.github/scripts/pr-overlap.sh +++ b/.github/scripts/pr-overlap.sh @@ -76,7 +76,7 @@ changed_files() { local base=$1 ref=$2 local mb mb=$(git merge-base "origin/${base}" "$ref") - git diff --name-only "${mb}...${ref}" | sort -u + git diff --no-renames --name-only "${mb}...${ref}" | sort -u } join_files() { @@ -101,6 +101,21 @@ intersect_files() { done | sort -u } +# Lists the union of conflicted and shared paths, marking the conflicted ones, +# so a CONFLICT row never hides shared paths that merged cleanly. +join_shared_files() { + local -n conflicts=$1 + local -n shared=$2 + local f out='' item + while IFS= read -r f; do + [[ -n "$f" ]] || continue + item=$(join_files '' "$f") + if printf '%s\n' "${conflicts[@]}" | grep -qxF -- "$f"; then item+=' (conflict)'; fi + if [[ -z "$out" ]]; then out=$item; else out+="
${item}"; fi + done < <(printf '%s\n' "${conflicts[@]}" "${shared[@]}" | sort -u) + [[ -n "$out" ]] && printf '%s' "$out" || printf '—' +} + # Prints the paths `git merge-tree` reports as conflicted when merging $a and # $b; prints nothing when they merge cleanly. With --name-only, a conflicted # merge prints the tree OID, then one conflicted path per line, then a blank @@ -177,17 +192,17 @@ make_report_for_pr() { mapfile -t conflict_files < <(merge_conflicts "$target_on_base" "$other_on_base") fi fi + # shellcheck disable=SC2034 # consumed by intersect_files via nameref + mapfile -t other_files < <(changed_files "$base" "$other_ref") + mapfile -t overlap_files < <(intersect_files target_files other_files) if ((${#conflict_files[@]})); then relation='CONFLICT' report_has_conflicts=1 report_has_any=1 - files_md=$(join_files '
' "${conflict_files[@]}") + files_md=$(join_shared_files conflict_files overlap_files) report_rows+="| #${number} | ${title//'|'/'\|'} | ${relation} | ${files_md} |"$'\n' continue fi - # shellcheck disable=SC2034 # consumed by intersect_files via nameref - mapfile -t other_files < <(changed_files "$base" "$other_ref") - mapfile -t overlap_files < <(intersect_files target_files other_files) if ((${#overlap_files[@]})); then relation='same files' report_has_any=1 diff --git a/.github/scripts/test-pr-overlap.sh b/.github/scripts/test-pr-overlap.sh index ccce9ed7be..f3581977cc 100755 --- a/.github/scripts/test-pr-overlap.sh +++ b/.github/scripts/test-pr-overlap.sh @@ -78,8 +78,19 @@ commit_file c.txt "$(printf 'c%s\n' 1 2 3 4 5 6 7 8 9 PR3)" 'pr3 c' git -C "$SEED" checkout -q -b pr4 "$b0" commit_file d.txt 'd' 'pr4' +# PRs 5 and 6 both add new.txt with different content (add/add conflict); PRs 7 +# and 8 both add same.txt with identical content (merges cleanly). +git -C "$SEED" checkout -q -b pr5 "$b1" +commit_file new.txt 'new-from-pr5' 'pr5' +git -C "$SEED" checkout -q -b pr6 "$b1" +commit_file new.txt 'new-from-pr6' 'pr6' +git -C "$SEED" checkout -q -b pr7 "$b1" +commit_file same.txt 'same-content' 'pr7' +git -C "$SEED" checkout -q -b pr8 "$b1" +commit_file same.txt 'same-content' 'pr8' + git -C "$SEED" push -q "$ORIGIN" v6 -for n in 1 2 3 4; do +for n in 1 2 3 4 5 6 7 8; do git -C "$SEED" push -q "$ORIGIN" "pr${n}:refs/pull/${n}/head" done @@ -94,7 +105,7 @@ shift case "$*" in -X*) printf '%s\n' "$*" >>"$GH_WRITE_LOG"; exit 0 ;; *'/pulls?base=v6'*) - for n in 4 3 2 1; do printf '%s\tPR %s\t%s\t2026-01-01T00:00:00Z\n' "$n" "$n" "$REPO_SLUG"; done ;; + for n in 8 7 6 5 4 3 2 1; do printf '%s\tPR %s\t%s\t2026-01-01T00:00:00Z\n' "$n" "$n" "$REPO_SLUG"; done ;; *'.head.repo.full_name'*) printf '%s\n' "$REPO_SLUG" ;; *'.head.sha'*) printf '%s\n' "${FALLBACK_SHA:-}" ;; *'.base.ref'*) printf 'v6\n' ;; @@ -127,13 +138,24 @@ LABEL_DEL="-X DELETE repos/${REPO_SLUG}/issues/%s/labels/conflicts-with-open-pr" echo 'PR 2: real sibling conflict with PR 3, stale PR 1 is not blamed' run_pr 2 assert_exit0 -assert_contains "$OUT" '| #3 | PR 3 | CONFLICT | `b.txt` |' 'reports the real b.txt conflict with PR 3, and only b.txt' -assert_not_contains "$OUT" 'c.txt' 'does not list the cleanly auto-merged c.txt' +assert_contains "$OUT" '| #3 | PR 3 | CONFLICT | `b.txt` (conflict)
`c.txt` |' 'marks b.txt as the conflict with PR 3 and lists shared clean c.txt unmarked' +assert_not_contains "$OUT" '`c.txt` (conflict)' 'does not mark the cleanly auto-merged c.txt as conflicting' assert_not_contains "$OUT" '| #1 |' 'does not blame PR 1 for its conflict with the base' assert_not_contains "$OUT" '| #4 |' 'does not link the unrelated stale PR 4' # shellcheck disable=SC2059 assert_contains "$WRITES" "$(printf -- "$LABEL_ADD" 2)" 'labels PR 2 conflicts-with-open-pr' +echo 'PR 5: add/add of the same new path with different content' +run_pr 5 +assert_exit0 +assert_contains "$OUT" '| #6 | PR 6 | CONFLICT | `new.txt` (conflict) |' 'reports the add/add conflict on new.txt' + +echo 'PR 7: add/add of the same new path with identical content' +run_pr 7 +assert_exit0 +assert_contains "$OUT" '| #8 | PR 8 | same files | `same.txt` |' 'reports same.txt as shared, not conflicting' +assert_not_contains "$OUT" 'CONFLICT |' 'does not call identical add/add a conflict' + echo 'PR 1: conflicts with the base itself' run_pr 1 assert_exit0 @@ -158,12 +180,12 @@ git -C "$WORK" update-ref refs/heads/pr-3 "$(git -C "$SEED" rev-parse pr4)" run_pr 2 assert_exit0 assert_contains "$OUT" 'PR #3 pull ref unavailable; fetching head' 'reports the fallback' -assert_contains "$OUT" '| #3 | PR 3 | CONFLICT | `b.txt` |' 'still detects the sibling conflict using the current head' +assert_contains "$OUT" '| #3 | PR 3 | CONFLICT | `b.txt` (conflict)
`c.txt` |' 'still detects the sibling conflict using the current head' echo 'PR 3: fallback also works when the target PR has no pull ref' run_pr 3 assert_exit0 -assert_contains "$OUT" '| #2 | PR 2 | CONFLICT | `b.txt` |' 'checks the target fetched by SHA' +assert_contains "$OUT" '| #2 | PR 2 | CONFLICT | `b.txt` (conflict)
`c.txt` |' 'checks the target fetched by SHA' echo 'PR 3: invalid API head fails without publishing a partial report' FALLBACK_SHA=null diff --git a/.github/scripts/testdata/ci-infra/code-upstream-download-404.log b/.github/scripts/testdata/ci-infra/code-upstream-download-404.log new file mode 100644 index 0000000000..3729828c45 --- /dev/null +++ b/.github/scripts/testdata/ci-infra/code-upstream-download-404.log @@ -0,0 +1,62 @@ +2026-11-09T05:38:04.5394499Z ##[group]Run docker buildx build --load --network host --build-arg BASE_REGISTRY="$BASE_REGISTRY" -f "src/Dockerfile.contributor" -t "hive-ci-contributor:test" . +2026-11-09T05:38:04.5395357Z ^[[36;1mdocker buildx build --load --network host --build-arg BASE_REGISTRY="$BASE_REGISTRY" -f "src/Dockerfile.contributor" -t "hive-ci-contributor:test" .^[[0m +2026-11-09T05:38:04.5408586Z shell: /usr/bin/bash -e {0} +2026-11-09T05:38:04.5408807Z env: +2026-11-09T05:38:04.5408996Z ACTIONS_CACHE_SEGMENT_DOWNLOAD_TIMEOUT_MINS: 1 +2026-11-09T05:38:04.5409237Z GO_CACHE_GUARD_BUILD_CACHE: job +2026-11-09T05:38:04.5409447Z BASE_REGISTRY: mirror.gcr.io/library +2026-11-09T05:38:04.5409654Z ##[endgroup] +2026-11-09T05:38:04.8809509Z #0 building with "builder-9e62066e-81b1-48b5-9654-3d2862d8a5ec" instance using docker-container driver +2026-11-09T05:38:40.8576324Z +2026-11-09T05:38:51.7305872Z #17 11.03 /tmp/just.tar.gz: OK +2026-11-09T05:38:51.8654320Z #17 11.17 curl: (22) The requested URL returned error: 404 +2026-11-09T05:39:01.8945014Z #17 21.19 curl: (22) The requested URL returned error: 404 +2026-11-09T05:39:11.9226188Z #17 31.22 curl: (22) The requested URL returned error: 404 +2026-11-09T05:39:21.9502710Z #17 41.25 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8186930Z #17 ERROR: process "/bin/sh -c ARCH=\"${TARGETARCH:-$(dpkg --print-architecture)}\" && case \"$ARCH\" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_AMD64\"; YQ_ASSET=yq_linux_amd64; YQ_SHA256=\"$YQ_SHA256_AMD64\" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_ARM64\"; YQ_ASSET=yq_linux_arm64; YQ_SHA256=\"$YQ_SHA256_ARM64\" ;; *) echo \"unsupported arch for just/yq: $ARCH\" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz \"https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz\" && echo \"${JUST_SHA256} /tmp/just.tar.gz\" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq \"https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}\" && echo \"${YQ_SHA256} /tmp/yq\" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version" did not complete successfully: exit code: 22 +2026-11-09T05:43:52.8191038Z ------ +2026-11-09T05:43:52.8194559Z > [stage-1 5/37] RUN ARCH="amd64" && case "$ARCH" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256="4a5cc2f53e6f0f8c59092a6cc38291eb729d46a7dd95d3ae582008881b84931d"; YQ_ASSET=yq_linux_amd64; YQ_SHA256="c5f056448f973ae7d39b5401949648a78f2dc1947d6a8eb65be60d5c504b9385" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256="748237128c4c40cbdabc65e841d05ceba13cc23a91eaba395495894c1d9764df"; YQ_ASSET=yq_linux_arm64; YQ_SHA256="88a1016bc1d657375a35864e4f44b6f333df8ff97b559f51bba0adcb2169df09" ;; *) echo "unsupported arch for just/yq: $ARCH" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz "https://github.com/casey/just/releases/download/1.58.0/just-1.58.0-${JUST_TARGET}.tar.gz" && echo "${JUST_SHA256} /tmp/just.tar.gz" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq "https://github.com/mikefarah/yq/releases/download/v4.53.6/${YQ_ASSET}" && echo "${YQ_SHA256} /tmp/yq" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version: +2026-11-09T05:43:52.8198817Z 221.8 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8199109Z 231.8 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8199369Z 241.9 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8199629Z 251.9 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8199892Z 261.9 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8200145Z 272.0 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8200396Z 282.0 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8200649Z 292.0 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8200901Z 302.1 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8201392Z 312.1 curl: (22) The requested URL returned error: 404 +2026-11-09T05:43:52.8201610Z ------ +2026-11-09T05:43:52.8201702Z +2026-11-09T05:43:52.8202097Z ^[[33m1 warning found (use docker --debug to expand): +2026-11-09T05:43:52.8202628Z ^[[0m - SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ARG "NODESOURCE_KEY_SHA256") (line 222) +2026-11-09T05:43:52.8203073Z Dockerfile.contributor:189 +2026-11-09T05:43:52.8203261Z -------------------- +2026-11-09T05:43:52.8203576Z 188 | ARG YQ_SHA256_ARM64=88a1016bc1d657375a35864e4f44b6f333df8ff97b559f51bba0adcb2169df09 +2026-11-09T05:43:52.8204079Z 189 | >>> RUN ARCH="${TARGETARCH:-$(dpkg --print-architecture)}" \ +2026-11-09T05:43:52.8204344Z 190 | >>> && case "$ARCH" in \ +2026-11-09T05:43:52.8204674Z 191 | >>> amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256="$JUST_SHA256_AMD64"; \ +2026-11-09T05:43:52.8205096Z 192 | >>> YQ_ASSET=yq_linux_amd64; YQ_SHA256="$YQ_SHA256_AMD64" ;; \ +2026-11-09T05:43:52.8205534Z 193 | >>> arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256="$JUST_SHA256_ARM64"; \ +2026-11-09T05:43:52.8205954Z 194 | >>> YQ_ASSET=yq_linux_arm64; YQ_SHA256="$YQ_SHA256_ARM64" ;; \ +2026-11-09T05:43:52.8206373Z 195 | >>> *) echo "unsupported arch for just/yq: $ARCH" >&2; exit 1 ;; \ +2026-11-09T05:43:52.8206780Z 196 | >>> esac \ +2026-11-09T05:43:52.8207453Z 197 | >>> && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors \ +2026-11-09T05:43:52.8208088Z 198 | >>> -o /tmp/just.tar.gz \ +2026-11-09T05:43:52.8208812Z 199 | >>> "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz" \ +2026-11-09T05:43:52.8209444Z 200 | >>> && echo "${JUST_SHA256} /tmp/just.tar.gz" | sha256sum -c - \ +2026-11-09T05:43:52.8209761Z 201 | >>> && tar -xzf /tmp/just.tar.gz -C /tmp just \ +2026-11-09T05:43:52.8210045Z 202 | >>> && install -m 0755 /tmp/just /usr/local/bin/just \ +2026-11-09T05:43:52.8210309Z 203 | >>> && rm -f /tmp/just.tar.gz /tmp/just \ +2026-11-09T05:43:52.8210699Z 204 | >>> && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors \ +2026-11-09T05:43:52.8211083Z 205 | >>> -o /tmp/yq \ +2026-11-09T05:43:52.8211397Z 206 | >>> "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}" \ +2026-11-09T05:43:52.8211767Z 207 | >>> && echo "${YQ_SHA256} /tmp/yq" | sha256sum -c - \ +2026-11-09T05:43:52.8212039Z 208 | >>> && install -m 0755 /tmp/yq /usr/local/bin/yq \ +2026-11-09T05:43:52.8212275Z 209 | >>> && rm -f /tmp/yq \ +2026-11-09T05:43:52.8212464Z 210 | >>> && just --version \ +2026-11-09T05:43:52.8212655Z 211 | >>> && yq --version +2026-11-09T05:43:52.8212829Z 212 | +2026-11-09T05:43:52.8212978Z -------------------- +2026-11-09T05:43:52.8216281Z ERROR: failed to build: failed to solve: process "/bin/sh -c ARCH=\"${TARGETARCH:-$(dpkg --print-architecture)}\" && case \"$ARCH\" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_AMD64\"; YQ_ASSET=yq_linux_amd64; YQ_SHA256=\"$YQ_SHA256_AMD64\" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_ARM64\"; YQ_ASSET=yq_linux_arm64; YQ_SHA256=\"$YQ_SHA256_ARM64\" ;; *) echo \"unsupported arch for just/yq: $ARCH\" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz \"https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz\" && echo \"${JUST_SHA256} /tmp/just.tar.gz\" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq \"https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}\" && echo \"${YQ_SHA256} /tmp/yq\" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version" did not complete successfully: exit code: 22 +2026-11-09T05:43:52.8268368Z ##[error]Process completed with exit code 1. diff --git a/.github/scripts/testdata/ci-infra/expected.tsv b/.github/scripts/testdata/ci-infra/expected.tsv index 662916c2df..6412faa6ba 100644 --- a/.github/scripts/testdata/ci-infra/expected.tsv +++ b/.github/scripts/testdata/ci-infra/expected.tsv @@ -16,6 +16,9 @@ infra-toolcache-clobbered-copyfile infra:toolcache-clobbered infra-toolcache-clobbered-rmdir infra:toolcache-clobbered infra-toolcache-clobbered-npm infra:toolcache-clobbered infra-upstream-download-5xx infra:upstream-download-5xx +infra-upstream-download-5xx-buildkit infra:upstream-download-5xx +infra-upstream-download-5xx-golangci infra:upstream-download-5xx +code-upstream-download-404 code derived-shard-gate derived code-compile-redeclared code code-vet-undefined code diff --git a/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-buildkit.log b/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-buildkit.log new file mode 100644 index 0000000000..7697eab264 --- /dev/null +++ b/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-buildkit.log @@ -0,0 +1,62 @@ +2026-11-09T05:38:04.5394499Z ##[group]Run docker buildx build --load --network host --build-arg BASE_REGISTRY="$BASE_REGISTRY" -f "src/Dockerfile.contributor" -t "hive-ci-contributor:test" . +2026-11-09T05:38:04.5395357Z ^[[36;1mdocker buildx build --load --network host --build-arg BASE_REGISTRY="$BASE_REGISTRY" -f "src/Dockerfile.contributor" -t "hive-ci-contributor:test" .^[[0m +2026-11-09T05:38:04.5408586Z shell: /usr/bin/bash -e {0} +2026-11-09T05:38:04.5408807Z env: +2026-11-09T05:38:04.5408996Z ACTIONS_CACHE_SEGMENT_DOWNLOAD_TIMEOUT_MINS: 1 +2026-11-09T05:38:04.5409237Z GO_CACHE_GUARD_BUILD_CACHE: job +2026-11-09T05:38:04.5409447Z BASE_REGISTRY: mirror.gcr.io/library +2026-11-09T05:38:04.5409654Z ##[endgroup] +2026-11-09T05:38:04.8809509Z #0 building with "builder-9e62066e-81b1-48b5-9654-3d2862d8a5ec" instance using docker-container driver +2026-11-09T05:38:40.8576324Z +2026-11-09T05:38:51.7305872Z #17 11.03 /tmp/just.tar.gz: OK +2026-11-09T05:38:51.8654320Z #17 11.17 curl: (22) The requested URL returned error: 504 +2026-11-09T05:39:01.8945014Z #17 21.19 curl: (22) The requested URL returned error: 504 +2026-11-09T05:39:11.9226188Z #17 31.22 curl: (22) The requested URL returned error: 504 +2026-11-09T05:39:21.9502710Z #17 41.25 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8186930Z #17 ERROR: process "/bin/sh -c ARCH=\"${TARGETARCH:-$(dpkg --print-architecture)}\" && case \"$ARCH\" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_AMD64\"; YQ_ASSET=yq_linux_amd64; YQ_SHA256=\"$YQ_SHA256_AMD64\" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_ARM64\"; YQ_ASSET=yq_linux_arm64; YQ_SHA256=\"$YQ_SHA256_ARM64\" ;; *) echo \"unsupported arch for just/yq: $ARCH\" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz \"https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz\" && echo \"${JUST_SHA256} /tmp/just.tar.gz\" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq \"https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}\" && echo \"${YQ_SHA256} /tmp/yq\" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version" did not complete successfully: exit code: 22 +2026-11-09T05:43:52.8191038Z ------ +2026-11-09T05:43:52.8194559Z > [stage-1 5/37] RUN ARCH="amd64" && case "$ARCH" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256="4a5cc2f53e6f0f8c59092a6cc38291eb729d46a7dd95d3ae582008881b84931d"; YQ_ASSET=yq_linux_amd64; YQ_SHA256="c5f056448f973ae7d39b5401949648a78f2dc1947d6a8eb65be60d5c504b9385" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256="748237128c4c40cbdabc65e841d05ceba13cc23a91eaba395495894c1d9764df"; YQ_ASSET=yq_linux_arm64; YQ_SHA256="88a1016bc1d657375a35864e4f44b6f333df8ff97b559f51bba0adcb2169df09" ;; *) echo "unsupported arch for just/yq: $ARCH" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz "https://github.com/casey/just/releases/download/1.58.0/just-1.58.0-${JUST_TARGET}.tar.gz" && echo "${JUST_SHA256} /tmp/just.tar.gz" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq "https://github.com/mikefarah/yq/releases/download/v4.53.6/${YQ_ASSET}" && echo "${YQ_SHA256} /tmp/yq" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version: +2026-11-09T05:43:52.8198817Z 221.8 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8199109Z 231.8 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8199369Z 241.9 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8199629Z 251.9 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8199892Z 261.9 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8200145Z 272.0 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8200396Z 282.0 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8200649Z 292.0 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8200901Z 302.1 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8201392Z 312.1 curl: (22) The requested URL returned error: 504 +2026-11-09T05:43:52.8201610Z ------ +2026-11-09T05:43:52.8201702Z +2026-11-09T05:43:52.8202097Z ^[[33m1 warning found (use docker --debug to expand): +2026-11-09T05:43:52.8202628Z ^[[0m - SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ARG "NODESOURCE_KEY_SHA256") (line 222) +2026-11-09T05:43:52.8203073Z Dockerfile.contributor:189 +2026-11-09T05:43:52.8203261Z -------------------- +2026-11-09T05:43:52.8203576Z 188 | ARG YQ_SHA256_ARM64=88a1016bc1d657375a35864e4f44b6f333df8ff97b559f51bba0adcb2169df09 +2026-11-09T05:43:52.8204079Z 189 | >>> RUN ARCH="${TARGETARCH:-$(dpkg --print-architecture)}" \ +2026-11-09T05:43:52.8204344Z 190 | >>> && case "$ARCH" in \ +2026-11-09T05:43:52.8204674Z 191 | >>> amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256="$JUST_SHA256_AMD64"; \ +2026-11-09T05:43:52.8205096Z 192 | >>> YQ_ASSET=yq_linux_amd64; YQ_SHA256="$YQ_SHA256_AMD64" ;; \ +2026-11-09T05:43:52.8205534Z 193 | >>> arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256="$JUST_SHA256_ARM64"; \ +2026-11-09T05:43:52.8205954Z 194 | >>> YQ_ASSET=yq_linux_arm64; YQ_SHA256="$YQ_SHA256_ARM64" ;; \ +2026-11-09T05:43:52.8206373Z 195 | >>> *) echo "unsupported arch for just/yq: $ARCH" >&2; exit 1 ;; \ +2026-11-09T05:43:52.8206780Z 196 | >>> esac \ +2026-11-09T05:43:52.8207453Z 197 | >>> && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors \ +2026-11-09T05:43:52.8208088Z 198 | >>> -o /tmp/just.tar.gz \ +2026-11-09T05:43:52.8208812Z 199 | >>> "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz" \ +2026-11-09T05:43:52.8209444Z 200 | >>> && echo "${JUST_SHA256} /tmp/just.tar.gz" | sha256sum -c - \ +2026-11-09T05:43:52.8209761Z 201 | >>> && tar -xzf /tmp/just.tar.gz -C /tmp just \ +2026-11-09T05:43:52.8210045Z 202 | >>> && install -m 0755 /tmp/just /usr/local/bin/just \ +2026-11-09T05:43:52.8210309Z 203 | >>> && rm -f /tmp/just.tar.gz /tmp/just \ +2026-11-09T05:43:52.8210699Z 204 | >>> && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors \ +2026-11-09T05:43:52.8211083Z 205 | >>> -o /tmp/yq \ +2026-11-09T05:43:52.8211397Z 206 | >>> "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}" \ +2026-11-09T05:43:52.8211767Z 207 | >>> && echo "${YQ_SHA256} /tmp/yq" | sha256sum -c - \ +2026-11-09T05:43:52.8212039Z 208 | >>> && install -m 0755 /tmp/yq /usr/local/bin/yq \ +2026-11-09T05:43:52.8212275Z 209 | >>> && rm -f /tmp/yq \ +2026-11-09T05:43:52.8212464Z 210 | >>> && just --version \ +2026-11-09T05:43:52.8212655Z 211 | >>> && yq --version +2026-11-09T05:43:52.8212829Z 212 | +2026-11-09T05:43:52.8212978Z -------------------- +2026-11-09T05:43:52.8216281Z ERROR: failed to build: failed to solve: process "/bin/sh -c ARCH=\"${TARGETARCH:-$(dpkg --print-architecture)}\" && case \"$ARCH\" in amd64|x86_64) JUST_TARGET=x86_64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_AMD64\"; YQ_ASSET=yq_linux_amd64; YQ_SHA256=\"$YQ_SHA256_AMD64\" ;; arm64|aarch64) JUST_TARGET=aarch64-unknown-linux-musl; JUST_SHA256=\"$JUST_SHA256_ARM64\"; YQ_ASSET=yq_linux_arm64; YQ_SHA256=\"$YQ_SHA256_ARM64\" ;; *) echo \"unsupported arch for just/yq: $ARCH\" >&2; exit 1 ;; esac && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/just.tar.gz \"https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-${JUST_TARGET}.tar.gz\" && echo \"${JUST_SHA256} /tmp/just.tar.gz\" | sha256sum -c - && tar -xzf /tmp/just.tar.gz -C /tmp just && install -m 0755 /tmp/just /usr/local/bin/just && rm -f /tmp/just.tar.gz /tmp/just && curl -fsSL --retry 30 --retry-delay 10 --retry-max-time 300 --retry-connrefused --retry-all-errors -o /tmp/yq \"https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${YQ_ASSET}\" && echo \"${YQ_SHA256} /tmp/yq\" | sha256sum -c - && install -m 0755 /tmp/yq /usr/local/bin/yq && rm -f /tmp/yq && just --version && yq --version" did not complete successfully: exit code: 22 +2026-11-09T05:43:52.8268368Z ##[error]Process completed with exit code 1. diff --git a/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-golangci.log b/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-golangci.log new file mode 100644 index 0000000000..d80699f89e --- /dev/null +++ b/.github/scripts/testdata/ci-infra/infra-upstream-download-5xx-golangci.log @@ -0,0 +1,37 @@ +2026-11-09T05:37:14.4726771Z ##[group]Run golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a +2026-11-09T05:37:14.4727483Z with: +2026-11-09T05:37:14.4727676Z version: v2.13.1 +2026-11-09T05:37:14.4727888Z working-directory: src +2026-11-09T05:37:14.4728108Z args: ./... ./crux/... +2026-11-09T05:37:14.4728316Z skip-cache: true +2026-11-09T05:37:14.4728516Z install-mode: binary +2026-11-09T05:37:14.4728730Z install-only: false +2026-11-09T05:37:14.4731189Z github-token: *** +2026-11-09T05:37:14.4731396Z verify: true +2026-11-09T05:37:14.4731596Z only-new-issues: false +2026-11-09T05:37:14.4731818Z skip-save-cache: false +2026-11-09T05:37:14.4732049Z cache-invalidation-interval: 7 +2026-11-09T05:37:14.4732310Z problem-matchers: false +2026-11-09T05:37:14.4732540Z env: +2026-11-09T05:37:14.4732727Z GO_CACHE_GUARD_BUILD_CACHE: job +2026-11-09T05:37:14.4732976Z GOTOOLCHAIN: local +2026-11-09T05:37:14.4733182Z ##[endgroup] +2026-11-09T05:37:14.6192548Z ##[group]Restore cache +2026-11-09T05:37:14.6195197Z Skipping cache restoration +2026-11-09T05:37:14.6196573Z ##[endgroup] +2026-11-09T05:37:14.6197312Z ##[group]Install +2026-11-09T05:37:14.6199693Z Finding needed golangci-lint version... +2026-11-09T05:37:14.6203375Z Installation mode: binary +2026-11-09T05:37:14.6204612Z Installing golangci-lint binary v2.13.1... +2026-11-09T05:37:14.6206156Z Downloading binary https://github.com/golangci/golangci-lint/releases/download/v2.13.1/golangci-lint-2.13.1-linux-amd64.tar.gz ... +2026-11-09T05:37:25.6552917Z Unexpected HTTP response: 504 +2026-11-09T05:37:25.6554716Z Waiting 10 seconds before trying again +2026-11-09T05:37:35.6698842Z Unexpected HTTP response: 504 +2026-11-09T05:37:35.6699432Z Waiting 16 seconds before trying again +2026-11-09T05:37:51.6850747Z ##[endgroup] +2026-11-09T05:37:51.6936148Z ##[error]Failed to run: Error: Unexpected HTTP response: 504, Error: Unexpected HTTP response: 504 + at /home/runner/work/_actions/golangci/golangci-lint-action/ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a/dist/run/index.js:12369:25 + at Generator.next () + at fulfilled (/home/runner/work/_actions/golangci/golangci-lint-action/ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a/dist/run/index.js:12270:58) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) +2026-11-09T05:37:51.6947704Z ##[error]Unexpected HTTP response: 504 diff --git a/.github/workflows/ci-runner-image.yml b/.github/workflows/ci-runner-image.yml index 457d98eceb..69705fe271 100644 --- a/.github/workflows/ci-runner-image.yml +++ b/.github/workflows/ci-runner-image.yml @@ -160,7 +160,7 @@ jobs: - name: Log in to GHCR if: github.event_name == 'workflow_dispatch' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index f83cfba952..ce9ac5a343 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -313,7 +313,7 @@ jobs: - name: Log in to GHCR if: needs.gate.outputs.push == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -550,7 +550,7 @@ jobs: driver-opts: network=host - name: Log in to GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -612,7 +612,7 @@ jobs: # credential for public reads regardless of org. - name: Log in to GHCR as the cross-org publisher if: steps.crosspat.outputs.available == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -711,7 +711,7 @@ jobs: - name: Log in to GHCR if: needs.gate.outputs.push == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -787,7 +787,7 @@ jobs: driver-opts: network=host - name: Log in to GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -829,7 +829,7 @@ jobs: - name: Log in to GHCR as the cross-org publisher if: steps.crosspat.outputs.available == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -925,7 +925,7 @@ jobs: - name: Log in to GHCR if: needs.gate.outputs.push == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -1010,7 +1010,7 @@ jobs: driver-opts: network=host - name: Log in to GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -1052,7 +1052,7 @@ jobs: - name: Log in to GHCR as the cross-org publisher if: steps.crosspat.outputs.available == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/integration-candidate.yml b/.github/workflows/integration-candidate.yml index 46b7c820d0..24be4b532d 100644 --- a/.github/workflows/integration-candidate.yml +++ b/.github/workflows/integration-candidate.yml @@ -560,7 +560,7 @@ jobs: set -euo pipefail JUST_VERSION=1.58.0 JUST_SHA256=4a5cc2f53e6f0f8c59092a6cc38291eb729d46a7dd95d3ae582008881b84931d - curl -fsSL -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" + curl -fsSL --retry 5 --retry-delay 10 --retry-all-errors -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" echo "${JUST_SHA256} /tmp/just.tgz" | sha256sum -c - tar -xzf /tmp/just.tgz -C /tmp just sudo install -m 0755 /tmp/just /usr/local/bin/just diff --git a/.github/workflows/integration-technical-v2-ci.yml b/.github/workflows/integration-technical-v2-ci.yml index 653496ec7d..6114facd28 100644 --- a/.github/workflows/integration-technical-v2-ci.yml +++ b/.github/workflows/integration-technical-v2-ci.yml @@ -414,7 +414,7 @@ jobs: set -euo pipefail JUST_VERSION=1.58.0 JUST_SHA256=4a5cc2f53e6f0f8c59092a6cc38291eb729d46a7dd95d3ae582008881b84931d - curl -fsSL -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" + curl -fsSL --retry 5 --retry-delay 10 --retry-all-errors -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" echo "${JUST_SHA256} /tmp/just.tgz" | sha256sum -c - tar -xzf /tmp/just.tgz -C /tmp just sudo install -m 0755 /tmp/just /usr/local/bin/just diff --git a/.github/workflows/mutation-advisory.yml b/.github/workflows/mutation-advisory.yml new file mode 100644 index 0000000000..11f293ec34 --- /dev/null +++ b/.github/workflows/mutation-advisory.yml @@ -0,0 +1,51 @@ +name: Mutation (advisory) + +# Phase 1 of #17349: surface "covered but never asserted" branches as surviving +# mutants on changed Go packages. Advisory only — never blocks a PR. +on: + pull_request: + branches: [v4, v5, v6] + paths: + - 'src/**.go' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + mutation: + runs-on: ubuntu-latest + timeout-minutes: 20 + continue-on-error: true + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + cache: false + go-version-file: src/go.mod + - name: Install gremlins + run: go install github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 + # The mutation run executes PR-controlled test code, so it gets no token: + # it only writes mutation-out/comment.md. The token is scoped to the + # separate comment-upsert step below. + - name: Run mutation report + env: + BASE_REF: ${{ github.base_ref }} + run: | + export PATH="$(go env GOPATH)/bin:$PATH" + bash src/scripts/mutation-report.sh run + - name: Upsert mutation comment + if: always() + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + GITHUB_REPOSITORY: ${{ github.repository }} + run: bash src/scripts/mutation-report.sh post diff --git a/.github/workflows/pr-verifier.yml b/.github/workflows/pr-verifier.yml index 893dcb6979..c01821d511 100644 --- a/.github/workflows/pr-verifier.yml +++ b/.github/workflows/pr-verifier.yml @@ -94,7 +94,7 @@ jobs: # objected, so it must not be treated more harshly. - name: Login to GHCR continue-on-error: true - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.yml index 4dfd3f8a57..52bea5e10a 100644 --- a/.github/workflows/promote-stable.yml +++ b/.github/workflows/promote-stable.yml @@ -138,7 +138,7 @@ jobs: uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Log in to native GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -192,7 +192,7 @@ jobs: - name: Log in to GHCR as the cross-org publisher if: steps.crosspat.outputs.available == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/stream-image.yml b/.github/workflows/stream-image.yml index 7963972b83..6bf45e2f18 100644 --- a/.github/workflows/stream-image.yml +++ b/.github/workflows/stream-image.yml @@ -111,7 +111,7 @@ jobs: - name: Log in to GHCR if: steps.ref.outputs.push == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/tagged-release.yml b/.github/workflows/tagged-release.yml index 6a2e66ecc6..0faa1e30ba 100644 --- a/.github/workflows/tagged-release.yml +++ b/.github/workflows/tagged-release.yml @@ -576,7 +576,7 @@ jobs: uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Log in to GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -679,7 +679,7 @@ jobs: - name: Log in to GHCR as the cross-org publisher if: steps.crosspat.outputs.available == 'true' - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/v2-ci.yml b/.github/workflows/v2-ci.yml index 614740d5b3..12ef0167d6 100644 --- a/.github/workflows/v2-ci.yml +++ b/.github/workflows/v2-ci.yml @@ -1051,12 +1051,14 @@ jobs: # had passed. The releases CDN stayed up throughout; a pinned URL with a # checksum has no API dependency at all. Bump the version and hash # together, deliberately. + # The CDN itself still 504s transiently (#17357), hence the curl + # --retry flags; sha256sum still gates whatever is fetched. - name: Install just run: | set -euo pipefail JUST_VERSION=1.58.0 JUST_SHA256=4a5cc2f53e6f0f8c59092a6cc38291eb729d46a7dd95d3ae582008881b84931d - curl -fsSL -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" + curl -fsSL --retry 5 --retry-delay 10 --retry-all-errors -o /tmp/just.tgz "https://github.com/casey/just/releases/download/${JUST_VERSION}/just-${JUST_VERSION}-x86_64-unknown-linux-musl.tar.gz" echo "${JUST_SHA256} /tmp/just.tgz" | sha256sum -c - tar -xzf /tmp/just.tgz -C /tmp just sudo install -m 0755 /tmp/just /usr/local/bin/just @@ -1641,7 +1643,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Log in to GHCR - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.gitignore b/.gitignore index 894a37beb9..baa6b80f12 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,6 @@ src/crux/.smoke/ # scratch Chrome profile from src/scripts/dashboard-mobile-shots.mjs .chrome-dashboard-mobile-shots/ + +# Python bytecode caches (e.g. from running .github/scripts locally) +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 2238f78855..ea0469cedb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -276,6 +276,304 @@ Hive did not historically maintain a complete changelog. This file starts a prag - 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-10 (v5.211.18) + +### Fixed + +- crux resumehandle: the claude layout now only captures UUID-named session transcripts, so a newer per-subagent transcript (SESSION/subagents/agent-*.jsonl) no longer yields a bogus "claude --resume agent-…" handle (hivecommons/crux#145) + +## 2026-11-10 (v5.211.17) + +### Fixed + +- crux: `crux serve` request metrics now record `1xx` and `3xx` status classes instead of lumping redirects and informational responses in with `2xx`, and a panicking handler is counted as a `5xx` sample with an error-status span (the span is ended while the panic unwinds, and the panic still propagates to net/http), so redirect-heavy routes no longer inflate the success ratio and crashing handlers no longer vanish from metrics ([hivecommons/crux#142](https://github.com/hivecommons/crux/issues/142)). + +## 2026-11-10 (v5.211.16) + +### Fixed + +- The kick freshness guard now logs a ref it withheld because the re-read found the item closed or merged at INFO with `reason=closed` instead of WARN with the generic `re-read`, so a closed item lingering in a stale snapshot no longer files an `unclassified_error_repeated` self-report every cycle ([#17518](https://github.com/hivecommons/hive/issues/17518)). + +## 2026-11-10 (v5.211.15) + +### Fixed + +- crux: the agent.send_kick span records agent.name only after the kick target resolves, so caller-supplied unknown names no longer become an unbounded span attribute (hivecommons/crux#141) + +## 2026-11-10 (v5.211.14) + +### Fixed + +- `check-docs-links.py` (the `relative links and anchors resolve` CI check) no longer treats Markdown link syntax quoted inside an inline code span as a real link, so a changelog entry such as the one for #17450 that shows a `Generated by [](…/actions/runs/)` template no longer turns the default branch's Docs Link Check red after a release. + +## 2026-11-10 (v5.211.13) + +### Fixed + +- The contributor lane now posts `/ok-to-test` once per head on a fork PR it admitted whose author is not an org member or collaborator, when the repository is Prow-managed, the PR has no `ok-to-test` label and Prow has reported no presubmit on the head ([#17474](https://github.com/hivecommons/hive/issues/17474)). Previously Prow's trigger plugin never ran its presubmits on such a PR, so Tide reported `Jobs … have not succeeded` on a head that was green on GitHub Actions until a person posted the command (#17359 sat about four hours). If Prow rejects the App (`Cannot trigger testing until a trusted user`), the lane logs `skipped=prow-rejects-bot-commands` once, leaves one needs-human note and stops posting on that PR. + +## 2026-11-10 (v5.211.12) + +### Fixed + +- Stage labels: a PR one of the repository's own workflows opened under a user PAT (its body names a `Generated by [](…/actions/runs/)` run of that repo on the PR's own server) is now `author/clanker` instead of `author/human`, so it takes the 072 / adoption path instead of parking at 071 waiting on a push from the PAT's owner (#17450). + +## 2026-11-10 (v5.211.11) + +### Fixed + +- dashboard: fold the human-gate verbs at render time; keeps its 44px tap target (#17515) + +## 2026-11-10 (v5.211.10) + +### Changed + +- Activity Monitor: every row a person must settle now carries exactly one human-gate control — a segmented `👤 Needs human · ` pill whose verbs are fixed per reason (review: Approve · Request changes… · Let hive decide; decision: Decide… · Approve as-is · Let hive decide; sentinel: Confirm safe · Let hive decide; hold: Release hold · Let hive decide; stacked reasons union, ≤ 3 visible + `…`). "Needs human", "Held · sentinel" and "Sentinel alert · needs human" never ride a chevron any more — the lit chevron is the real stage with the amber outline — the scattered `sentinel` chip / `Approve ▸` / `Let hive decide ▸` are folded into the pill, secondary rows of a shared PR render no gate (their *decision pending on #N* chip links to the primary row), and a new `POST /api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` endpoint gives a sentinel alert its own answer (hivecommons/hive#17470). + +## 2026-11-10 (v5.211.9) + +### Fixed + +- Dashboard: the Activity Monitor's CI chevron no longer stays lit as running after every check on the head has concluded. A required check that never produced a run is a settled word (*hasn't reported*), never inferred motion from a part-filled tally; at `060 reviewed` with all reported checks concluded, Review is the lit chevron and CI is its blocker only when red. A CI snapshot that still claims a check running or queued after `dashboard.stage_tracker.ci_activity_stale_m` (default 10 minutes) is re-listed from GitHub on the next tracker build regardless of the batch cache, ETag or stage. ([#17508](https://github.com/hivecommons/hive/issues/17508)) + +## 2026-11-10 (v5.211.8) + +### Fixed + +- Security: a `sec-check` agent configured at `ISSUES_PRS_MERGE` (or `autonomous`) now mints a new `sec-check-trusted` token tier — the trusted set plus Dependabot alerts read — so `dependabot/alerts` no longer returns 403; the grant stays optional and role-scoped. ([#17496](https://github.com/hivecommons/hive/issues/17496)) +- Edits to `/etc/hive/hive.yaml` on hub-provisioned spokes provisioned (or re-applied) after this change now survive a pod restart: the config path is a link to the persisted `/data/hive.yaml.runtime` instead of a throwaway `emptyDir` copy; existing spokes need their deployment re-applied (hub upgrades do not rewrite the init command). Startup logs which file is the boot source of truth, and `/api/config/export` reports it as `metadata.persisted_path`. + +## 2026-11-10 (v5.211.7) + +### Fixed + +- CI: the advisory `mutation` check now mutates only the lines a PR adds (`gremlins --diff`, run from inside each changed package so paths match) instead of every file under the changed package, so PRs touching large packages such as `pkg/dashboard` or `pkg/github` no longer hit the 20-minute job limit and show a red check that never judged the change. ([#17463](https://github.com/hivecommons/hive/issues/17463)) +- Dashboard: an Approve on a Prow repo now reads Prow's reply to the relayed `/lgtm` + `/approve` and says Prow rejected them instead of showing "approved" (#17475, part of #17451). +- Dashboard: when a required check on a Prow repository has never reported (or is only a pending commit status), the stage tracker's CI chevron now quotes Tide's status description in its tooltip ("Not mergeable. Jobs … have not succeeded.") and links to Tide's page when the check has no link of its own, so a presubmit that never ran no longer looks like a failing check. Tide stays out of the pass/fail tally. ([#17476](https://github.com/hivecommons/hive/issues/17476)) +- Activity Monitor: the CI chevron no longer counts Prow's `tide` merge-gate status (or `enforce-guardrails` / DCO) as a check, so a PR whose tests are all green reads `CI 18/18` instead of `CI 18/19 · 'tide' running` and the lit stage moves on to Review / Merge queue; merge eligibility still enforces the gates. +- Activity Monitor: a PR deferred to a fleet-wide `[shared-ci]` incident now reads *Waiting on shared CI · #N* with the incident linked and a tooltip that names the failing check and promises the lift, instead of *Deferred · by scanner*; a plain deferral's tooltip leads with the agent's reason. The shared-CI rerun sweep now treats a newest run that concluded `cancelled` (a job cut off by `timeout-minutes`) as red, re-runs it once when the incident closes and comments *Shared-CI incident #N closed — re-running ``* (``), so a PR like hive#17471 no longer sits deferred after the incident is over (#17500). + +## 2026-11-10 (v5.211.6) + +### Fixed + +- Agent: the token-restart give-up diagnosis ("the agent is still at a login prompt") now logs once per give-up episode instead of once per pane flap; the per-boot re-arm keeps the latch while the rolling 24h restart window is still full (#17483). + +## 2026-11-10 (v5.211.5) + +### Fixed + +- Editing `hive.yaml` on a busy hive now takes effect: a config hot-reload no longer waits behind a whole governor cycle but is applied before that cycle's state persist, so the persist (which also rewrites `hive.yaml`) saves the reloaded config instead of the one the cycle started from, and the shutdown persist now takes the config lock so it cannot race a reload. If any other save (hub heartbeat, dashboard, agent pause) wrote the pre-reload config to `hive.yaml` while the reload was waiting, the reloaded config is saved back once it is applied ([#17467](https://github.com/hivecommons/hive/issues/17467)). + +## 2026-11-10 (v5.211.4) + +### Fixed + +- Activity Monitor: a PR parked at `stage/085-needs-decision` whose head is short of merge-ready (checks running, red or unreported; review verdict pending or asking for a person) now lights its real stage — the CI or Review track, with an amber human-gated marker — and carries the ask as the **needs human decision** pill (question in the hover, decision popover on click) instead of forcing a *Needs human · decision* chevron into the PR in progress column while CI and Review spun dim (#17442, #17416). PR in progress is passed, Merge queue stays empty; one lit stage per row. + +## 2026-11-10 (v5.211.3) + +### Fixed + +- The knowledge advisor_llm endpoint is now path-aware: an endpoint already ending in `/chat/completions` is used as-is and a `/v1` base gets `/chat/completions`, so the Copilot chat API (`https://api.githubcopilot.com/chat/completions`) works without a `?_=` query hack. Bare-host endpoints behave as before. + +## 2026-11-09 (v5.211.2) + +### Changed + +- A new [fork PR presubmit stall runbook](https://github.com/hivecommons/hive/blob/v5/src/docs/fork-pr-presubmit-stall-runbook.md) documents how to tell a missing Prow presubmit from a failing one and how to clear it with `/ok-to-test`, and what to do when dashboard-relayed `/lgtm` and `/approve` are rejected; the code fixes remain open in [#17451](https://github.com/hivecommons/hive/issues/17451). + +### Fixed + +- The merge train's one-PR-per-issue and same-issue claim-conflict holds now judge only heads at the merge gate ([#17439](https://github.com/hivecommons/hive/issues/17439)). A PR whose CI is still running or whose review is outstanding is evaluated as usual, so its tracker row reads CI / Review instead of "needs human decision · Let hive decide", and it is held at the merge point only if it gets there. The first same-issue PR at the merge point keeps the issue and that pick stands until it closes or is blocked for good, so a check going red mid-run no longer flips the winner and two PRs no longer wear each other's number as `duplicate-of`. +- The sec-check agent's Dependabot alerts call no longer 403s once the GitHub App is granted the new read-only Dependabot alerts permission (documented in the GitHub App setup guide); existing installations must re-accept it once. Only the sec-check role's token requests the grant — other agents' tokens are unchanged. +- hub: hives whose spoke reports `forge_unreachable` are labelled "forge unreachable (github_host)" instead of generic stale badges, and the condition no longer counts against their health or advisory status + +## 2026-11-09 (v5.211.1) + +### Changed + +- Activity Monitor: the **Merge queue** column header, its chevron, the merge-train chip and the Merge queue popover now wear a "merge" traffic-sign glyph (an up arrow with a lane curving in from the lower right, like the W4-1 road sign) instead of the railcar, which read as a tram front. Same inline SVG, `currentColor`, hover *Merge queue*. +- Refreshed the model list-price table from OpenRouter (3 rows moved; list prices as of 2026-11-09); the Cost panel estimate now uses the new rates. The `kimi-k3` row keeps its prior value: the OpenRouter quote (0.192 in / 16.00 out) is a catalogue anomaly the reconciler's plausibility guard now holds for review. + +### Fixed + +- Dashboard: the page no longer drifts away from the section you are reading when other panels grow or shrink. A ResizeObserver-driven scroll stabilizer now pins the topmost visible section (or agent card) across every repaint path, not just the main status render. +- An unreachable GitHub (Enterprise) host no longer makes every hub heartbeat stale: the github_auth health probe now runs under its own 3s sub-budget, reports its last cached result, and the heartbeat carries a new `forge_unreachable` field; the fleet-stats collector backs off exponentially up to 15 minutes during a forge outage and logs one WARN when it starts failing and one INFO on recovery instead of a WARN per retry ([#17427](https://github.com/hivecommons/hive/issues/17427)). +- The merge train's one-PR-per-issue rule now groups candidates by base branch, so the same fix opened against two release lines (v5 and v6, both `Fixes #N`) is no longer held as a duplicate and shown as "needs human decision"; the same-issue claim-conflict pass likewise ignores claimants on another base branch. Two PRs for one issue on the same line still compete as before ([#17436](https://github.com/hivecommons/hive/issues/17436)). +- Activity Monitor: while CI or review runs, the stage chevron keeps its neutral settled-current fill — the Open-column draft / blocked / New / stale tints no longer paint a second coloured chevron beside the running track (a draft PR with no stage read as slate Open + amber CI). + +## 2026-11-09 (v5.211.0) + +### Added + +- **Red-team agent (`redteam`, opt-in at L5/L6).** A new lane plays a malicious contributor — a human, an AI, or one posing as the other — and writes the issues, PR bodies, review comments and RFC text such an actor would use to get agents to write malicious code or lower the hive's defenses. It measures them against the deterministic defenses by adding attack cases and benign controls to the `ioscan` red-team corpus in `hold`-labelled PRs, with each outcome recorded as observed, and never posts attack text anywhere else ([#17420](https://github.com/hivecommons/hive/issues/17420)). It ships paused in every governor mode, and an agent whose role or base name is `redteam` serves **no** repository until it has a `repos:` scope: the proxy and every write relay refuse it, its kick lists no repositories or work, and the boot log warns. Scope it to the repository holding the corpus and give it a cadence to turn it on; see `src/docs/redteam.md`. + +### Changed + +- Advisory digest: the one `hive:advisory-digest` comment on the pinned advisory issue is edited in place (marker + `Updated N times · last ` footer, counter read back from the comment) and a *changed* digest is rewritten at most once per `governor.advisory.digest_min_interval` (default `1h`, Settings → Advisory). Unchanged digests never write; the baseline is the comment's own `updated_at` on GitHub, so a restart does not repost inside the window. On hive's own spoke this collapses a rewrite every ~5 minutes into one per hour. New log line `advisory digest comment written` marks real writes. + +### Fixed + +- ci(scorecard): skip push runs on non-default branches (v5) (#17414) +- The ingress-nginx error backend (`src/deploy/k8s/error-pages.yaml`) now reflects an intercepted 403 or 404 as that status with a dedicated "Page not found" document (HTML or JSON by caller) instead of falling through to the 503 "Hive is restarting" page with an auto-refresh. With the controller's global `custom-http-errors` list including 404, every missing URL on the hub had been served as a 503, which Google Search Console reported as Soft 404 and which told visitors a healthy hub was down ([#17431](https://github.com/hivecommons/hive/issues/17431)). The global list is documented as `502,503,504`. +- ci: Scorecard `push` runs on non-default release branches are skipped instead of failing; `schedule` and `workflow_dispatch` runs are unchanged ([#17392](https://github.com/hivecommons/hive/issues/17392)). + +## 2026-11-09 (v5.210.0) + +### Added + +- ci: advisory gremlins mutation-testing job comments surviving mutants on PRs that change Go code (#17349). + +### Fixed + +- crux: WaitReady now surfaces the health route's last answer (e.g. "tmux not found on PATH") instead of a bare deadline error, and returns promptly on a 503 unavailable verdict. +- The dashboard `data_disk` check no longer warns every spoke on shared node-root image pressure: when `/data` reports an implausible size and the sampler falls back to the node root, that sample is informational below 95% and only still fails at ≥95%, where kubelet DiskPressure eviction hits the pod regardless of who owns the disk. + +## 2026-11-09 (v5.209.8) + +### Fixed + +- Crux `GET /v1/health` now reports a `tmux` field (where tmux resolves on PATH) and answers 503, with the full health body, when tmux is missing (the body also carries `error`/`code`, so `api.Client` callers and the supervisor see "tmux not found on PATH" rather than a bare 503): every agent runs in tmux, so a server without it cannot serve traffic and was reporting healthy ([hivecommons/crux#137](https://github.com/hivecommons/crux/issues/137)). Existing fields are unchanged; probes that treated any 200 as healthy now see the failure. + +## 2026-11-09 (v5.209.7) + +### Fixed + +- Crux's command log (`GET /v1/runs/{id}/cmdlog`) no longer pins a follower's `next_seq` forever ([#17410](https://github.com/hivecommons/hive/issues/17410)). A command that ended `unfinished` (the launcher failed without an exit the runtime could read) is now terminal, so `next_seq` moves past it; a command left in flight by a runner that died is ended `unfinished` when its log is next opened, which `crux serve` now does for every run it reconciles at start; and `more` is never true on a page whose `next_seq` did not move, so a "page while `more`" loop such as `crux cmdlog list --all` can no longer spin on the same request. + +## 2026-11-09 (v5.209.6) + +### Fixed + +- Self-authored automerge sweeps no longer file repeated-error self-reports for expected destination merge contention; local warnings and reporting of other failures are preserved ([#17400](https://github.com/hivecommons/hive/issues/17400)). + +## 2026-11-09 (v5.209.5) + +### Fixed + +- crux cmdlog: a follower polling with next_seq now receives a command's ended record instead of seeing it as unfinished forever (#17398). + +## 2026-11-09 (v5.209.4) + +### Security + +- The maintainer-notes store (`/data/maintainer-notes.jsonl`, the private per-item notes the dashboard's Activity monitor shares between maintainers) is now created owner-only (0600) and an existing file left wider by an earlier release is tightened on its next write ([#17386](https://github.com/hivecommons/hive/issues/17386)). It was created 0644 under a world-traversable `/data`, so any agent UID on the spoke could read every note on every item — including deleted ones — rather than only the capped, per-item section a kick deliberately carries. + +## 2026-11-09 (v5.209.3) + +### Changed + +- The weekly price-table refresh now holds implausible OpenRouter quotes (a field moving more than 5×, an output/input ratio above 30, or a cache-read rate at or above 90% of input) instead of applying them: the current row is kept, `priceTableDate` is still bumped so the run opens a refresh PR even when no other row moved, and that PR lists the row under "Held for review" with the rule that fired, so a catalogue defect like the `kimi-k3` row in #17354 reaches a human as a question rather than a change (#17364). + +## 2026-11-09 (v5.209.2) + +### Fixed + +- The crux serve request metrics and spans (`crux.serve.request.duration`, `crux.serve.requests`) now bound their HTTP method attribute to the standard set (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, CONNECT, TRACE), recording anything else as `_OTHER`, as OTel HTTP semconv does for `http.request.method` ([hivecommons/crux#135](https://github.com/hivecommons/crux/issues/135)). Previously the client-supplied method was recorded verbatim, so any caller could mint unbounded metric series on the host's metrics backend simply by sending arbitrary method tokens. +- The review-dispatch starvation-guard promotion WARN is no longer reported by the fleet feed as a repeated unclassified runtime error ([#17366](https://github.com/hivecommons/hive/issues/17366)). + +## 2026-11-09 (v5.209.1) + +### Security + +- Crux agent steps now refuse a `prompt_path` file, and ignore a codex answer file, over 16 MiB (`agentstep.MaxPromptFileBytes`): both were read whole into the crux server's memory with no bound, so a run owner or the sandboxed agent itself could make the host allocate without limit; an oversize prompt file is a 400 naming the bound and an oversize answer file falls back to the last message on stdout, as a missing one already did. + +## 2026-11-09 (v5.209.0) + +### Added + +- Activity monitor: a red PR the hive deferred now reads **Deferred · waiting on #N** (first successor, `+N` for more; *Deferred · by scanner* when none is named) in plain amber instead of **Unassigned · next: …**, which sent operators to investigate work the hive had already decided ([#17347](https://github.com/hivecommons/hive/issues/17347)). The issue-request relay records a hive agent's PR comment that defers the PR (*Deferring …*, *Deferred …*, *Waiting on #N*) as an `agent_pr_deferred` audit entry bound to the PR's head, with the successors it names and the deferral's own words; the tooltip carries the reason, every successor and the first one's link. A fix kick, claim or push for the same head after the deferral returns the row to *Remediating* / *Fix pushed*, and a new head clears it. When the deferral says a maintainer may close the PR, the row leads with **Close now** (closes the PR as won't-fix with an attributed note). + +## 2026-11-09 (v5.208.1) + +### Fixed + +- Fleet report: the Copilot hang detector's repeated `copilot hung with no CLI prompt, running diagnostic` WARNs — a Copilot agent showed no CLI prompt 180 s after launch, so the hive killed its session, ran a bare `copilot` diagnostic and relaunched it — and the diagnostic's own `timed out waiting for copilot error output` WARNs are now classified as `copilot_cli_hung` (medium, component `agent-runtime`), so a hive whose Copilot agents keep failing to reach their prompt files one self-report that names the condition instead of `unclassified_error_repeated` ([#17353](https://github.com/hivecommons/hive/issues/17353)). + +## 2026-11-09 (v5.208.0) + +### Added + +- Added `github.Client.ProcessPRRequestDirOnce` to run one PR-request watcher pass on a given dir, authorizer and clock, with a regression test for epic-driven PRs on contributor-claimed, PR-covered issues (#17302). + +## 2026-11-09 (v5.207.5) + +### Changed + +- Activity Monitor: the issues one PR closes together are now one group of the list — the secondary rows sit right after their primary (indented on a rail), render from the primary's own PR snapshot, and fold under a caret on the primary's "also closes" pill (remembered in localStorage). + +### Fixed + +- Activity Monitor: a row lights exactly one stage chevron. When a push lands during review, CI is the lit chevron and Review is dim with a muted "re-review queued" note instead of a second amber chevron; the base-refresh detail line reads in plain words (no "preparation"/"unverified" jargon, each signal said once); the muted `stage ↓` pill now reads "stage reset" / "stage reset by push" (#17335). + +## 2026-11-09 (v5.207.4) + +### Changed + +- Contributor nudge: CI-failure nudges are keyed on the failing-check set, not the lane's reason prefix — the same set on a new head or a check joining the set on the same head edits the PR's one `hive:contributor-nudge` comment (no relay re-dispatch for the same head), and a changed set within `governor.labels.stage.contributor_nudge.ci_failure_cooldown` (default 6h) folds into it instead of counting as a fresh nudge. The ledger persists in the stage-label store across restarts. +- activity monitor: sentinel alerts and `hold`-class labels are gates, not stages — a PR's column now follows its real progress (CI, Review, Merge queue) and the gate rides along as an amber **Held · sentinel · confirm intent** / **Held · hold** pill with the route reason in its tooltip and the decision popover, instead of pinning every such PR at `stage/085-needs-decision`; the gate stays a hard merge stop (lanes and the dashboard's human-merge shortcuts refuse on the label itself, never on the stage) and the 090 entry comment says "Held: …" (hivecommons/hive#17327). + +## 2026-11-09 (v5.207.3) + +### Fixed + +- dashboard: the Recent merges popover is 52rem wide (was capped at 34rem) so PR titles read instead of ellipsising; it stays right-anchored under the Merged pill, capped to the viewport and its bar, and the phone full-width sheet is unchanged. +- Activity Monitor: a secondary issue that shares a PR with another issue (its row shows the compact "↳ #PR · under #primary" chip) now lights the PR's lane — CI / Review, Merge queue (soaking), Merged — like the primary row, instead of wearing the PR's stage word in the "PR in progress" lane (hivecommons/hive#17324). +- Watchdog no longer pages `PaneShowsLogin` for the sub-second login flash a relaunched Copilot CLI paints while re-validating its token: boot grace is now dated from the most recent CLI (re)launch, and login chrome must persist for `governor.watchdog.liveness.login_streak` consecutive polls (default 3) before `auth-required` is raised. + +## 2026-11-09 (v5.207.2) + +### Fixed + +- The fleet selfreport feed no longer files a repository's oversized AGENTS.md as an unclassified runtime error, and the scheduler's injection-cap warning now reports the effective cap instead of the config default sentinel (#17318). + +## 2026-11-09 (v5.207.1) + +### Fixed + +- hive-open-pr and the PR-request watcher now refuse a Fixes/Closes target that another principal has claimed or covered with an open PR, and post one deduplicated notice on the issue; the same gate denies a claim or start comment on such an issue before the start is booked (#17298). + +## 2026-11-09 (v5.207.0) + +### Added + +- `hive-open-issue --claim` files and claims a self-filed issue in one request (claimed-by label, `help wanted` removed, failures reported as `claim_error`); an issue a hive agent files without `--claim` is marked filed-for-outside-help and that agent's later claim of it is refused ([#17299](https://github.com/hivecommons/hive/issues/17299)). + +## 2026-11-08 (v5.206.3) + +### Fixed + +- contribute: when a relay contributor's lease ends while their own open PR covers the issue, the claim is now kept as a PR-held claim by the same contributor until that PR merges or closes, instead of being released with `lease revoked` and leaving the issue looking unclaimed to dispatch, the PR-request gate and the claim listing ([#17300](https://github.com/hivecommons/hive/issues/17300)). + +## 2026-11-08 (v5.206.2) + +### Fixed + +- hold guard no longer logs a WARN every tick when a held PR's base refresh is deliberately deferred to the automerge preparation front; the deferral is logged at debug level and no longer trips the selfreport error classifier. + +## 2026-11-08 (v5.206.1) + +### Security + +- crux agentstep: step prompt/answer file access on the host now goes through an os.Root at the workspace, so a symlink inside a provisioned worktree (or one planted by the sandboxed agent) can no longer read or write host paths outside it ([#17293](https://github.com/hivecommons/hive/issues/17293)). A `prompt_path` that resolves outside the workspace is refused with the existing "must be relative to the workspace and stay inside it" 400. + +## 2026-11-08 (v5.206.0) + +### Added + +- The GitHub conditional-request (ETag / 304) response cache is now sized by `github.etag_cache_max_mb` and `github.etag_cache_max_entries` (env `HIVE_GITHUB_ETAG_CACHE_MAX_MB` / `HIVE_GITHUB_ETAG_CACHE_MAX_ENTRIES`), editable under Settings → Forge App and applied without a restart. The built-in default rises from 64 MiB / 4096 entries to 128 MiB / 8192 entries, cached bodies are stored gzip-compressed so the cap holds several times as many responses, and `/api/gh-rate-limits` plus the Debug → GitHub API budget panel show the cache's fill level (`bytes` / `max_bytes` / `max_entries`) so an operator can see eviction pressure before the hit rate slides. + +### Security + +- crux: a contained run's `workspace_path` is now checked against `workspace_roots` after resolving symlinks, and the run mounts the resolved directory ([#17029](https://github.com/hivecommons/hive/issues/17029)). Previously the root check was lexical, so a symlink under a workspace root — one a previous run could plant in its read-write workspace — pointing at `/` passed the check and the backend mounted the link's target read-write. Such a request is now refused with 403 (`resolves outside this server's workspace_roots`); roots that are themselves reached through a symlink keep working. + +## 2026-11-08 (v5.205.0) + +### Added + +- crux: saved run results complete, the seventh work service of the Crux work-services RFC ([hivecommons/crux#114](https://github.com/hivecommons/crux/issues/114) S7). A finished run can now be re-run with `POST /v1/runs/{id}/restart` (`crux --server … runs restart`): the server re-validates the request the run was accepted with as its original owner against the current configuration, links the two records (`restarted_from` / `restarted_by`), audits the restart with its reason, and refuses with `409 conflict` while the old run is still live so two drivers never resume one task. `GET /v1/runs` lists the caller's runs newest first (the operator's view is every run; `?status=` and `?limit=` narrow it), `GET /v1/runs/{id}/history` is the record's status transitions, and a `crux serve` restart now settles the `running` steps of an unfinished session to `unfinished` alongside the run. `crux runs list|restart|history` round out the CLI. + ## 2026-11-08 (v5.204.1) ### Fixed diff --git a/README.md b/README.md index f18fc07950..353f16f2aa 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@

Get started · Overview · + How Hive works (video) · Community

@@ -139,7 +140,7 @@ Use official images from `ghcr.io/hivecommons/hive`. ## Community -[First contribution](docs/getting-started-contributing.md) · [Contributing](CONTRIBUTING.md) · [Contribute compute](src/docs/contributor-relay.md) · [Discord](https://hivecommons.dev/discord) · [Community meeting](https://docs.hivecommons.dev/docs/community/meetings) · [Live stream (Twitch)](https://www.twitch.tv/hivecommons) · [Discussions](https://github.com/hivecommons/hive/discussions). +[How Hive works (video)](https://www.youtube.com/watch?v=uo1KGTyJJyU) · [First contribution](docs/getting-started-contributing.md) · [Contributing](CONTRIBUTING.md) · [Contribute compute](src/docs/contributor-relay.md) · [Discord](https://hivecommons.dev/discord) · [Community meeting](https://docs.hivecommons.dev/docs/community/meetings) · [Live stream (Twitch)](https://www.twitch.tv/hivecommons) · [Discussions](https://github.com/hivecommons/hive/discussions). [Code of Conduct](CODE_OF_CONDUCT.md) · [Project governance](GOVERNANCE.md) · [Report a vulnerability](SECURITY.md) · [Telemetry](src/docs/telemetry.md). diff --git a/changed-gate-fold-tap-target.md b/changed-gate-fold-tap-target.md new file mode 100644 index 0000000000..e47dc05587 --- /dev/null +++ b/changed-gate-fold-tap-target.md @@ -0,0 +1 @@ +Activity Monitor: the human-gate pill folds its verbs at render time (three on the strip tier, one plus `…` at ≤1100px), keeps the folded verbs in a template until `…` opens, and gives the `…` button its 44px tap target — the row holds no hidden buttons for the header-geometry probe to reject. diff --git a/changelog.d/changed-v6-topup-from-v5-20261110.md b/changelog.d/changed-v6-topup-from-v5-20261110.md new file mode 100644 index 0000000000..ec8667279f --- /dev/null +++ b/changelog.d/changed-v6-topup-from-v5-20261110.md @@ -0,0 +1 @@ +- v6 carries every v5 change through v5.211.18: the hosted spoke's `/etc/hive/hive.yaml` is durable, a shared-CI deferral names the incident it waits on and lifts when it closes, the CI chevron ignores Prow's `tide` merge-gate status and re-lists a head whose snapshot claims a check still running after `dashboard.stage_tracker.ci_activity_stale_m`, Prow's rejection of a relayed `/lgtm` + `/approve` is surfaced, and a hold-class label or sentinel alert rides a PR's real stage as a gate pill instead of parking it at 085. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 047729af75..8897966794 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -31605,6 +31605,122 @@ } } }, + "/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm": { + "post": { + "tags": [ + "Status" + ], + "summary": "Confirm a sentinel finding safe on one issue or pull request from the activity monitor", + "description": "Backs the human-gate pill's Confirm safe verb on a row carrying the sentinel label. Posts a comment marked `` naming the signed-in operator (plus their words when given), then removes the configured sentinel label so the merge gate no longer holds the item; when the label is already gone the comment is still posted and the response says alreadyClear. Same authorisation as the hold toggle plus a signed-in GitHub user; every confirmation is written to the audit log as repo_item_sentinel_confirm.", + "parameters": [ + { + "name": "owner", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "number", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "comment": { + "type": "string", + "description": "Optional: why the finding is safe; posted with the confirmation" + }, + "type": { + "type": "string", + "enum": [ + "issue", + "pr" + ], + "description": "Row kind for the result wording; defaults to issue" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Finding confirmed safe", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "repo": { + "type": "string" + }, + "number": { + "type": "integer" + }, + "label": { + "type": "string", + "description": "The configured sentinel label" + }, + "removed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Sentinel labels removed from the item" + }, + "alreadyClear": { + "type": "boolean", + "description": "No sentinel label was on the item; only the comment was posted" + }, + "result": { + "type": "object", + "description": "Shared row-action outcome for the dashboard toast" + } + } + } + } + } + }, + "400": { + "description": "Invalid request body" + }, + "401": { + "description": "GitHub user session required" + }, + "403": { + "description": "Repository write permission required" + }, + "502": { + "description": "GitHub mutation failed" + }, + "503": { + "description": "GitHub client not configured" + } + } + } + }, "/api/notes": { "get": { "tags": [ diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..d8104be8c1 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,51 @@ +# docs/ + +This directory holds contributor guides, design records and some older pages. +The current documentation lives in [`src/docs/`](../src/docs/); its full +catalogue is the [documentation map](../src/docs/documentation-map.md). Start +there unless you are looking for one of the pages below. + +## Start here + +- [Getting started as a first-time contributor](getting-started-contributing.md) — the end-to-end path for a first code or documentation contribution. +- [Local development](development.md) — prerequisites, build and test loop for the Go codebase. +- [Hive Commons repositories](repositories.md) — the sibling repositories developed alongside Hive. + +## Running and configuring agents + +- [Agent backend setup](backend-setup.md) — setup notes for the agent CLI backends. +- [Inference backends](inference-backends.md) — routing agents through OpenAI-compatible model gateways. +- [Running Goose unattended at scale with Hive](goose-at-scale.md) +- [Hive Hub — Backup & Disaster Recovery](HUB_DISASTER_RECOVERY.md) +- [Runs](runs.md) — how a run is represented as a staged task lease. +- [Readiness-first preparation](readiness-preparation.md) +- [Weekly competitor report grounding](weekly-competitor-report.md) +- [Outreach anti-spam and deduplication ruleset](outreach-antispam.md) + +## Design records and RFCs + +Proposals and designs here are not commitments; check each page for its status. + +- [Hive Federation](federation-design.md) +- [RFC #4002: Re-entrant conversation-as-state turn model](rfc-4002-reentrant-conversation-state.md) and its [phased delivery roadmap](rfc-4002-phased-roadmap.md) +- [RFC #5691: Constellation hubs and coordinated spokes](rfc-5691-constellation.md) +- [RFC #5698: Backend capacity, model inventory, pacing, and placement](rfc-5698-backend-capacity-model-inventory-placement.md) +- [RFC #6825: Capability-aware contributor task assignment](rfc-6825-capability-aware-contributor-task-assignment.md) +- [RFC #17054: LLM-ranked knowledge advisor](rfc-17054-llm-ranked-knowledge-advisor.md) +- [Contribute-app distribution roadmap](contribute-distribution-roadmap.md) +- [Proposed upstream issue: Goose-at-scale guide](goose-at-scale-upstream-proposal.md) +- [OpenAI Symphony specification alignment review](design/symphony-spec-alignment.md) +- [Hive: Hub & Spoke presentation](presentations/hive-hub-and-spoke.html) (HTML slides) + +## Moved or retired + +These pages are kept so existing links keep working. Do not use them for the +current deployment. + +- [Architecture](architecture.md), [Hive landscape and positioning](landscape.md) and [Advisory digest staleness](advisory-staleness.md) — redirects to their `src/docs/` pages. +- [Legacy v1 architecture](LEGACY-v1-architecture.md), [macOS support (launchd)](macos.md) and [Troubleshooting](troubleshooting.md) — retired v1 documentation. +- [Migrating from Hive v1 to v2](migration-v1-v2.md) — historical; both ends of the migration are retired. + +## Other + +- [`readme/`](readme/README.md) — graphics and chart data used by the root README. diff --git a/src/Dockerfile b/src/Dockerfile index d961508afc..92afd97605 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -335,7 +335,7 @@ RUN npm install -g --ignore-scripts --no-fund --no-audit @openai/codex@${CODEX_V echo "WARN: OpenAI Codex CLI install failed — skipping" # --- Layer 7: Claude Code (most frequent updates) --- -ARG CLAUDE_CODE_VERSION=2.1.319 +ARG CLAUDE_CODE_VERSION=2.1.322 # --ignore-scripts (kept, deliberately: no arbitrary postinstall runs during the # build) skips claude-code's install.cjs, which is what LINKS the platform # native binary into the package's bin/. The binary itself ships in the @@ -356,9 +356,9 @@ RUN npm install -g --ignore-scripts --no-fund --no-audit @anthropic-ai/claude-co # Installs from the OFFICIAL aaif-goose/goose repo, pinned to a fixed release and # SHA-256-verified before extraction. Download failures are tolerated because # Goose is an optional backend; checksum mismatches must hard-fail the build. -ARG GOOSE_VERSION=1.57.0 -ARG GOOSE_SHA256_AMD64=10eb96cb6a159b6e1d38eeedbef6ab64cd28168aad91948f1fa5c34eefdf98e3 -ARG GOOSE_SHA256_ARM64=c32605acfd560aeb2adbf17ec359cc0217e28022a7e647b35a6af5dcfca91749 +ARG GOOSE_VERSION=1.58.1 +ARG GOOSE_SHA256_AMD64=43adae6abf10d40d5b1d5cd23bcf6481ef72fddede8fe9a8577c385e325cba68 +ARG GOOSE_SHA256_ARM64=20d9586ac7d37d2700d41d85d0051547a959ae96576aae6cbd290f77b5605a61 RUN ARCH="${TARGETARCH:-$(dpkg --print-architecture)}" && \ case "$ARCH" in \ amd64) GOOSE_ARCH=x86_64; GOOSE_SHA256="$GOOSE_SHA256_AMD64" ;; \ diff --git a/src/Dockerfile.contributor b/src/Dockerfile.contributor index 2452b435ed..21d2d2701c 100644 --- a/src/Dockerfile.contributor +++ b/src/Dockerfile.contributor @@ -263,7 +263,7 @@ RUN mkdir -p /etc/apt/keyrings \ # npm cache is cleaned in the same layer it's populated (issue #2613, # Observation 2 "also minor") so the cache doesn't linger in this layer's # diff, mirroring the cleanup already done for the bobshell install below. -ARG CLAUDE_CODE_VERSION=2.1.319 +ARG CLAUDE_CODE_VERSION=2.1.322 ARG COPILOT_VERSION=1.0.88 # --ignore-scripts (kept, deliberately: no arbitrary postinstall runs during # the build) skips claude-code's install.cjs, which is what LINKS the platform @@ -389,9 +389,9 @@ RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \ # build time (sec-check issue #2919). Pin to a specific release tag and verify # the tarball before extraction. Download failures are tolerated because Goose # is an optional contributor backend; checksum mismatches are not tolerated. -ARG GOOSE_VERSION=1.57.0 -ARG GOOSE_SHA256_AMD64=10eb96cb6a159b6e1d38eeedbef6ab64cd28168aad91948f1fa5c34eefdf98e3 -ARG GOOSE_SHA256_ARM64=c32605acfd560aeb2adbf17ec359cc0217e28022a7e647b35a6af5dcfca91749 +ARG GOOSE_VERSION=1.58.1 +ARG GOOSE_SHA256_AMD64=43adae6abf10d40d5b1d5cd23bcf6481ef72fddede8fe9a8577c385e325cba68 +ARG GOOSE_SHA256_ARM64=20d9586ac7d37d2700d41d85d0051547a959ae96576aae6cbd290f77b5605a61 RUN ARCH="${TARGETARCH:-$(dpkg --print-architecture)}" \ && case "$ARCH" in \ amd64) GOOSE_ARCH=x86_64; GOOSE_SHA256="$GOOSE_SHA256_AMD64" ;; \ diff --git a/src/cmd/hive/boot.go b/src/cmd/hive/boot.go index 791b216de4..ed5da1097f 100644 --- a/src/cmd/hive/boot.go +++ b/src/cmd/hive/boot.go @@ -80,7 +80,29 @@ type boot struct { // the governor loop's tick bodies that read cfg. Without it, a reload // racing the fast agent-status tick crashed the process with "concurrent // map read and map write" in buildConfiguredAgents. + // + // The governor loop holds it for a whole tick, so the watcher callback + // never waits for it: submitConfigReload parks the reload in + // pendingReload and the holder applies it at its next safe point via + // lockCfg/unlockCfg (hivecommons/hive#17467). cfgReloadMu sync.Mutex + // reloadApply swaps a reloaded config into cfg and re-syncs the + // subsystems that cache it. Caller holds cfgReloadMu; it returns the + // ACMM level transition to fire once the lock is released. + reloadApply func(*config.Config) (prevACMMLevel, nextACMMLevel int) + // pendingACMM holds ACMM transitions applied under cfgReloadMu that + // unlockCfg fires after releasing it; guarded by cfgReloadMu. + pendingACMM [][2]int + // pendingReloadMu guards pendingReload, the newest reload the watcher + // delivered that has not been applied yet, and parkedSaveSeq, the + // config.SaveSeq() seen when the oldest of those reloads was parked. + pendingReloadMu sync.Mutex + pendingReload *config.Config + parkedSaveSeq uint64 + // configSaveSeq and saveConfig default to config.SaveSeq and cfg.Save; + // tests replace them. + configSaveSeq func() uint64 + saveConfig func() error // sweepConfig is an immutable copy published outside long-running eval IO. sweepConfig atomic.Pointer[config.Config] diff --git a/src/cmd/hive/boot_watchers_deps_test.go b/src/cmd/hive/boot_watchers_deps_test.go index 82fa1595b1..3ee597579c 100644 --- a/src/cmd/hive/boot_watchers_deps_test.go +++ b/src/cmd/hive/boot_watchers_deps_test.go @@ -244,11 +244,13 @@ func TestBootWatchersWith_ReloadWithChangedIdentityRebuildsAuth(t *testing.T) { // A config reload runs on the watcher's timer goroutine and mutates *cfg // (including the cfg.Agents map) that the governor loop's ticks read. It must -// wait for cfgReloadMu, or a reload racing the fast agent-status tick crashes -// the process with "concurrent map read and map write". -func TestBootWatchersWith_ReloadWaitsForConfigLock(t *testing.T) { +// not touch cfg while the loop holds cfgReloadMu, or a reload racing the fast +// agent-status tick crashes the process with "concurrent map read and map +// write". It must not wait for the lock either: the loop holds it for whole +// ticks, which starved hot-reload (hivecommons/hive#17467). The reload is +// parked and applied when the holder releases the lock. +func TestBootWatchersWith_ReloadDefersWhileConfigLockHeld(t *testing.T) { const reloadWait = 5 * time.Second - const blockedCheck = 100 * time.Millisecond f := newBootWatchersFake() cfg := bootWatchersConfig() @@ -265,7 +267,7 @@ func TestBootWatchersWith_ReloadWaitsForConfigLock(t *testing.T) { "scanner": {Enabled: true, Backend: "copilot", Model: "gpt-5.4"}, } - b.cfgReloadMu.Lock() + b.lockCfg() done := make(chan struct{}) go func() { f.onReload(newCfg) @@ -274,22 +276,16 @@ func TestBootWatchersWith_ReloadWaitsForConfigLock(t *testing.T) { select { case <-done: - b.cfgReloadMu.Unlock() - t.Fatal("reload applied while the governor loop held cfgReloadMu") - case <-time.After(blockedCheck): + case <-time.After(reloadWait): + b.unlockCfg() + t.Fatal("reload callback blocked on cfgReloadMu held by the governor loop") } if sameStringSlice(cfg.Project.Repos, []string{"widgets", "reloaded"}) { - b.cfgReloadMu.Unlock() + b.unlockCfg() t.Fatal("reload mutated cfg while the governor loop held cfgReloadMu") } - - b.cfgReloadMu.Unlock() - select { - case <-done: - case <-time.After(reloadWait): - t.Fatal("reload never completed after cfgReloadMu was released") - } + b.unlockCfg() if !sameStringSlice(cfg.Project.Repos, []string{"widgets", "reloaded"}) { - t.Fatalf("repos = %v after reload, want the reloaded list", cfg.Project.Repos) + t.Fatalf("repos = %v after the lock was released, want the reloaded list", cfg.Project.Repos) } } diff --git a/src/cmd/hive/cfg_reload.go b/src/cmd/hive/cfg_reload.go new file mode 100644 index 0000000000..941dbee0b6 --- /dev/null +++ b/src/cmd/hive/cfg_reload.go @@ -0,0 +1,125 @@ +package main + +import "github.com/hivecommons/hive/pkg/config" + +// submitConfigReload is the config watcher's callback. The governor loop +// holds cfgReloadMu for a whole tick (minutes on a busy spoke), so waiting +// for it starved hot-reload, and every save made from the in-memory config +// in the meantime (the tick's persistState, whose +// Config.ReconcilePausedAndSave rewrites hive.yaml) wrote the pre-reload +// config over the operator's edit (hivecommons/hive#17467). The reload is +// parked instead: applied now when the lock is free, otherwise by the holder +// at its next safe point, which is always before the tick's persist. Only the +// newest parked reload is applied; each one is a full file. +// +// Savers that run without cfgReloadMu (heartbeat callbacks, dashboard +// mutations, the pause callback) can still write the pre-reload config to +// hive.yaml while the reload is parked. config.SaveSeq() is recorded at park +// time so applyPendingReloadLocked can detect that and save the reloaded +// config back to disk. +func (b *boot) submitConfigReload(newCfg *config.Config) { + b.pendingReloadMu.Lock() + if b.pendingReload == nil { + b.parkedSaveSeq = b.currentSaveSeq() + } + b.pendingReload = newCfg + b.pendingReloadMu.Unlock() + if !b.cfgReloadMu.TryLock() { + if b.logger != nil { + b.logger.Info("config reload deferred until the governor cycle reaches a safe point") + } + return + } + b.unlockCfg() +} + +// lockCfg acquires cfgReloadMu and applies any parked reload, so the work +// that follows reads the newest config. +func (b *boot) lockCfg() { + b.cfgReloadMu.Lock() + b.applyPendingReloadLocked() +} + +// unlockCfg applies any parked reload, releases cfgReloadMu and fires the +// ACMM transitions those reloads caused. A reload parked after the last check +// but before the release (its TryLock failed against us) is picked up by the +// loop, so a parked reload is never stranded. +func (b *boot) unlockCfg() { + for { + b.applyPendingReloadLocked() + transitions := b.pendingACMM + b.pendingACMM = nil + b.cfgReloadMu.Unlock() + for _, t := range transitions { + b.onACMMLevelChanged(t[0], t[1]) + } + if !b.hasPendingReload() || !b.cfgReloadMu.TryLock() { + return + } + } +} + +func (b *boot) hasPendingReload() bool { + b.pendingReloadMu.Lock() + defer b.pendingReloadMu.Unlock() + return b.pendingReload != nil && b.reloadApply != nil +} + +func (b *boot) currentSaveSeq() uint64 { + if b.configSaveSeq != nil { + return b.configSaveSeq() + } + return config.SaveSeq() +} + +func (b *boot) saveReloadedConfig() error { + if b.saveConfig != nil { + return b.saveConfig() + } + return b.cfg.Save() +} + +// applyPendingReloadLocked swaps in the parked reload, if any. Caller holds +// cfgReloadMu. +// +// If any config save started while the reload was parked, hive.yaml now +// holds the pre-reload config, not the operator's edit. The reloaded config +// is saved back so disk matches memory; the save arms the watcher's SkipNext +// through the save observer, so it does not trigger another reload. +func (b *boot) applyPendingReloadLocked() { + if b.reloadApply == nil { + return + } + b.pendingReloadMu.Lock() + newCfg := b.pendingReload + parkedSeq := b.parkedSaveSeq + b.pendingReload = nil + b.pendingReloadMu.Unlock() + if newCfg == nil { + return + } + prev, next := b.reloadApply(newCfg) + if prev != next { + b.pendingACMM = append(b.pendingACMM, [2]int{prev, next}) + } + if seq := b.currentSaveSeq(); seq != parkedSeq { + if b.logger != nil { + b.logger.Info("config was saved while a reload was pending; saving the reloaded config back to disk", + "saves_while_pending", seq-parkedSeq) + } + if err := b.saveReloadedConfig(); err != nil && b.logger != nil { + b.logger.Error("failed to save reloaded config back to disk", "error", err) + } + } +} + +// persistCycleLocked is a governor tick's persist. persistState writes the +// governor snapshot and reach counters and ends in +// Config.ReconcilePausedAndSave, which rewrites hive.yaml from the in-memory +// config. Any parked reload is applied first, so the save writes the +// reloaded config rather than the one the tick started from, and the +// governor state is still saved this tick. Caller holds cfgReloadMu. +func (b *boot) persistCycleLocked(persist func(*boot)) { + b.applyPendingReloadLocked() + persist(b) +} diff --git a/src/cmd/hive/cfg_reload_test.go b/src/cmd/hive/cfg_reload_test.go new file mode 100644 index 0000000000..9d1def0dc1 --- /dev/null +++ b/src/cmd/hive/cfg_reload_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// A save that ran from the pre-reload config while the reload was parked +// left hive.yaml without the operator's edit; applying the reload must save +// the reloaded config back (hivecommons/hive#17467). +func TestApplyPendingReload_SavesBackAfterStaleSaveWhileParked(t *testing.T) { + b, log, _ := newLoopBoot(t, 60, 0) + b.reloadApply = func(newCfg *config.Config) (int, int) { + *b.cfg = *newCfg + return 0, 0 + } + var seq uint64 + b.configSaveSeq = func() uint64 { return seq } + var saved [][]string + b.saveConfig = func() error { + saved = append(saved, append([]string(nil), b.cfg.Project.Repos...)) + return nil + } + + newCfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{"alpha": {Enabled: true}}}} + newCfg.Project.Repos = []string{"reloaded"} + + b.lockCfg() + b.submitConfigReload(newCfg) + seq++ // e.g. a heartbeat callback's cfg.Save() from the stale config + b.unlockCfg() + + if !sameStringSlice(b.cfg.Project.Repos, []string{"reloaded"}) { + t.Fatalf("repos = %v, want the reloaded config applied", b.cfg.Project.Repos) + } + if len(saved) != 1 || !sameStringSlice(saved[0], []string{"reloaded"}) { + t.Fatalf("saves after reload = %v, want exactly one save of the reloaded config", saved) + } + if !strings.Contains(log.String(), "saving the reloaded config back to disk") { + t.Fatalf("write-back not logged:\n%s", log.String()) + } +} + +func TestApplyPendingReload_NoSaveBackWithoutStaleSave(t *testing.T) { + b, _, _ := newLoopBoot(t, 60, 0) + b.reloadApply = func(newCfg *config.Config) (int, int) { + *b.cfg = *newCfg + return 0, 0 + } + b.configSaveSeq = func() uint64 { return 7 } + saves := 0 + b.saveConfig = func() error { saves++; return nil } + + newCfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{"alpha": {Enabled: true}}}} + newCfg.Project.Repos = []string{"reloaded"} + + // Deferred and immediate paths both leave disk alone when nothing saved. + b.lockCfg() + b.submitConfigReload(newCfg) + b.unlockCfg() + b.submitConfigReload(newCfg) + + if saves != 0 { + t.Fatalf("saves = %d, want 0 when no save ran while the reload was pending", saves) + } + if !sameStringSlice(b.cfg.Project.Repos, []string{"reloaded"}) { + t.Fatalf("repos = %v, want the reloaded config applied", b.cfg.Project.Repos) + } +} + +// parkedSaveSeq belongs to the oldest unapplied reload: a save between two +// parked reloads still counts, since the disk may hold neither edit. +func TestApplyPendingReload_SaveSeqAnchoredToOldestParkedReload(t *testing.T) { + b, _, _ := newLoopBoot(t, 60, 0) + b.reloadApply = func(newCfg *config.Config) (int, int) { + *b.cfg = *newCfg + return 0, 0 + } + var seq uint64 + b.configSaveSeq = func() uint64 { return seq } + saves := 0 + b.saveConfig = func() error { saves++; return nil } + + first := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{"alpha": {Enabled: true}}}} + first.Project.Repos = []string{"first"} + second := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{"alpha": {Enabled: true}}}} + second.Project.Repos = []string{"second"} + + b.lockCfg() + b.submitConfigReload(first) + seq++ + b.submitConfigReload(second) + b.unlockCfg() + + if saves != 1 { + t.Fatalf("saves = %d, want 1", saves) + } + if !sameStringSlice(b.cfg.Project.Repos, []string{"second"}) { + t.Fatalf("repos = %v, want the newest reload applied", b.cfg.Project.Repos) + } +} diff --git a/src/cmd/hive/claims_admission_test.go b/src/cmd/hive/claims_admission_test.go index 649cff06c8..7822cbdb38 100644 --- a/src/cmd/hive/claims_admission_test.go +++ b/src/cmd/hive/claims_admission_test.go @@ -2,12 +2,14 @@ package main import ( "context" + "encoding/json" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "path/filepath" + "strings" "sync/atomic" "testing" @@ -202,3 +204,93 @@ func TestKickClaimsRefuseIssueWithOpenLinkedPR(t *testing.T) { t.Fatalf("open-PR listings = %d, want still 1 (renewal/tick never list)", pullsCalls.Load()) } } + +// hivecommons/hive#17299: an issue an agent filed without --claim is filed +// for outside help, and the hub's own scanner dispatch of it back to that +// agent (#17243→#17250) is refused — not only the agent's relay `claim` +// request. Another agent still takes it. +func TestKickClaimsRefuseFilerOfFiledForHelpIssue(t *testing.T) { + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/repos/o/r/issues/17243": + body, _ := json.Marshal(map[string]any{ + "number": 17243, "state": "open", "labels": []map[string]string{{"name": "help wanted"}}, + "body": "someone take this\n\n" + github.FiledForHelpMarker("scanner"), + }) + _, _ = w.Write(body) + case r.URL.Path == "/repos/o/r/pulls", r.URL.Path == "/repos/o/r/issues/17243/labels", r.URL.Path == "/repos/o/r/labels": + fmt.Fprint(w, `[]`) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer api.Close() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + client := github.NewClientForTest(api.URL, "o", []string{"r"}, logger) + ledger := testClaimsLedger(t) + installClaimAdmissionCheck(context.Background(), ledger, func() *github.Client { return client }) + + res, err := ledger.Claim(claims.Request{Repo: "o/r", Issue: 17243, Holder: "scanner", HolderID: "scanner", Kind: claims.KindAgent}) + if err != nil || res.Outcome != claims.OutcomeRefused || !strings.HasPrefix(res.Reason, github.ClaimBlockReasonFiledForHelpPrefix+"scanner") { + t.Fatalf("filer's dispatch = %+v, %v; want refused with %q", res, err, github.ClaimBlockReasonFiledForHelpPrefix+"scanner") + } + ledger.MarkListed("o/r", 17243, "scanner") + recordAgentStart(ledger, "o", "scanner", "r", 17243, github.AgentStartSignalClaim, logger) + if c, ok := ledger.Lookup("o/r", 17243); ok { + t.Fatalf("filer's start signal claimed its own filed-for-help issue: %+v", c) + } + + res, err = ledger.Claim(claims.Request{Repo: "o/r", Issue: 17243, Holder: "reviewer", HolderID: "reviewer", Kind: claims.KindAgent}) + if err != nil || res.Outcome != claims.OutcomeClaimed { + t.Fatalf("another agent's claim = %+v, %v; want claimed", res, err) + } +} + +// hivecommons/hive#17299: an issue an agent files with --claim was never in +// a kick, so a plain `claim` start signal on it ledgers nothing and every +// ledger-only reader (dispatch admission Lookup, the PR-request gate, the +// claim listing) still sees it unclaimed. The filed-claim signal the create +// path raises is the issue's own listing: the ledger claim is recorded, the +// admission check still runs, and another agent's dispatch is refused. +func TestRecordAgentStartFiledClaimLedgersSelfFiledIssue(t *testing.T) { + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/repos/o/r/issues/17243": + body, _ := json.Marshal(map[string]any{ + "number": 17243, "state": "open", "body": "stage 2 of my epic", + "labels": []map[string]string{{"name": "hive/claimed-by-scanner"}}, + }) + _, _ = w.Write(body) + case r.URL.Path == "/repos/o/r/pulls", r.URL.Path == "/repos/o/r/issues/17243/labels", r.URL.Path == "/repos/o/r/labels": + fmt.Fprint(w, `[]`) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer api.Close() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + client := github.NewClientForTest(api.URL, "o", []string{"r"}, logger) + ledger := testClaimsLedger(t) + installClaimAdmissionCheck(context.Background(), ledger, func() *github.Client { return client }) + + // The plain claim signal a `claim` request raises: no kick listed the + // issue, so the ledger stays empty — the gap the filed-claim signal closes. + recordAgentStart(ledger, "o", "scanner", "r", 17243, github.AgentStartSignalClaim, logger) + if c, ok := ledger.Lookup("o/r", 17243); ok { + t.Fatalf("plain claim signal on an unlisted issue recorded a claim: %+v", c) + } + + recordAgentStart(ledger, "o", "scanner", "r", 17243, github.AgentStartSignalFiledClaim, logger) + c, ok := ledger.Lookup("o/r", 17243) + if !ok || c.Holder != "scanner" || c.Kind != claims.KindAgent || c.PRStarted { + t.Fatalf("filed-claim signal did not ledger the self-filed issue to its filer: %+v, %v", c, ok) + } + if li, listed := ledger.Listed("o/r", 17243); listed { + t.Fatalf("listing outlived the claim it became: %+v", li) + } + + res, err := ledger.Claim(claims.Request{Repo: "o/r", Issue: 17243, Holder: "reviewer", HolderID: "reviewer", Kind: claims.KindAgent}) + if err != nil || res.Outcome != claims.OutcomeHeld || res.Claim.Holder != "scanner" { + t.Fatalf("another agent's dispatch of the self-filed issue = %+v, %v; want held by scanner", res, err) + } +} diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index 140d7bd587..9f3aedc6b1 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -217,8 +217,13 @@ func installClaimAdmissionCheck(ctx context.Context, ledger *claims.Ledger, clie // A fresh claim with no PR behind it is a dispatch: it also asks // whether an open PR already fixes the issue (#14799). A renewal, // a PR-backed start signal and the release tick's recheck of live - // claims do not — the holder's own PR is the open PR. + // claims do not — the holder's own PR is the open PR. A hive + // agent's own dispatch (Holder is the agent name) also refuses an + // issue that agent filed for outside help (hivecommons/hive#17299). if _, held := ledger.Lookup(req.Repo, req.Issue); !held && !req.PRStarted { + if req.Kind == claims.KindAgent { + return gh.IssueStartBlockReason(ctx, req.Repo, req.Issue, req.Holder) + } return gh.IssueDispatchBlockReason(ctx, req.Repo, req.Issue) } return gh.IssueClaimBlockReason(ctx, req.Repo, req.Issue) @@ -514,12 +519,22 @@ func recordAgentKickListings(dashSrv *dashboard.Server, org, agentName string, i // comment or a label request; see pkg/github/agent_start_hook.go). The first such signal on an issue a kick // listed to the agent records the agent claim (comment and label included) // that the escalation gate counts; a later one renews it. A signal on an -// issue no kick listed to the agent records nothing. +// issue no kick listed to the agent records nothing — except the filed-claim +// signal (hivecommons/hive#17299): the agent filed that issue itself as its +// own next step and claimed it in the same request, so no kick could have +// listed it; the filing is its listing, and the claim is recorded like a +// kicked issue's first start (admission check included). func recordAgentStart(ledger *claims.Ledger, org, agentName, repo string, issue int, signal string, logger *slog.Logger) { if ledger == nil || agentName == "" || issue <= 0 { return } - res, started, err := ledger.ClaimOnStart(qualifyClaimRepo(org, repo), issue, agentName, github.StartSignalIsPREvidence(signal)) + qualified := qualifyClaimRepo(org, repo) + if signal == github.AgentStartSignalFiledClaim { + if _, listed := ledger.MarkListed(qualified, issue, agentName); !listed && logger != nil { + logger.Debug("issue-claims: self-filed issue someone else holds; not listed", "agent", agentName, "repo", repo, "issue", issue) + } + } + res, started, err := ledger.ClaimOnStart(qualified, issue, agentName, github.StartSignalIsPREvidence(signal)) if logger == nil || !started { return } diff --git a/src/cmd/hive/github_client_config.go b/src/cmd/hive/github_client_config.go index b5b802fbcc..2fe536e87f 100644 --- a/src/cmd/hive/github_client_config.go +++ b/src/cmd/hive/github_client_config.go @@ -132,6 +132,9 @@ func (b *boot) applyGitHubClientConfigHooks(client *github.Client) { client.SetRedMainThresholdFunc(b.cfg.RepoRedMainThreshold) // Open-held-PR cap (#13645), live per repo. client.SetMaxOpenHeldPRsFunc(b.cfg.RepoMaxOpenHeldPRs) + // Changed-digest rewrite floor (#17435); the eval cycle re-applies it + // from live config so a dashboard edit takes effect without a rebuild. + client.SetAdvisoryDigestMinInterval(b.cfg.Governor.Advisory.EffectiveDigestMinInterval()) client.SetScheduledBaseRefresh(func(repo string) bool { return b.cfg.AutoMerge.RequireCurrentBaseFor(repo) }) // Per-repo custom agents (#6204). A live predicate over the shared // config, so the hive-open-pr / hive-merge / hive-open-issue relays diff --git a/src/cmd/hive/hold_guard_mergeability_test.go b/src/cmd/hive/hold_guard_mergeability_test.go index 14ff9f0ebc..d9419dd978 100644 --- a/src/cmd/hive/hold_guard_mergeability_test.go +++ b/src/cmd/hive/hold_guard_mergeability_test.go @@ -5,7 +5,9 @@ package main // integration style of hold_guard_test.go. import ( + "bytes" "context" + "log/slog" "strings" "testing" @@ -452,3 +454,60 @@ func TestMaintainHeldPRMergeabilityLeavesDependencyBotBranchesToTheBot(t *testin }) } } + +// A held PR whose repo's base refresh belongs to the automerge preparation +// front is a policy deferral: it must not log the failure WARN every tick. +func TestMaintainHeldPRMergeabilityDefersScheduledBaseRefreshWithoutWarn(t *testing.T) { + store := newTestHoldGuardStore(t) + fake := &holdGuardServer{commits: map[int][]map[string]any{ + 7: {ghCommit("c1", "strategist-bot", "docs: plan")}, + }} + client := newHoldGuardClient(t, fake) + client.SetScheduledBaseRefresh(func(string) bool { return true }) + cfg := escalationTestConfig() + store.Snapshot("acme/widgets", 7, "c1", []holdguard.Commit{{SHA: "c1", Author: "strategist-bot"}}) + + var buf bytes.Buffer + logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})) + held := heldPRsActionable(github.PullRequest{Repo: "widgets", Number: 7, HeadSHA: "c1", BaseSHA: "b1", MergeableState: "behind"}) + if got := enforceHoldGuard(context.Background(), cfg, client, client, held, logger); len(got) != 0 { + t.Fatalf("deferred base refresh must not flag the PR for re-review, got %v", got) + } + + out := buf.String() + if strings.Contains(out, "keeping held PR mergeable failed") || strings.Contains(out, "level=WARN") { + t.Fatalf("deferred base refresh logged a warning:\n%s", out) + } + if !strings.Contains(out, "base refresh deferred to the automerge preparation front") { + t.Fatalf("missing debug deferral log:\n%s", out) + } +} + +// The deferral is scoped to `behind`: a held PR that GitHub reports `dirty` on +// a scheduled-base-refresh repo is a real conflict, and the preparation front +// does not tell the human about held PRs, so the conflict notice must still +// be posted. +func TestMaintainHeldPRMergeabilityStillNotesConflictWhenBaseRefreshIsScheduled(t *testing.T) { + store := newTestHoldGuardStore(t) + fake := &holdGuardServer{commits: map[int][]map[string]any{ + 7: {ghCommit("c1", "strategist-bot", "docs: plan")}, + }} + client := newHoldGuardClient(t, fake) + client.SetScheduledBaseRefresh(func(string) bool { return true }) + cfg := escalationTestConfig() + store.Snapshot("acme/widgets", 7, "c1", nil) + + held := heldPRsActionable(github.PullRequest{Repo: "widgets", Number: 7, HeadSHA: "c1", BaseSHA: "b1", MergeableState: "dirty"}) + _ = enforceHoldGuard(context.Background(), cfg, client, client, held, discardLogger()) + + if len(fake.comments) != 1 { + t.Fatalf("want one conflict notice on a dirty held PR, got %v", fake.comments) + } + if !strings.Contains(fake.comments[0], "conflict") { + t.Fatalf("conflict comment = %q, want it to name the conflict", fake.comments[0]) + } + rec, ok := store.Recorded("acme/widgets", 7) + if !ok || !rec.ConflictNoted { + t.Fatalf("snapshot = %+v ok=%v, want ConflictNoted set", rec, ok) + } +} diff --git a/src/cmd/hive/kick_freshness.go b/src/cmd/hive/kick_freshness.go index 6db38e66dd..5ca92c93c4 100644 --- a/src/cmd/hive/kick_freshness.go +++ b/src/cmd/hive/kick_freshness.go @@ -33,7 +33,9 @@ func freshenKickMessages(ctx context.Context, guard github.IrreversibleGuard, ac continue } kept := make([]string, 0, len(msg.IssueRefs)) - allDeferred := true + // Deferred and closed refusals are the guard working as designed; a + // kick withheld only by those is summarised below WARN too (#17518). + allExpected := true var stale, closed, deferredReads, readErrors int for _, raw := range msg.IssueRefs { ref, ok := worksource.ParseKey(raw) @@ -45,8 +47,8 @@ func freshenKickMessages(ctx context.Context, guard github.IrreversibleGuard, ac _, isPR := prRefs[key] if err := guard(ctx, ref.Repo, ref.Number, isPR); err != nil { deferred := errors.Is(err, github.ErrAPIBudgetCritical) || errors.Is(err, github.ErrRateLimitCaution) - if !deferred { - allDeferred = false + if !deferred && !errors.Is(err, github.ErrItemNotOpen) { + allExpected = false } if logger != nil { reason := "re-read" @@ -61,6 +63,14 @@ func freshenKickMessages(ctx context.Context, guard github.IrreversibleGuard, ac reason = "stale snapshot" stale++ case errors.Is(err, github.ErrItemNotOpen): + // The re-read found the item closed or merged: the guard + // doing its job, not a fault. The snapshot keeps serving the + // stale copy until the cache catches up, so this repeats + // every cycle; at WARN the slog feed filed it as an + // unclassified repeated error (#17518). The withheld-kick + // summary below still counts it as closed. + reason = "closed" + level = slog.LevelInfo closed++ default: readErrors++ @@ -76,7 +86,7 @@ func freshenKickMessages(ctx context.Context, guard github.IrreversibleGuard, ac if len(kept) == 0 { if logger != nil { level := slog.LevelWarn - if allDeferred { + if allExpected { level = slog.LevelInfo } logger.Log(ctx, level, "kick withheld: every ref failed the freshness check", diff --git a/src/cmd/hive/kick_freshness_test.go b/src/cmd/hive/kick_freshness_test.go index d9de31f101..7d440c57d4 100644 --- a/src/cmd/hive/kick_freshness_test.go +++ b/src/cmd/hive/kick_freshness_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "log/slog" + "strconv" "strings" "sync/atomic" "testing" @@ -77,17 +78,22 @@ func TestFreshenKickMessages_WithholdsStaleAndClosed(t *testing.T) { // A refusal from the API budget or rate-limit caution window is the designed // back-off, not a fault: it is withheld but logged below WARN so the fleet // self-report feed does not file it as an unclassified repeated error -// (#15465). Any other refusal still logs at WARN. +// (#15465). A re-read that finds the item closed is likewise the guard +// working as designed and repeats every cycle until the cache catches up, +// so it logs below WARN with reason=closed (#17518). Any other refusal still +// logs at WARN. func TestFreshenKickMessages_DeferredReadLogsBelowWarn(t *testing.T) { cases := []struct { - name string - err error - wantWarn bool + name string + err error + wantWarn bool + wantReason string }{ - {"budget critical", github.ErrAPIBudgetCritical, false}, - {"caution window", github.ErrRateLimitCaution, false}, - {"stale snapshot", github.ErrSnapshotStaleForDecision, true}, - {"item closed", github.ErrItemNotOpen, true}, + {"budget critical", github.ErrAPIBudgetCritical, false, "github read deferred"}, + {"caution window", github.ErrRateLimitCaution, false, "github read deferred"}, + {"stale snapshot", github.ErrSnapshotStaleForDecision, true, "stale snapshot"}, + {"item closed", github.ErrItemNotOpen, false, "closed"}, + {"read error", errors.New("private endpoint failed"), true, "re-read"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -107,6 +113,9 @@ func TestFreshenKickMessages_DeferredReadLogsBelowWarn(t *testing.T) { if got := strings.Contains(log, "level=WARN"); got != tc.wantWarn { t.Fatalf("WARN logged = %v, want %v: %q", got, tc.wantWarn, log) } + if want := "reason=" + strconv.Quote(tc.wantReason); !strings.Contains(log, want) && !strings.Contains(log, "reason="+tc.wantReason) { + t.Fatalf("reason not logged, want %s: %q", want, log) + } }) } } diff --git a/src/cmd/hive/knowledge_adviser_llm.go b/src/cmd/hive/knowledge_adviser_llm.go index da6507e872..233a540260 100644 --- a/src/cmd/hive/knowledge_adviser_llm.go +++ b/src/cmd/hive/knowledge_adviser_llm.go @@ -344,13 +344,25 @@ func buildKnowledgeAdviserLLMPrompt(kickSummary string, scope crux.KnowledgeScop return b.String() } +// knowledgeAdviserLLMURL maps the configured endpoint to the chat URL: a base +// already ending in /chat/completions is used as-is (the Copilot API has no +// /v1 prefix); anything else is delegated to config.LiteLLMChatCompletionsURL +// so the /v1 and bare-host handling stays in one place. +func knowledgeAdviserLLMURL(endpoint string) string { + base := strings.TrimRight(strings.TrimSpace(endpoint), "/") + if strings.HasSuffix(base, "/chat/completions") { + return base + } + return config.LiteLLMChatCompletionsURL(base) +} + func (d *knowledgeAdviserLLM) complete(ctx context.Context, r config.ResolvedAdvisorLLM, reqBody knowledgeAdviserLLMRequest) (knowledgeAdviserLLMResponse, error) { var cr knowledgeAdviserLLMResponse body, err := json.Marshal(reqBody) if err != nil { return cr, fmt.Errorf("marshal knowledge advisor request: %w", err) } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Endpoint+"/v1/chat/completions", bytes.NewReader(body)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, knowledgeAdviserLLMURL(r.Endpoint), bytes.NewReader(body)) if err != nil { return cr, fmt.Errorf("build knowledge advisor request: %w", err) } diff --git a/src/cmd/hive/knowledge_adviser_llm_test.go b/src/cmd/hive/knowledge_adviser_llm_test.go index 5ddeba5bf5..9a478e9cd7 100644 --- a/src/cmd/hive/knowledge_adviser_llm_test.go +++ b/src/cmd/hive/knowledge_adviser_llm_test.go @@ -353,6 +353,19 @@ func TestKnowledgeAdviserLLM_EndpointErrorFallsBackPerOnError(t *testing.T) { } } +func TestKnowledgeAdviserLLMURL(t *testing.T) { + for in, want := range map[string]string{ + "https://api.githubcopilot.com": "https://api.githubcopilot.com/v1/chat/completions", + "https://x.example/v1": "https://x.example/v1/chat/completions", + "https://x.example/v1/": "https://x.example/v1/chat/completions", + "https://api.githubcopilot.com/chat/completions": "https://api.githubcopilot.com/chat/completions", + } { + if got := knowledgeAdviserLLMURL(in); got != want { + t.Errorf("knowledgeAdviserLLMURL(%q) = %q, want %q", in, got, want) + } + } +} + func TestKnowledgeAdviserLLM_PerAgentHourBudget(t *testing.T) { f := newLLMFixture(t, config.AdvisorLLMConfig{Mode: config.AdvisorLLMModeRank, OnError: config.AdvisorLLMOnErrorSilence}) for i := 0; i < config.AdvisorLLMMaxCallsPerAgentHourCap; i++ { diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 0cd267d0cc..c6bbb2a260 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -673,6 +673,15 @@ func (b *boot) bootConfigWith(deps bootConfigDeps) bool { b.logger = withStartID(deps.fileLogger(b.cfg), b.startID) slog.SetDefault(b.logger) + // #17468: one line naming the file this boot actually read. On hosted + // spokes /etc/hive/hive.yaml is a symlink into the PVC, so the resolved + // path is the persisted file an operator must edit. + b.logger.Info("boot: config source of truth", + "loaded_from", b.configPath, + "boot_source", config.ResolvedConfigPath(b.configPath), + "persisted_path", config.PersistedConfigPath(b.configPath), + ) + // Load or generate a unique Hive ID for this instance b.cfg.HiveID = deps.hiveID(b.logger) _ = os.Setenv("HIVE_ID", b.cfg.HiveID) // valid key/value; Setenv cannot fail on Unix @@ -2222,9 +2231,9 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { // (GetACMMLevel), NOT from a client flag — the gh-wrapper.sh tail that used // to add the label was dead code after `exec hive-open-pr`. L1/L2 open no // agent PRs (manual); non-outreach L6 PRs retain their existing automerge - // behavior. + // behavior. The red-team lane is held at every level (see shouldHoldAgentPR). holdLabel := func(agentName, repo string) bool { - return shouldHoldAgentPR(agentName, repo, b.agentMgr.GetACMMLevel(), b.cfg.AgentOwnsRepo) + return shouldHoldAgentPR(agentName, repo, b.agentMgr.GetACMMLevel(), b.cfg.AgentOwnsRepo, b.cfg.IsRedTeamAgent) } selfAuthorizationHoldEnabled := b.selfAuthorizationHoldEnabled @@ -3972,17 +3981,14 @@ func (b *boot) bootWatchers() { b.bootWatchersWith(defaultBootWatchersDeps()) } // bootWatchersDeps. func (b *boot) bootWatchersWith(deps bootWatchersDeps) { // Watch hive.yaml for external changes and reload config when modified - b.configWatcher = deps.newConfigWatcher(b.configPath, func(newCfg *config.Config) { - b.cfgReloadMu.Lock() - prevACMMLevel := b.cfg.ACMMLevelOrZero() - nextACMMLevel := prevACMMLevel - defer func() { - b.publishSweepConfig() - b.cfgReloadMu.Unlock() - if prevACMMLevel != nextACMMLevel { - b.onACMMLevelChanged(prevACMMLevel, nextACMMLevel) - } - }() + // The watcher callback never waits for cfgReloadMu: submitConfigReload + // parks the config and whichever goroutine holds the lock applies it at + // its next safe point (hivecommons/hive#17467). reloadApply runs with + // cfgReloadMu held and returns the ACMM transition to fire after unlock. + b.reloadApply = func(newCfg *config.Config) (prevACMMLevel, nextACMMLevel int) { + prevACMMLevel = b.cfg.ACMMLevelOrZero() + nextACMMLevel = prevACMMLevel + defer b.publishSweepConfig() // Preserve runtime-only fields that are not in the YAML newCfg.HiveID = b.cfg.HiveID @@ -4155,7 +4161,9 @@ func (b *boot) bootWatchersWith(deps bootWatchersDeps) { } b.refreshDashboard() - }, b.logger) + return prevACMMLevel, nextACMMLevel + } + b.configWatcher = deps.newConfigWatcher(b.configPath, b.submitConfigReload, b.logger) config.SetSaveObserver(b.configWatcher.SkipNext) b.dashSrv.SetSkipReloadFunc(b.configWatcher.SkipNext) deps.startConfigWatcher(b.ctx, b.configWatcher) @@ -5220,7 +5228,9 @@ func (b *boot) bootHeartbeatWith(deps bootHeartbeatDeps) { // base_url and api_url — a GHE placeholder with base_url:"" but // api_url: github.ibm.com must report github.ibm.com, not be // silently rendered as github.com in the spokes table. - GitHubHost: b.cfg.GitHub.HostLabel(), + GitHubHost: b.cfg.GitHub.HostLabel(), + // Read after Health above, so it reflects this beat's probe. + ForgeUnreachable: b.dashSrv.ForgeUnreachable(), GitHubAppRequired: b.dashSrv.IsGitHubAppRequired(), GitHubAppPermIssue: b.dashSrv.GetGitHubAppPermIssue(), GitHubAppState: b.dashSrv.GetGitHubAppState(), @@ -6504,16 +6514,16 @@ func (b *boot) runLoopWith(deps runLoopDeps) { if loopNow == nil { loopNow = time.Now } - b.cfgReloadMu.Lock() + b.lockCfg() b.publishSweepConfig() - b.cfgReloadMu.Unlock() + b.unlockCfg() if deps.startSweeps != nil { defer deps.startSweeps(b)() } // Cadence is measured from the start, including the first (often slow) // enumerate pass, not from completion of startup evaluation. lastEnumerateAt := loopNow() - b.cfgReloadMu.Lock() + b.lockCfg() initialTickStarted := time.Now() b.evalCycles++ deps.runEval(b, nil, evalSourceEnumerate) @@ -6533,8 +6543,8 @@ func (b *boot) runLoopWith(deps runLoopDeps) { if b.wd != nil { b.wd.Tick(b.ctx) } - deps.persist(b) - b.cfgReloadMu.Unlock() + b.persistCycleLocked(deps.persist) + b.unlockCfg() b.logger.Info("governor tick complete", "tick_wall_s", time.Since(initialTickStarted).Seconds(), "eval_s", initialEvalDuration.Seconds(), "rotation_s", initialRotationDuration.Seconds(), "sweeps_s", 0, "source", evalSourceEnumerate.String(), "startup", true) @@ -6556,7 +6566,7 @@ func (b *boot) runLoopWith(deps runLoopDeps) { if source == evalSourceEnumerate { lastEnumerateAt = loopNow() } - b.cfgReloadMu.Lock() + b.lockCfg() b.publishSweepConfig() restarted := deps.restartCrashed(b.ctx, b.agentMgr) for _, name := range restarted { @@ -6642,7 +6652,7 @@ func (b *boot) runLoopWith(deps runLoopDeps) { b.logger.Info("retro lane filed advisory beads", "findings", n) } } - deps.persist(b) + b.persistCycleLocked(deps.persist) effectiveEvalInterval, mode := evalIntervalAndModeForConfig(b.cfg, b.ghClient, b.logger) if effectiveEvalInterval != lastEvalInterval { b.logger.Info("eval interval changed, resetting ticker", @@ -6653,7 +6663,7 @@ func (b *boot) runLoopWith(deps runLoopDeps) { if b.evalLoop != nil { b.evalLoop.setInterval(effectiveEvalInterval, mode) } - b.cfgReloadMu.Unlock() + b.unlockCfg() b.logger.Info("governor tick complete", "tick_wall_s", time.Since(tickStarted).Seconds(), "eval_s", evalDuration.Seconds(), "rotation_s", rotationDuration.Seconds(), "sweeps_s", 0, "source", source.String()) @@ -6771,11 +6781,11 @@ func (b *boot) runLoopWith(deps runLoopDeps) { tick(evalSourceCached) } else { // Keep this cycle lean: planning and delivery without sweeps. - b.cfgReloadMu.Lock() + b.lockCfg() b.evalCycles++ deps.runEval(b, nil, evalSourceCached) - deps.persist(b) - b.cfgReloadMu.Unlock() + b.persistCycleLocked(deps.persist) + b.unlockCfg() } after, afterWho := b.gov.NextContinuousKickAt() if backoff, stalled := wakeHold.observe(next, after, who, afterWho, wakeNow()); stalled { @@ -6808,7 +6818,11 @@ func (b *boot) runLoopWith(deps runLoopDeps) { select { case <-b.ctx.Done(): b.logger.Info("shutting down, persisting state") - deps.persist(b) + // Under the config lock, so a reload being applied cannot race + // the final save and the save writes the newest config. + b.lockCfg() + b.persistCycleLocked(deps.persist) + b.unlockCfg() return case <-ticker.Chan(): tick(evalSourceEnumerate) @@ -6848,7 +6862,7 @@ func (b *boot) runLoopWith(deps runLoopDeps) { armContinuousWake() armWebhookHealthRecheck() case <-healthCh: - b.cfgReloadMu.Lock() + b.lockCfg() effectiveEvalInterval, mode := evalIntervalAndModeForConfig(b.cfg, b.ghClient, b.logger) if effectiveEvalInterval != lastEvalInterval { b.logger.Info("eval interval changed, resetting ticker", @@ -6859,17 +6873,17 @@ func (b *boot) runLoopWith(deps runLoopDeps) { if b.evalLoop != nil { b.evalLoop.setInterval(effectiveEvalInterval, mode) } - b.cfgReloadMu.Unlock() + b.unlockCfg() armWebhookHealthRecheck() case <-wakeCh: // The loop-top due check services this timer. armContinuousWake() case <-agentTickCh: - b.cfgReloadMu.Lock() + b.lockCfg() govState := b.gov.GetState() agentStatuses := b.agentMgr.AllStatuses() payload := dashboard.BuildAgentOnlyStatus(govState, agentStatuses, b.cfg) - b.cfgReloadMu.Unlock() + b.unlockCfg() b.dashSrv.BroadcastAgentStatus(payload) } } diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 5866eea2c2..cb4eedeabf 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -1441,6 +1441,9 @@ func runEvalCycle( // The App is the sole advisory-digest writer (#1927): a user-token // failure must never drive the App banner, so every banner hook // below is fed exclusively by the App's own error. + // digest_min_interval is read live like the other advisory knobs + // (#17435): a dashboard edit applies from the next cycle. + ghClient.SetAdvisoryDigestMinInterval(advCfg.EffectiveDigestMinInterval()) publishAdvisoryDigest(ctx, md, digest, advisoryPublishRoute{ target: advisoryTarget, linearIssue: advisoryLinearIssue, diff --git a/src/cmd/hive/main_helpers.go b/src/cmd/hive/main_helpers.go index 29567b0b07..77273959de 100644 --- a/src/cmd/hive/main_helpers.go +++ b/src/cmd/hive/main_helpers.go @@ -431,6 +431,19 @@ func maintainHeldPRMergeability( "repo", repo, "pr", pr.Number, "expected_head", head, "error", err) continue } + if github.IsBaseRefreshAwaitingAdmission(err) { + if state == "dirty" { + // The preparation front does not tell the human about + // held PRs; a dirty held PR is a real conflict and still + // gets its notice. + stopHeldPRUpdate(ctx, writer, store, repo, pr, holdguard.UpdateStopConflict, err, logger) + continue + } + // Policy deferral, not a failure: it recurs every tick by design. + logger.Debug("hold guard: held PR base refresh deferred to the automerge preparation front", + "repo", repo, "pr", pr.Number, "mergeable_state", state) + continue + } switch github.ClassifyBranchUpdateError(err, pr.FromFork) { case github.BranchUpdateWorkflowPermission: stopHeldPRUpdate(ctx, writer, store, repo, pr, holdguard.UpdateStopWorkflowPermission, err, logger) diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index a2d1549178..d2d8543bd8 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -143,6 +143,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy StalledRequireQuiet: stage.Stalled.IsRequireQuiet(), ContributorNudge: stage.ContributorNudge.IsEnabled(), RenudgeInterval: nudgeRepeatAfter(cfg), + CIFailureCooldown: stage.ContributorNudge.EffectiveCIFailureCooldown(), Adoption: stage.Adoption.IsEnabled(), GraceOnline: stage.EffectiveContributorGraceOnline(), GraceOffline: stage.EffectiveContributorGraceOffline(), @@ -381,7 +382,18 @@ const ( // ordinary hive PR and flows through normal review and auto-merge (operator // decision, 2026-10-16). A nil ownsRepo fails closed to "cross-repo", so a // wiring mistake can only hold too much, never too little. -func shouldHoldAgentPR(agentName, repo string, level int, ownsRepo func(agent, repo string) bool) bool { +// +// The red-team lane (hivecommons/hive#17420) adds a second level-independent +// reason: its PRs change the ioscan red-team corpus and the published block +// rate, and the lane's whole output is adversarial text. Its policy promises +// "hold at every ACMM level, including L6"; alwaysHold is the server-side +// enforcement of that promise, keyed on the authenticated agent's role/base +// name from config, so a prompt that forgets the label cannot open an +// auto-merge path. A nil alwaysHold simply adds no reason. +func shouldHoldAgentPR(agentName, repo string, level int, ownsRepo func(agent, repo string) bool, alwaysHold func(agent string) bool) bool { + if alwaysHold != nil && alwaysHold(agentName) { + return true + } if isOutreachAgent(agentName) { if ownsRepo == nil || !ownsRepo(agentName, repo) { return true diff --git a/src/cmd/hive/outreach_hold_test.go b/src/cmd/hive/outreach_hold_test.go index 721011f362..dd4f682b44 100644 --- a/src/cmd/hive/outreach_hold_test.go +++ b/src/cmd/hive/outreach_hold_test.go @@ -1,6 +1,10 @@ package main -import "testing" +import ( + "testing" + + "github.com/hivecommons/hive/pkg/config" +) func TestShouldHoldAgentPR(t *testing.T) { // ownsRepo models config.AgentOwnsRepo: the hive manages "hive" and @@ -31,9 +35,45 @@ func TestShouldHoldAgentPR(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := shouldHoldAgentPR(tt.agent, tt.repo, tt.level, tt.ownsRepo); got != tt.want { + if got := shouldHoldAgentPR(tt.agent, tt.repo, tt.level, tt.ownsRepo, nil); got != tt.want { t.Fatalf("shouldHoldAgentPR(%q, %q, %d) = %v, want %v", tt.agent, tt.repo, tt.level, got, tt.want) } }) } } + +// The red-team lane (hivecommons/hive#17420) is held at every level, including +// L6, by the alwaysHold predicate the relay wires to config.IsRedTeamAgent — +// matched by role, by base name, and through a replica. +func TestShouldHoldAgentPRHoldsRedTeamAtEveryLevel(t *testing.T) { + cfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{ + "redteam": {Role: config.RedTeamRole}, + "adversary": {Role: config.RedTeamRole}, + "adversary-2": {ReplicaOf: "adversary"}, + "scanner": {Role: "scanner"}, + "redteam-named": {}, + }}} + ownsRepo := func(_, _ string) bool { return true } + tests := []struct { + agent string + level int + want bool + }{ + {agent: "redteam", level: 6, want: true}, + {agent: "adversary", level: 6, want: true}, + {agent: "adversary-2", level: 6, want: true}, + {agent: "redteam", level: 2, want: true}, + {agent: "scanner", level: 6, want: false}, + {agent: "redteam-named", level: 6, want: false}, + } + for _, tt := range tests { + t.Run(tt.agent, func(t *testing.T) { + if got := shouldHoldAgentPR(tt.agent, "hive", tt.level, ownsRepo, cfg.IsRedTeamAgent); got != tt.want { + t.Fatalf("shouldHoldAgentPR(%q, L%d) = %v, want %v", tt.agent, tt.level, got, tt.want) + } + }) + } + if shouldHoldAgentPR("redteam", "hive", 6, ownsRepo, nil) { + t.Fatal("nil alwaysHold must add no reason to hold") + } +} diff --git a/src/cmd/hive/run_loop_deps_test.go b/src/cmd/hive/run_loop_deps_test.go index bef9bdff5d..acc2af2af4 100644 --- a/src/cmd/hive/run_loop_deps_test.go +++ b/src/cmd/hive/run_loop_deps_test.go @@ -170,6 +170,99 @@ func TestRunLoopWithRunsFirstCycleThenTicks(t *testing.T) { } } +// hivecommons/hive#17467: a hot-reload delivered while a governor tick holds +// cfgReloadMu must not wait for the tick and must be applied before that +// tick's persist, so the persist saves the reloaded config (not the one the +// tick started from) and the governor state is not deferred a tick. The +// shutdown persist also saves the reloaded config. +func TestRunLoopWithAppliesMidCycleReloadWithoutClobbering(t *testing.T) { + b, log, cancel := newLoopBoot(t, 60, 0) + b.reloadApply = func(newCfg *config.Config) (int, int) { + *b.cfg = *newCfg + return 0, 0 + } + gov := newFakeTicker() + h := &loopHarness{startupOK: true, pending: []*fakeTicker{gov}, persisted: make(chan struct{}, 8)} + deps := h.deps() + + var persistedRepos [][]string + basePersist := deps.persist + deps.persist = func(b *boot) { + persistedRepos = append(persistedRepos, append([]string(nil), b.cfg.Project.Repos...)) + basePersist(b) + } + baseEval := deps.runEval + deps.runEval = func(b *boot, restarted []string, source evalCycleSource) { + baseEval(b, restarted, source) + if len(h.evals) != 2 { + return + } + // The watcher fires on its own goroutine while this tick holds + // cfgReloadMu; it must return without waiting for the tick. + newCfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{Agents: map[string]config.AgentConfig{"alpha": {Enabled: true}}}} + newCfg.Governor.EvalIntervalS = 60 + newCfg.Project.Repos = []string{"reloaded"} + submitted := make(chan struct{}) + go func() { + b.submitConfigReload(newCfg) + close(submitted) + }() + select { + case <-submitted: + case <-time.After(5 * time.Second): + t.Error("config reload blocked behind the governor tick") + } + if sameStringSlice(b.cfg.Project.Repos, []string{"reloaded"}) { + t.Error("reload mutated cfg while the eval cycle was running") + } + } + + done := runLoopAsync(b, deps) + <-h.persisted // startup cycle + gov.fire() // reload lands mid-tick and is applied before its persist + <-h.persisted + cancel() + waitDone(t, done) + + if !sameStringSlice(b.cfg.Project.Repos, []string{"reloaded"}) { + t.Fatalf("repos = %v, want the reloaded config applied", b.cfg.Project.Repos) + } + // startup cycle, the tick the reload landed in, shutdown. + if len(persistedRepos) != 3 || len(persistedRepos[0]) != 0 || + !sameStringSlice(persistedRepos[1], []string{"reloaded"}) || !sameStringSlice(persistedRepos[2], []string{"reloaded"}) { + t.Fatalf("persisted repos per save = %v, want [[] [reloaded] [reloaded]]", persistedRepos) + } + if !strings.Contains(log.String(), "config reload deferred") { + t.Fatalf("deferred reload not logged:\n%s", log.String()) + } +} + +// hivecommons/hive#17467: the shutdown persist takes cfgReloadMu, so it cannot +// save while a reload is being applied. +func TestRunLoopWithShutdownPersistTakesConfigLock(t *testing.T) { + b, _, cancel := newLoopBoot(t, 60, 0) + gov := newFakeTicker() + h := &loopHarness{startupOK: true, pending: []*fakeTicker{gov}, persisted: make(chan struct{}, 8)} + done := runLoopAsync(b, h.deps()) + <-h.persisted // startup cycle + + b.lockCfg() + cancel() + select { + case <-h.persisted: + b.unlockCfg() + t.Fatal("shutdown persist ran while cfgReloadMu was held") + case <-time.After(100 * time.Millisecond): + } + b.unlockCfg() + select { + case <-h.persisted: + case <-time.After(5 * time.Second): + t.Fatal("shutdown persist did not run after cfgReloadMu was released") + } + waitDone(t, done) +} + // staticFleet is a watchdog.Fleet with no agents, so Tick is a no-op and the // test only exercises runLoop's mode re-resolution. type staticFleet struct{} diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 39baf8aa65..e386f0319d 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -337,7 +337,9 @@ type AgentProcess struct { // lastTokenRestart beside it. tokenRestartAttempts int // tokenRestartGaveUp latches once the cap is hit so the diagnosis is logged - // a single time rather than every poll (~3s). Cleared alongside the counter. + // a single time rather than every poll (~3s). Cleared by a fresh fire in + // decideTokenRestart, by clearTokenRestartCap, and by the per-boot re-arm + // (rearmTokenRestartCap) only once the rolling window has drained (#17483). tokenRestartGaveUp bool // tokenRestartFiredAt is the rolling ledger of token-triggered restart // times inside tokenRestartWindow. Unlike tokenRestartAttempts it is NOT @@ -435,9 +437,10 @@ type AgentProcess struct { // this as "Waiting on CI" instead of "Working" so a stalled-on-CI agent // no longer looks indistinguishable from one making progress. AwaitingCI bool - TransientNudges int // total transient-API-error nudges sent (surfaced to the dashboard) - launchGen int // increments per launch; stale deliverStartupKick goroutines check it and drop - lastInferKickMarks int // no-action watchdog: tool-marker count in pane+scrollback just after kick delivery + TransientNudges int // total transient-API-error nudges sent (surfaced to the dashboard) + launchGen int // increments per launch; stale deliverStartupKick goroutines check it and drop + lastCLILaunchAt time.Time // when the CLI was last typed into the pane; dates watchdog boot grace on relaunch (#17320) + lastInferKickMarks int // no-action watchdog: tool-marker count in pane+scrollback just after kick delivery ProviderErrorClass string ProviderErrorLine string ProviderErrorBackoffUntil time.Time diff --git a/src/crux/agent/manager_kick.go b/src/crux/agent/manager_kick.go index 781121f2b9..59142c3de1 100644 --- a/src/crux/agent/manager_kick.go +++ b/src/crux/agent/manager_kick.go @@ -114,8 +114,7 @@ func (m *Manager) SendKickWithSource(name string, message string, source string) // (the default). SendKick has no context parameter, so this span roots at // Background; it still captures the kick leg of the governor→agent // lifecycle. Ended before delivery bookkeeping via defer. - _, span := m.startSpan(context.Background(), "agent.send_kick", - attribute.String("agent.name", name)) + _, span := m.startSpan(context.Background(), "agent.send_kick") defer span.End() // Kick duration/outcome metrics; role stays kickRoleUnknown until the @@ -131,6 +130,7 @@ func (m *Manager) SendKickWithSource(name string, message string, source string) return fmt.Errorf("agent %s not found", name) } role = name + span.SetAttributes(attribute.String("agent.name", role)) trigger := "send-kick" if strings.TrimSpace(source) != "" { diff --git a/src/crux/agent/manager_launch.go b/src/crux/agent/manager_launch.go index 76c154ce58..52fb0b7870 100644 --- a/src/crux/agent/manager_launch.go +++ b/src/crux/agent/manager_launch.go @@ -338,8 +338,7 @@ func (m *Manager) launchInTmux(ctx context.Context, agent *AgentProcess) error { // clean; a relaunch on the same rejected id keeps the count and the kick // backoff, because nothing about it changed (model_rejection.go). m.clearStaleModelRejectionLocked(agent, agent.effectiveModel(), now) - agent.StartedAt = &now - agent.launchGen++ + m.markCLILaunchedLocked(agent, now) m.logger.Info("audit: agent started", "name", agent.Name, "backend", backend, diff --git a/src/crux/agent/manager_poll.go b/src/crux/agent/manager_poll.go index c8d4273603..0065b1a7c0 100644 --- a/src/crux/agent/manager_poll.go +++ b/src/crux/agent/manager_poll.go @@ -96,9 +96,9 @@ func (m *Manager) pollTmuxOutputForAgent(agent *AgentProcess, ctx context.Contex if agent.shouldResetTokenRestartCap(paneHasCLIMarker(strings.Join(tail, "\n")), startedAt, time.Now()) { // A future "token appeared, nudge it" restart is now a // fresh theory rather than a repeat of one that already - // failed. Reset both halves of the cap together. - agent.tokenRestartAttempts = 0 - agent.tokenRestartGaveUp = false + // failed. The latch survives while the rolling window is + // still full (#17483). + agent.rearmTokenRestartCap(time.Now()) } } diff --git a/src/crux/agent/resumehandle/resumehandle.go b/src/crux/agent/resumehandle/resumehandle.go index 9f48bbd012..c61b7057da 100644 --- a/src/crux/agent/resumehandle/resumehandle.go +++ b/src/crux/agent/resumehandle/resumehandle.go @@ -109,10 +109,19 @@ type backendResumeLayout struct { // in a mktemp file that is discarded on every relaunch (agy_turn.go), so a // captured id would point at a conversation the next launch never reopens. var backendResumeLayouts = map[string]backendResumeLayout{ + // claude keeps the session transcript at ~/.claude/projects//.jsonl. + // Per-subagent transcripts under /subagents/agent-*.jsonl are not + // sessions, so only a UUID-named file yields an id. "claude": { - root: func(home, _ string) string { return filepath.Join(home, ".claude", "projects") }, - ext: ".jsonl", - id: func(name string) string { return trimResumeName(name, "", ".jsonl") }, + root: func(home, _ string) string { return filepath.Join(home, ".claude", "projects") }, + ext: ".jsonl", + id: func(name string) string { + id := trimResumeName(name, "", ".jsonl") + if !looksLikeUUID(id) { + return "" + } + return id + }, command: func(id string) string { return "claude --resume " + id }, }, "copilot": { diff --git a/src/crux/agent/resumehandle/resumehandle_test.go b/src/crux/agent/resumehandle/resumehandle_test.go index 144c0c6cfd..df06cc1680 100644 --- a/src/crux/agent/resumehandle/resumehandle_test.go +++ b/src/crux/agent/resumehandle/resumehandle_test.go @@ -70,6 +70,26 @@ func TestCaptureResumeHandle_ClaudeNamesNewestTranscript(t *testing.T) { } } +func TestCaptureResumeHandle_ClaudeIgnoresSubagentTranscripts(t *testing.T) { + home := homeForCapture(t) + now := time.Now() + const sid = "11111111-2222-3333-4444-555555555555" + project := filepath.Join(home, ".claude", "projects", "-data-work-hive") + writeResumeTranscript(t, filepath.Join(project, sid+".jsonl"), now.Add(-time.Hour)) + writeResumeTranscript(t, filepath.Join(project, sid, "subagents", "agent-0123456789abcdef.jsonl"), now) + + h, ok := capture("claude", now) + if !ok { + t.Fatal("no handle captured for claude") + } + if h.SessionID != sid { + t.Errorf("session id = %q, want the session transcript's %q", h.SessionID, sid) + } + if h.Command != "claude --resume "+sid { + t.Errorf("command = %q", h.Command) + } +} + func TestCaptureResumeHandle_CopilotUsesSessionDirectories(t *testing.T) { home := homeForCapture(t) now := time.Now() diff --git a/src/crux/agent/stuck_login_diagnosis.go b/src/crux/agent/stuck_login_diagnosis.go index d0e1481dbf..9dd5726d2e 100644 --- a/src/crux/agent/stuck_login_diagnosis.go +++ b/src/crux/agent/stuck_login_diagnosis.go @@ -150,9 +150,26 @@ func (a *AgentProcess) decideTokenRestart(now time.Time) tokenRestartAction { a.tokenRestartAttempts++ a.lastTokenRestart = now a.tokenRestartFiredAt = append(a.tokenRestartFiredAt, now) + // A fresh attempt is a new theory: if this episode also fails, the + // give-up diagnosis must log again, once. + a.tokenRestartGaveUp = false return tokenRestartFire } +// rearmTokenRestartCap is the poller's per-boot re-arm: it zeroes the attempt +// counter but keeps the give-up latch while the rolling window ledger would +// make decideTokenRestart give up again straight away. Clearing it +// unconditionally made every pane flap (login line gone, then back) re-run the +// give-up WARN and diagnosis, once per flap rather than once per episode +// (#17483). The ledger itself is deliberately not reset: that would re-enable +// the restart storm the window ended (#6578). +func (a *AgentProcess) rearmTokenRestartCap(now time.Time) { + a.tokenRestartAttempts = 0 + if a.tokenRestartsInWindow(now) < tokenRestartWindowMax { + a.tokenRestartGaveUp = false + } +} + // tokenRestartsInWindow prunes the rolling ledger to tokenRestartWindow and // returns how many token-triggered restarts fired inside it. func (a *AgentProcess) tokenRestartsInWindow(now time.Time) int { @@ -170,7 +187,8 @@ func (a *AgentProcess) tokenRestartsInWindow(now time.Time) int { // clearTokenRestartCap is the operator-facing reset: it re-arms the per-boot // cap, the give-up latch AND the rolling window ledger together, so a reset // or resume genuinely allows the heal to run again. The poller's own re-arm -// (shouldResetTokenRestartCap) deliberately touches only the first two. +// (rearmTokenRestartCap) deliberately leaves the ledger alone and keeps the +// latch while the ledger is full. func (a *AgentProcess) clearTokenRestartCap() { a.tokenRestartAttempts = 0 a.tokenRestartGaveUp = false diff --git a/src/crux/agent/stuck_login_diagnosis_test.go b/src/crux/agent/stuck_login_diagnosis_test.go index e165b60c90..2188114b9c 100644 --- a/src/crux/agent/stuck_login_diagnosis_test.go +++ b/src/crux/agent/stuck_login_diagnosis_test.go @@ -534,3 +534,47 @@ func TestDiagnoseStuckLoginUnreadableDoesNotBlameTheAgent(t *testing.T) { t.Errorf("diagnosis should say the identity is undetermined from the hive's view:\n%s", got) } } + +func TestRearmTokenRestartCapKeepsLatchWhileWindowFull(t *testing.T) { + now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) + tests := []struct { + name string + age time.Duration + wantGaveUp bool + wantGiveUp bool + }{ + {"ledger full inside window keeps latch", time.Hour, true, true}, + {"ledger expired clears latch", tokenRestartWindow + time.Minute, false, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + a := &AgentProcess{Name: "quality", tokenRestartGaveUp: true, tokenRestartAttempts: tokenRestartMaxAttempts} + for i := 0; i < tokenRestartWindowMax; i++ { + a.tokenRestartFiredAt = append(a.tokenRestartFiredAt, now.Add(-tc.age)) + } + a.rearmTokenRestartCap(now) + if a.tokenRestartAttempts != 0 { + t.Fatalf("attempts = %d, want 0", a.tokenRestartAttempts) + } + if a.tokenRestartGaveUp != tc.wantGaveUp { + t.Fatalf("gaveUp = %v, want %v", a.tokenRestartGaveUp, tc.wantGaveUp) + } + if tc.wantGiveUp { + if got := a.decideTokenRestart(now); got != tokenRestartGiveUp { + t.Fatalf("decide = %v, want give-up", got) + } + } + }) + } +} + +func TestDecideTokenRestartFireClearsLatch(t *testing.T) { + a := &AgentProcess{Name: "quality", tokenRestartGaveUp: true} + now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) + if got := a.decideTokenRestart(now); got != tokenRestartFire { + t.Fatalf("decide = %v, want fire", got) + } + if a.tokenRestartGaveUp { + t.Fatal("gaveUp still latched after a fresh fire") + } +} diff --git a/src/crux/agent/token_restart_boot_pane_test.go b/src/crux/agent/token_restart_boot_pane_test.go index 25c80489e0..2eea9420de 100644 --- a/src/crux/agent/token_restart_boot_pane_test.go +++ b/src/crux/agent/token_restart_boot_pane_test.go @@ -76,9 +76,11 @@ func TestPollerUsesTokenRestartCapResetGate(t *testing.T) { if !strings.Contains(string(src), "shouldResetTokenRestartCap(") { t.Fatal("pollTmuxOutputForAgent must call shouldResetTokenRestartCap; otherwise the boot pane re-arms the restart storm (#8711)") } - if strings.Contains(string(src), "agent.tokenRestartAttempts = 0\n\t\t\t\tagent.tokenRestartGaveUp = false") && - !strings.Contains(string(src), "if agent.shouldResetTokenRestartCap") { - t.Fatal("poller resets token restart attempts without the cap reset gate") + if !strings.Contains(string(src), "agent.rearmTokenRestartCap(") { + t.Fatal("pollTmuxOutputForAgent must re-arm via rearmTokenRestartCap; an inline reset wipes the give-up latch on every pane flap (#17483)") + } + if strings.Contains(string(src), "agent.tokenRestartGaveUp = false") { + t.Fatal("poller clears tokenRestartGaveUp inline instead of through rearmTokenRestartCap (#17483)") } } @@ -92,8 +94,7 @@ func (a *AgentProcess) simulatePollTick(t *testing.T, pane []string, startedAt * } else { *loginStreak = 0 if a.shouldResetTokenRestartCap(hasCLI, startedAt, now) { - a.tokenRestartAttempts = 0 - a.tokenRestartGaveUp = false + a.rearmTokenRestartCap(now) } } if !showsLogin || *loginStreak < loginStreakRestartMin { @@ -234,21 +235,26 @@ func TestTokenRestartCapReArmsAfterGenuineRecovery(t *testing.T) { loginStreak := 0 a.simulatePollTick(t, readyPane, &started, now, &loginStreak) - if a.tokenRestartGaveUp { - t.Fatal("latch survived a genuine recovery: a real login would never re-enable the nudge") - } if a.tokenRestartAttempts != 0 { t.Fatalf("attempts = %d after recovery, want 0", a.tokenRestartAttempts) } // The per-boot cap is re-armed, but the rolling 24h budget was spent by // the three restarts above (#12466): a nudge inside the window still - // gives up, and a nudge once the window has rolled on fires again. + // gives up, so the give-up latch must hold through the recovery or that + // give-up would re-log the WARN once per pane flap (#17483). A nudge once + // the window has rolled on fires again and drops the latch. + if !a.tokenRestartGaveUp { + t.Fatal("latch cleared by a recovery inside the window: the next give-up would re-log the diagnosis (#17483)") + } if got := a.decideTokenRestart(now); got != tokenRestartGiveUp { t.Fatalf("after recovery inside the window: got %v, want giveUp", got) } if got := a.decideTokenRestart(now.Add(tokenRestartWindow + time.Second)); got != tokenRestartFire { t.Fatalf("after recovery and a full window: got %v, want fire", got) } + if a.tokenRestartGaveUp { + t.Fatal("latch survived a fresh fire after the window drained: a real login would never re-enable the nudge") + } } // TestShouldResetTokenRestartCapConditions pins each branch of the rule, diff --git a/src/crux/agent/tracing_test.go b/src/crux/agent/tracing_test.go index 36ba55e8be..6694aaa531 100644 --- a/src/crux/agent/tracing_test.go +++ b/src/crux/agent/tracing_test.go @@ -5,7 +5,10 @@ import ( "log/slog" "testing" + "github.com/hivecommons/hive/crux/config" "go.opentelemetry.io/otel/attribute" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace/noop" ) @@ -25,8 +28,8 @@ func TestSetSpanStarterRoutesRuntimeSpans(t *testing.T) { if gotName != "agent.send_kick" { t.Fatalf("span name = %q, want agent.send_kick", gotName) } - if len(gotAttrs) != 1 || gotAttrs[0].Key != "agent.name" || gotAttrs[0].Value.AsString() != "missing" { - t.Fatalf("span attrs = %v, want agent.name=missing", gotAttrs) + if len(gotAttrs) != 0 { + t.Fatalf("span attrs = %v, want none before the kick target resolves", gotAttrs) } m.SetSpanStarter(nil) @@ -41,3 +44,36 @@ func TestSetSpanStarterRoutesRuntimeSpans(t *testing.T) { t.Fatal("default span starter returned a nil span") } } + +func TestSendKickSpanAgentNameOnlyAfterResolve(t *testing.T) { + rec := tracetest.NewSpanRecorder() + tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(rec)) + m := NewManager(map[string]config.AgentConfig{ + "known": {Backend: "claude"}, + }, slog.Default(), ProjectContext{}) + m.SetSpanStarter(func(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span) { + return tp.Tracer("test").Start(ctx, name, trace.WithAttributes(attrs...)) + }) + + _ = m.SendKick("caller-garbage-name", "hello") + _ = m.SendKick("known", "hello") + + spans := rec.Ended() + if len(spans) != 2 { + t.Fatalf("ended spans = %d, want 2", len(spans)) + } + for _, kv := range spans[0].Attributes() { + if kv.Key == "agent.name" { + t.Fatalf("unknown-name span carries agent.name=%q", kv.Value.AsString()) + } + } + var got string + for _, kv := range spans[1].Attributes() { + if kv.Key == "agent.name" { + got = kv.Value.AsString() + } + } + if got != "known" { + t.Fatalf("known-agent span agent.name = %q, want known", got) + } +} diff --git a/src/crux/agent/watchdog_fleet.go b/src/crux/agent/watchdog_fleet.go index 7ab2250b1e..426173ed0e 100644 --- a/src/crux/agent/watchdog_fleet.go +++ b/src/crux/agent/watchdog_fleet.go @@ -148,7 +148,9 @@ func (f WatchdogFleet) Observe(name string) (watchdog.Observation, error) { // StartedAt dates the current launch so the reconciler can suppress dead // verdicts during boot. Copied by value: the field is a pointer the - // manager mutates on relaunch. + // manager mutates on relaunch. LastLaunchAt is the most recent CLI spawn + // (markCLILaunchedLocked), which a restored or resumed session can leave + // StartedAt lagging behind. var startedAt time.Time providerClass := "" providerLine := "" @@ -156,6 +158,7 @@ func (f WatchdogFleet) Observe(name string) (watchdog.Observation, error) { if agent.StartedAt != nil { startedAt = *agent.StartedAt } + lastLaunchAt := agent.lastCLILaunchAt if f.M.providerErrorBackoffRemainingLocked(agent, time.Now()) > 0 { providerClass = agent.ProviderErrorClass providerLine = agent.ProviderErrorLine @@ -170,6 +173,7 @@ func (f WatchdogFleet) Observe(name string) (watchdog.Observation, error) { ShowsLoginPrompt: needsLogin || paneShowsLoginPrompt(strings.Split(pane, "\n")), LastChange: lastChange, StartedAt: startedAt, + LastLaunchAt: lastLaunchAt, AuthAvailable: authAvailable, AuthKnown: authKnown, CredentialProven: credentialProven, @@ -458,3 +462,13 @@ func newestMtimeBounded(root string, maxDepth int) (time.Time, bool) { func (m *Manager) WatchdogSource() watchdog.Source { return WatchdogFleet{M: m} } + +// markCLILaunchedLocked records a completed CLI launch into the pane: the +// agent's StartedAt, the launch generation stale startup-kick goroutines +// check, and the relaunch timestamp the watchdog dates its boot grace from +// (#17320). Caller holds m.mu. +func (m *Manager) markCLILaunchedLocked(agent *AgentProcess, now time.Time) { + agent.StartedAt = &now + agent.launchGen++ + agent.lastCLILaunchAt = now +} diff --git a/src/crux/agent/watchdog_fleet_test.go b/src/crux/agent/watchdog_fleet_test.go index d0d000ced9..bd5febe1f2 100644 --- a/src/crux/agent/watchdog_fleet_test.go +++ b/src/crux/agent/watchdog_fleet_test.go @@ -488,6 +488,59 @@ func TestWatchdogObserveCarriesStartedAt(t *testing.T) { if !obs.StartedAt.Equal(started) { t.Fatalf("StartedAt = %v, want %v — without it boot grace cannot apply", obs.StartedAt, started) } + if !obs.LastLaunchAt.IsZero() { + t.Fatalf("LastLaunchAt = %v, want zero before any CLI launch is recorded", obs.LastLaunchAt) + } +} + +// TestWatchdogObserveCarriesLastLaunchAt pins the manager half of #17320: a +// mid-life CLI relaunch must reach the classifier as LastLaunchAt, distinct +// from the agent's original StartedAt, or the relaunch gets no boot grace and +// its login-chrome flash pages an operator. +func TestWatchdogObserveCarriesLastLaunchAt(t *testing.T) { + m, _ := newWatchdogTestManager(t, map[string]string{"a1": "copilot"}) + started := time.Date(2026, 8, 23, 11, 30, 0, 0, time.UTC) + relaunched := started.Add(22 * time.Hour) + m.agents["a1"].StartedAt = &started + m.agents["a1"].lastCLILaunchAt = relaunched + + obs, err := WatchdogFleet{M: m}.Observe("a1") + if err != nil { + t.Fatal(err) + } + if !obs.StartedAt.Equal(started) { + t.Fatalf("StartedAt = %v, want %v — a relaunch must not rewrite the agent's start", obs.StartedAt, started) + } + if !obs.LastLaunchAt.Equal(relaunched) { + t.Fatalf("LastLaunchAt = %v, want %v — without it a relaunch gets no boot grace", obs.LastLaunchAt, relaunched) + } +} + +// TestMarkCLILaunchedLockedStampsEveryLaunchField guards the single write +// point launchInTmux uses: StartedAt, the launch generation stale startup-kick +// goroutines check, and the relaunch timestamp the watchdog dates boot grace +// from must all move together. +func TestMarkCLILaunchedLockedStampsEveryLaunchField(t *testing.T) { + m, _ := newWatchdogTestManager(t, map[string]string{"a1": "copilot"}) + agent := m.agents["a1"] + first := time.Date(2026, 8, 23, 11, 30, 0, 0, time.UTC) + second := first.Add(22 * time.Hour) + + m.mu.Lock() + gen := agent.launchGen + m.markCLILaunchedLocked(agent, first) + m.markCLILaunchedLocked(agent, second) + m.mu.Unlock() + + if agent.StartedAt == nil || !agent.StartedAt.Equal(second) { + t.Fatalf("StartedAt = %v, want %v", agent.StartedAt, second) + } + if agent.launchGen != gen+2 { + t.Fatalf("launchGen = %d, want %d — one increment per launch", agent.launchGen, gen+2) + } + if !agent.lastCLILaunchAt.Equal(second) { + t.Fatalf("lastCLILaunchAt = %v, want %v", agent.lastCLILaunchAt, second) + } } func TestWatchdogFleetPauseRestartDelegation(t *testing.T) { diff --git a/src/crux/agentmode/agentmode.go b/src/crux/agentmode/agentmode.go index b6c195822f..c98890d905 100644 --- a/src/crux/agentmode/agentmode.go +++ b/src/crux/agentmode/agentmode.go @@ -125,9 +125,34 @@ func TokenTierForRole(m AgentMode, role string) string { if m == ModeAdvisory && role == ReviewerRole { return "reviewer" } + if role == SecCheckRole { + switch m { + case ModeIssuesAndPRs: + return SecCheckTier + case ModeIssuesPRsMerge: + return SecCheckTrustedTier + } + } return m.TokenTier() } +// SecCheckRole is the agent role whose token at ISSUES_AND_PRS and above +// additionally carries Dependabot alerts read (#17426, #17496). Like the reviewer refinement it +// is a role, not a rung on the mode ladder: a sec-check agent mints the +// SecCheckTier (the contributor set plus vulnerability_alerts:read) so that +// no other contributor-tier agent's token is widened by the grant. At +// ISSUES_PRS_MERGE it mints SecCheckTrustedTier, the trusted set plus the +// same grant. +const SecCheckRole = "sec-check" + +// SecCheckTier is the scoped-token tier TokenTierForRole yields for an +// ISSUES_AND_PRS agent with SecCheckRole. +const SecCheckTier = "sec-check" + +// SecCheckTrustedTier is the scoped-token tier TokenTierForRole yields for an +// ISSUES_PRS_MERGE agent with SecCheckRole (#17496). +const SecCheckTrustedTier = "sec-check-trusted" + // CanComment reports whether an agent at this mode may post a comment on an // issue. It sits at the ISSUES_ONLY rung: the newcomer token tier is the first // with Issues:write, and ADVISORY (advisor, and the reviewer refinement whose @@ -137,8 +162,10 @@ func TokenTierForRole(m AgentMode, role string) string { func (m AgentMode) CanComment() bool { return m >= ModeIssuesOnly } // ModeForTokenTier is the inverse of TokenTier / TokenTierForRole: the mode a -// scoped-token tier corresponds to. The reviewer tier maps to ADVISORY (it is -// a role refinement of that mode, see TokenTierForRole); "merger" is the +// scoped-token tier corresponds to. The reviewer tier maps to ADVISORY and the +// sec-check tier to ISSUES_AND_PRS and the sec-check-trusted tier to +// ISSUES_PRS_MERGE (all are role refinements of their mode, +// see TokenTierForRole); "merger" is the // contribute queue's name for the tier above trusted and shares its mode. An // unknown tier reports ADVISORY and false, so a caller that gates a write on // the result fails closed. @@ -148,9 +175,9 @@ func ModeForTokenTier(tier string) (AgentMode, bool) { return ModeAdvisory, true case "newcomer": return ModeIssuesOnly, true - case "contributor": + case "contributor", SecCheckTier: return ModeIssuesAndPRs, true - case "trusted", "merger": + case "trusted", "merger", SecCheckTrustedTier: return ModeIssuesPRsMerge, true default: return ModeAdvisory, false diff --git a/src/crux/agentmode/claim_comment_test.go b/src/crux/agentmode/claim_comment_test.go index 189763633c..f0916728de 100644 --- a/src/crux/agentmode/claim_comment_test.go +++ b/src/crux/agentmode/claim_comment_test.go @@ -50,6 +50,9 @@ func TestModeForTokenTier_InvertsTokenTier(t *testing.T) { if got, ok := ModeForTokenTier("merger"); !ok || got != ModeIssuesPRsMerge { t.Errorf("merger tier = %v,%v; want ISSUES_PRS_MERGE", got, ok) } + if got, ok := ModeForTokenTier(SecCheckTrustedTier); !ok || got != ModeIssuesPRsMerge { + t.Errorf("sec-check-trusted tier = %v,%v; want ISSUES_PRS_MERGE", got, ok) + } if got, ok := ModeForTokenTier("revoked"); ok || got != ModeAdvisory || got.CanComment() { t.Errorf("unknown tier = %v,%v; must fail closed to ADVISORY", got, ok) } diff --git a/src/crux/agentmode/reviewer_tier_test.go b/src/crux/agentmode/reviewer_tier_test.go index a952a1bafd..2f449f412d 100644 --- a/src/crux/agentmode/reviewer_tier_test.go +++ b/src/crux/agentmode/reviewer_tier_test.go @@ -62,3 +62,44 @@ func TestTokenTierForRole_ReviewerGainsNoModeCapability(t *testing.T) { t.Error("ADVISORY reports CanMerge — the reviewer's safety asymmetry depends on this staying false") } } + +// The sec-check role refines ISSUES_AND_PRS into a tier whose App token adds +// Dependabot alerts read (#17426). It is scoped to that one role and mode: +// every other contributor-tier agent, and a sec-check agent at any other mode, +// keeps the plain mode tier — except ISSUES_PRS_MERGE, which mints the +// sec-check-trusted tier (#17496). +func TestTokenTierForRole_SecCheckGetsAlertsCapableTier(t *testing.T) { + if got := TokenTierForRole(ModeIssuesAndPRs, SecCheckRole); got != SecCheckTier { + t.Errorf("ISSUES_AND_PRS sec-check minted %q, want %q", got, SecCheckTier) + } + for _, role := range []string{"", "scanner", ReviewerRole} { + if got := TokenTierForRole(ModeIssuesAndPRs, role); got != "contributor" { + t.Errorf("ISSUES_AND_PRS %q minted %q, want contributor — only the sec-check role is refined", role, got) + } + } + for _, tc := range []struct { + mode AgentMode + want string + }{ + {ModeAdvisory, "advisor"}, + {ModeIssuesOnly, "newcomer"}, + } { + if got := TokenTierForRole(tc.mode, SecCheckRole); got != tc.want { + t.Errorf("%v sec-check minted %q, want %q", tc.mode, got, tc.want) + } + } + if got := TokenTierForRole(ModeIssuesPRsMerge, SecCheckRole); got != SecCheckTrustedTier { + t.Errorf("ISSUES_PRS_MERGE sec-check minted %q, want %q", got, SecCheckTrustedTier) + } + for _, role := range []string{"", "scanner", ReviewerRole} { + if got := TokenTierForRole(ModeIssuesPRsMerge, role); got != "trusted" { + t.Errorf("ISSUES_PRS_MERGE %q minted %q, want trusted — only the sec-check role is refined", role, got) + } + } + if mode, ok := ModeForTokenTier(SecCheckTrustedTier); !ok || mode != ModeIssuesPRsMerge { + t.Errorf("ModeForTokenTier(%q) = %v, %v; want ISSUES_PRS_MERGE, true", SecCheckTrustedTier, mode, ok) + } + if mode, ok := ModeForTokenTier(SecCheckTier); !ok || mode != ModeIssuesAndPRs { + t.Errorf("ModeForTokenTier(%q) = %v, %v; want ISSUES_AND_PRS, true", SecCheckTier, mode, ok) + } +} diff --git a/src/crux/agentstep/agentstep.go b/src/crux/agentstep/agentstep.go index 1a831e2da5..d295542b75 100644 --- a/src/crux/agentstep/agentstep.go +++ b/src/crux/agentstep/agentstep.go @@ -21,6 +21,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "os" "path/filepath" "strings" @@ -38,6 +39,12 @@ const ( MaxRetries = 5 // MaxPromptBytes bounds an inline prompt. MaxPromptBytes = 1 << 20 + // MaxPromptFileBytes bounds the workspace files the host reads whole: a + // prompt_path file (the run owner's) and a backend's answer file (the + // sandboxed agent's). Everything else a caller or an agent can shape + // is bounded; without this the two files were the one way to make the + // server allocate without limit. + MaxPromptFileBytes = 16 << 20 // workspaceDir is where prompts and backend answer files go inside the // workspace, next to the agent sandbox's .hive. workspaceDir = ".crux/steps" @@ -158,10 +165,23 @@ func validate(host Host, req api.StepRequest) (plan, error) { if filepath.IsAbs(rel) || rel == ".." || strings.HasPrefix(rel, "../") { return p, &RequestError{"prompt_path must be relative to the workspace and stay inside it"} } - data, err := os.ReadFile(filepath.Join(host.Workspace, rel)) + root, err := os.OpenRoot(host.Workspace) if err != nil { return p, &RequestError{fmt.Sprintf("prompt_path %q: %v", req.PromptPath, err)} } + data, err := readBounded(root, rel, MaxPromptFileBytes) + root.Close() + if err != nil { + if errors.Is(err, errFileTooLarge) { + return p, &RequestError{fmt.Sprintf("prompt_path %q is over %d bytes", req.PromptPath, MaxPromptFileBytes)} + } + // os.Root's escape error is unexported; a symlink leaving the + // workspace is reported like a lexical escape. + if strings.Contains(err.Error(), "escapes from parent") { + return p, &RequestError{"prompt_path must be relative to the workspace and stay inside it"} + } + return p, &RequestError{fmt.Sprintf("prompt_path %q: %v", req.PromptPath, err)} + } p.prompt = string(data) default: return p, &RequestError{"one of prompt or prompt_path is required"} @@ -251,10 +271,18 @@ func runAttempt(ctx context.Context, host Host, store Store, step api.Step, p pl spec := p.spec spec.PromptRel = rel + fmt.Sprintf("/prompt-%d.md", n) spec.AnswerRel = rel + fmt.Sprintf("/answer-%d.txt", n) - if err := os.MkdirAll(filepath.Join(host.Workspace, rel), 0o770); err != nil { + // Every host-side workspace access goes through root so a symlink in the + // workspace (provisioned, or planted by the sandboxed agent) cannot + // redirect it outside (#17293). + root, err := os.OpenRoot(host.Workspace) + if err != nil { return a, Outcome{Status: api.StepBackendError, Reason: "writing the prompt: " + host.scrub(err.Error())} } - if err := os.WriteFile(filepath.Join(host.Workspace, filepath.FromSlash(spec.PromptRel)), []byte(prompt), 0o660); err != nil { + defer root.Close() + if err := root.MkdirAll(rel, 0o770); err != nil { + return a, Outcome{Status: api.StepBackendError, Reason: "writing the prompt: " + host.scrub(err.Error())} + } + if err := root.WriteFile(filepath.FromSlash(spec.PromptRel), []byte(prompt), 0o660); err != nil { return a, Outcome{Status: api.StepBackendError, Reason: "writing the prompt: " + host.scrub(err.Error())} } cmd, err := p.backend.Command(spec) @@ -298,7 +326,7 @@ func runAttempt(ctx context.Context, host Host, store Store, step api.Step, p pl out = Outcome{Status: api.StepBackendError, Reason: host.scrub(runErr.Error())} default: out = p.backend.Parse(spec, res, func(rel string) ([]byte, error) { - return os.ReadFile(filepath.Join(host.Workspace, filepath.FromSlash(rel))) + return readBounded(root, filepath.FromSlash(rel), MaxPromptFileBytes) }) out.Reason = host.scrub(out.Reason) } @@ -316,6 +344,28 @@ func runAttempt(ctx context.Context, host Host, store Store, step api.Step, p pl return a, out } +// errFileTooLarge is readBounded's refusal of a file over its bound. +var errFileTooLarge = errors.New("agentstep: file exceeds the size bound") + +// readBounded reads rel through root, refusing with errFileTooLarge once +// more than max bytes are present, so a file in the workspace can never +// make the host allocate without limit. +func readBounded(root *os.Root, rel string, max int64) ([]byte, error) { + f, err := root.Open(rel) + if err != nil { + return nil, err + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, max+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > max { + return nil, errFileTooLarge + } + return data, nil +} + // finish writes the terminal record and announces it on the run. func finish(host Host, store Store, step api.Step, status, reason string, violations []api.SchemaViolation) api.Step { now := host.now() diff --git a/src/crux/agentstep/agentstep_test.go b/src/crux/agentstep/agentstep_test.go index 35bd5eec52..58033095fc 100644 --- a/src/crux/agentstep/agentstep_test.go +++ b/src/crux/agentstep/agentstep_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" "path/filepath" + "runtime" "strings" "sync" "testing" @@ -223,6 +224,114 @@ func TestPromptPathReadsFromTheWorkspace(t *testing.T) { } } +func TestPromptPathOverTheBoundIsRefused(t *testing.T) { + f := newFixture(t, answers(`{"verdict":"pass"}`)) + // A sparse file: the bound is on bytes present, not bytes on disk. + if err := os.WriteFile(filepath.Join(f.host.Workspace, "task.md"), nil, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Truncate(filepath.Join(f.host.Workspace, "task.md"), MaxPromptFileBytes+1); err != nil { + t.Fatal(err) + } + req := f.process("", okSchema) + req.PromptPath = "task.md" + _, err := Run(context.Background(), f.host, req) + var reqErr *RequestError + if !errors.As(err, &reqErr) || !strings.Contains(err.Error(), "over") { + t.Fatalf("err = %v, want *RequestError naming the bound", err) + } + if len(f.launcher.prompts) != 0 { + t.Fatalf("an oversize prompt file reached the step: %q", f.launcher.prompts) + } +} + +func TestOversizeAnswerFileIsNotReadIntoMemory(t *testing.T) { + stdout := strings.Join([]string{ + `{"type":"item.completed","item":{"type":"agent_message","text":"{\"verdict\":\"pass\"}"}}`, + `{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}`, + }, "\n") + launcher := &fakeLauncher{} + launcher.results = append(launcher.results, func(_ context.Context, spec sandbox.LaunchSpec) (sandbox.Result, error) { + // The sandboxed agent writes the answer file codex was told to + // produce (--output-last-message ''), here far over the bound. + line := spec.Command[len(spec.Command)-1] + rest := line[strings.Index(line, "--output-last-message '")+len("--output-last-message '"):] + rel := rest[:strings.Index(rest, "'")] + path := filepath.Join(spec.Workspace, filepath.FromSlash(rel)) + if err := os.WriteFile(path, nil, 0o600); err != nil { + return sandbox.Result{}, err + } + if err := os.Truncate(path, MaxPromptFileBytes+1); err != nil { + return sandbox.Result{}, err + } + return sandbox.Result{Stdout: stdout}, nil + }) + f := newFixture(t, launcher) + step := f.run(api.StepRequest{Backend: "codex", Prompt: "judge", OutputSchema: json.RawMessage(okSchema)}) + // The file is refused and the last agent_message on stdout stands in. + if step.Status != api.StepSucceeded || string(step.Answer) != `{"verdict":"pass"}` { + t.Fatalf("step = %+v", step) + } +} + +func TestPromptPathSymlinkOutsideWorkspaceIsRefused(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks need privileges on windows") + } + f := newFixture(t, answers(`{"verdict":"pass"}`)) + outside := filepath.Join(t.TempDir(), "secret") + if err := os.WriteFile(outside, []byte("host-secret"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(f.host.Workspace, "task.md")); err != nil { + t.Fatal(err) + } + req := f.process("", okSchema) + req.PromptPath = "task.md" + _, err := Run(context.Background(), f.host, req) + var reqErr *RequestError + if !errors.As(err, &reqErr) { + t.Fatalf("err = %v, want *RequestError", err) + } + if strings.Contains(err.Error(), "host-secret") || len(f.launcher.prompts) != 0 { + t.Fatalf("outside file reached the step: %v, prompts %q", err, f.launcher.prompts) + } +} + +func TestSymlinkedCruxDirCannotRedirectThePromptWrite(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks need privileges on windows") + } + f := newFixture(t, answers(`{"verdict":"pass"}`)) + outside := t.TempDir() + link := filepath.Join(f.host.Workspace, filepath.FromSlash(workspaceDir)) + if err := os.MkdirAll(filepath.Dir(link), 0o770); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, link); err != nil { + t.Fatal(err) + } + step := Step(t, f) + if step.Status != api.StepBackendError { + t.Fatalf("status = %q, want %q", step.Status, api.StepBackendError) + } + var found []string + _ = filepath.WalkDir(outside, func(p string, d os.DirEntry, _ error) error { + if p != outside { + found = append(found, p) + } + return nil + }) + if len(found) != 0 { + t.Fatalf("wrote outside the workspace: %v", found) + } +} + +func Step(t *testing.T, f *fixture) api.Step { + t.Helper() + return f.run(f.process("hello", okSchema)) +} + func TestRequestRefusals(t *testing.T) { f := newFixture(t, answers(`{}`)) long := strings.Repeat("x", MaxPromptBytes+1) diff --git a/src/crux/api/api.go b/src/crux/api/api.go index d18bcc8437..951e732e16 100644 --- a/src/crux/api/api.go +++ b/src/crux/api/api.go @@ -105,6 +105,16 @@ type Health struct { // that restarted the server sees the uptime reset. StartedAt time.Time `json:"started_at"` UptimeSeconds float64 `json:"uptime_seconds"` + // Tmux is where tmux resolves on PATH, "" when it does not. Every agent + // runs inside tmux, so the route answers 503 (with this body) when empty. + Tmux string `json:"tmux"` + // Error and Code are set only on a non-2xx answer and share their wire + // keys with api.Error, so the 503 body also decodes as the Error that + // Client surfaces in a *StatusError: a caller polling health (the + // supervisor's WaitReady) sees "tmux not found on PATH", not a bare 503: + // WaitReady returns that 503 at once instead of polling to its deadline. + Error string `json:"error,omitempty"` + Code string `json:"code,omitempty"` } // HiveCallback is the wire form of the callback client's status. @@ -257,4 +267,7 @@ const ( // holds; the runtime does not replace definitions. CodeConflict = "conflict" CodeRuntime = "runtime_error" + // CodeUnavailable is a server that is up but cannot serve: GET /v1/health + // answers 503 with it when tmux is missing from PATH. + CodeUnavailable = "unavailable" ) diff --git a/src/crux/api/client.go b/src/crux/api/client.go index 6066734102..86a61a5fb2 100644 --- a/src/crux/api/client.go +++ b/src/crux/api/client.go @@ -135,6 +135,13 @@ func IsUnauthorized(err error) bool { return errors.As(err, &se) && se.Status == http.StatusUnauthorized } +// IsUnavailable reports whether err is a 503 carrying CodeUnavailable: a +// server that is up but cannot serve. +func IsUnavailable(err error) bool { + var se *StatusError + return errors.As(err, &se) && se.Status == http.StatusServiceUnavailable && se.Body.Code == CodeUnavailable +} + // Health is GET /v1/health. func (c *Client) Health(ctx context.Context) (Health, error) { var out Health @@ -358,21 +365,33 @@ func (a Address) target() string { } // WaitReady polls GET /v1/health until it answers or ctx ends; it is for a -// caller that just started `crux serve` and needs to know when to begin. +// caller that just started `crux serve` and needs to know when to begin. A +// 401 or a 503 unavailable verdict (the server is up but cannot serve, e.g. +// "tmux not found on PATH") returns at once. On any other failure it keeps +// polling, and when ctx ends the error wraps ctx.Err() and names the last +// health answer. func (c *Client) WaitReady(ctx context.Context, interval time.Duration) error { if interval <= 0 { interval = 100 * time.Millisecond } t := time.NewTicker(interval) defer t.Stop() + var lastErr error for { if _, err := c.Health(ctx); err == nil { return nil - } else if IsUnauthorized(err) { + } else if IsUnauthorized(err) || IsUnavailable(err) { return err + } else if ctx.Err() == nil || lastErr == nil { + // A probe cut short by ctx ending is not a health answer; keep + // the last real one so the deadline error still names it. + lastErr = err } select { case <-ctx.Done(): + if lastErr != nil { + return fmt.Errorf("%w (last health answer: %v)", ctx.Err(), lastErr) + } return ctx.Err() case <-t.C: } diff --git a/src/crux/api/client_test.go b/src/crux/api/client_test.go index 2268aeff5a..21fcd745a1 100644 --- a/src/crux/api/client_test.go +++ b/src/crux/api/client_test.go @@ -512,3 +512,82 @@ func TestClientStatusTracksReachability(t *testing.T) { t.Fatalf("status after success = %+v", st) } } + +// A 503 health body carries error/code alongside the health fields, so the +// client names the cause (the supervisor's WaitReady logs this error). +func TestClientHealthUnavailableNamesCause(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", ContentTypeJSON) + w.WriteHeader(http.StatusServiceUnavailable) + _ = json.NewEncoder(w).Encode(Health{ + Version: Version, + Error: "tmux not found on PATH: exec: \"tmux\": executable file not found in $PATH", + Code: CodeUnavailable, + }) + })) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "tok") + if err != nil { + t.Fatal(err) + } + _, err = c.Health(context.Background()) + var se *StatusError + if !errors.As(err, &se) || se.Status != http.StatusServiceUnavailable || se.Body.Code != CodeUnavailable { + t.Fatalf("status error: %+v (%v)", se, err) + } + if !strings.Contains(err.Error(), "tmux not found on PATH") { + t.Fatalf("error does not name tmux: %v", err) + } + // WaitReady returns the 503 unavailable verdict at once. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := c.WaitReady(ctx, time.Millisecond); !IsUnavailable(err) { + t.Fatalf("wait ready: %v", err) + } +} + +// WaitReady returns promptly on a 503 unavailable verdict and names its cause. +func TestWaitReadyUnavailableReturnsPromptly(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", ContentTypeJSON) + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"tmux not found on PATH: x","code":"unavailable"}`)) + })) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "tok") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + start := time.Now() + err = c.WaitReady(ctx, time.Hour) + if err == nil || !strings.Contains(err.Error(), "tmux not found on PATH") { + t.Fatalf("wait ready: %v", err) + } + if time.Since(start) > 2*time.Second { + t.Fatalf("wait ready took %v", time.Since(start)) + } +} + +// A health route that keeps failing is polled until ctx ends, and the final +// error carries the last answer next to the deadline. +func TestWaitReadyDeadlineNamesLastAnswer(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "tok") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + err = c.WaitReady(ctx, 5*time.Millisecond) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait ready: %v", err) + } + if !strings.Contains(err.Error(), "500") { + t.Fatalf("error does not name the last status: %v", err) + } +} diff --git a/src/crux/api/cmdlog.go b/src/crux/api/cmdlog.go index eea88d9c36..db749a547a 100644 --- a/src/crux/api/cmdlog.go +++ b/src/crux/api/cmdlog.go @@ -67,8 +67,9 @@ type CommandOutput struct { Truncated bool `json:"truncated,omitempty"` } -// CommandRecord is one dispatched command. ExitCode and EndedAt are -// absent while the command is unfinished. +// CommandRecord is one dispatched command. EndedAt is absent while the +// command is in flight; ExitCode is absent whenever the exit is not known, +// so an unfinished record can carry EndedAt without ExitCode. type CommandRecord struct { Seq int64 `json:"seq"` Command []string `json:"command"` @@ -88,6 +89,11 @@ type CommandRecord struct { // CommandPage is GET /v1/runs/{id}/cmdlog. NextSeq is the seq to pass as // since_seq for the following page; More says one exists now. A caller // following a live run keeps polling with NextSeq after More is false. +// NextSeq never advances past a record with no EndedAt, so a follower +// re-receives an in-flight command until it ends (idempotent by seq); a +// record with EndedAt is terminal whatever its Status. More is never set +// on a page whose NextSeq equals the since_seq it answered, so paging +// while More is true always makes progress. type CommandPage struct { Run string `json:"run"` Commands []CommandRecord `json:"commands"` diff --git a/src/crux/cli/serve.go b/src/crux/cli/serve.go index cd39043aed..3d212966f2 100644 --- a/src/crux/cli/serve.go +++ b/src/crux/cli/serve.go @@ -214,7 +214,8 @@ func (e *Env) openRuns(workDir, path string) (*runs.Service, error) { } svc := runs.New(store, backend, cfg) // S4: every dispatched command is appended to /commands.jsonl - // by the runner, with the default head/tail output policy. + // by the runner, with the default head/tail output policy. It is set + // before Reconcile so a command left in flight gets its ended line. svc.CmdLog = cmdlog.FileOpener(cmdlog.Policy{}) // S5: turn signals go to /signals.jsonl. The book is set // before Reconcile so a run left in flight gets its done signal. diff --git a/src/crux/cmdlog/cmdlog.go b/src/crux/cmdlog/cmdlog.go index 347a4c3319..222180cf77 100644 --- a/src/crux/cmdlog/cmdlog.go +++ b/src/crux/cmdlog/cmdlog.go @@ -5,8 +5,10 @@ // // The log is one commands.jsonl file in the run's directory. Each command // contributes a "started" line when it is dispatched and an "ended" line -// when its exit is known; a command with no "ended" line is unfinished, -// never guessed. Readers fold the two into one api.CommandRecord per seq. +// once the runtime stops waiting on it, carrying the exit when it is +// known; a command with no "ended" line is in flight and reads as +// unfinished, never guessed. Readers fold the two into one +// api.CommandRecord per seq. // // Honest scope: a record says how the command was observed in its // capture field. The S2 runner records what it hands to the sandbox @@ -34,6 +36,10 @@ const ( EventEnded = "ended" ) +// OrphanReason is the reason on the unfinished ended line Open appends +// for a command whose started line an earlier writer never ended. +const OrphanReason = "the log was reopened with no exit recorded for this command (the runtime restarted, or its ended write failed); the exit is not knowable" + // Output policy defaults: how much of each stream a record keeps. The // full output stays with the run (runs.StdoutArtifact); the record keeps // enough of both ends to tell what happened without re-reading it. diff --git a/src/crux/cmdlog/cmdlog_test.go b/src/crux/cmdlog/cmdlog_test.go index 02edb6fd75..cb8705eaa3 100644 --- a/src/crux/cmdlog/cmdlog_test.go +++ b/src/crux/cmdlog/cmdlog_test.go @@ -120,12 +120,57 @@ func TestOpenResumesTheSeqCounter(t *testing.T) { if err != nil || seq != 4 { t.Fatalf("resumed seq = %d, %v", seq, err) } - // The earlier log's open commands are not the new log's to end. + // Ended still refuses a seq this log never started, even one Open ended. if err := second.Ended(1, End{}); !errors.Is(err, ErrUnknownSeq) { t.Fatalf("Ended(1) on resumed = %v", err) } } +// A started line no writer will ever end (its runner died) is ended +// unfinished by the next Open, so it cannot pin NextSeq for the rest of +// the run (#17410). +func TestOpenEndsACommandAnEarlierWriterLeftOpen(t *testing.T) { + dir := t.TempDir() + c := newClock() + first := openLog(t, dir, Policy{Now: c.tick}) + orphan, err := first.Started(Start{Command: []string{"make", "test"}}) + if err != nil { + t.Fatal(err) + } + seq, err := first.Started(Start{Command: []string{"echo"}}) + if err != nil { + t.Fatal(err) + } + if err := first.Ended(seq, End{ExitCode: intp(0)}); err != nil { + t.Fatal(err) + } + second := openLog(t, dir, Policy{Now: c.tick}) + page, err := Read(dir, 0, 0) + if err != nil || len(page.Commands) != 2 || page.NextSeq != seq || page.More { + t.Fatalf("page = %+v, %v", page, err) + } + rec := page.Commands[0] + if rec.Seq != orphan || rec.Status != api.CommandUnfinished || rec.EndedAt == nil || rec.ExitCode != nil || rec.Reason != OrphanReason || rec.DurationMs == nil || *rec.DurationMs != 750 { + t.Fatalf("orphan = %+v", rec) + } + if page.Commands[1].Status != api.CommandCompleted { + t.Fatalf("ended command = %+v", page.Commands[1]) + } + // The orphan is ended once: reopening again appends nothing. + path := filepath.Join(dir, FileName) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + openLog(t, dir, Policy{}) + if after, err := os.ReadFile(path); err != nil || string(after) != string(before) { + t.Fatalf("second reopen rewrote the log: %q, %v", after, err) + } + if next, err := second.Started(Start{Command: []string{"y"}}); err != nil || next != seq+1 { + t.Fatalf("resumed seq = %d, %v", next, err) + } +} + func TestReadPagesWithSinceSeqAndLimit(t *testing.T) { dir := t.TempDir() l := openLog(t, dir, Policy{}) @@ -161,6 +206,112 @@ func TestReadPagesWithSinceSeqAndLimit(t *testing.T) { } } +func TestReadFollowerSeesEndedLineOfUnfinishedCommand(t *testing.T) { + dir := t.TempDir() + l := openLog(t, dir, Policy{}) + seq, err := l.Started(Start{Command: []string{"make", "test"}}) + if err != nil { + t.Fatal(err) + } + page, err := Read(dir, 0, 0) + if err != nil || len(page.Commands) != 1 || page.Commands[0].Status != api.CommandUnfinished || page.NextSeq != 0 { + t.Fatalf("unfinished page = %+v, %v", page, err) + } + if err := l.Ended(seq, End{ExitCode: intp(0)}); err != nil { + t.Fatal(err) + } + page, err = Read(dir, page.NextSeq, 0) + if err != nil || len(page.Commands) != 1 || page.Commands[0].Status != api.CommandCompleted || page.NextSeq != seq { + t.Fatalf("terminal page = %+v, %v", page, err) + } +} + +func TestReadNextSeqStopsBeforeFirstUnfinished(t *testing.T) { + dir := t.TempDir() + l := openLog(t, dir, Policy{}) + for i := range 3 { + seq, err := l.Started(Start{Command: []string{"cmd", string(rune('a' + i))}}) + if err != nil { + t.Fatal(err) + } + if i == 1 { + continue + } + if err := l.Ended(seq, End{ExitCode: intp(0)}); err != nil { + t.Fatal(err) + } + } + page, err := Read(dir, 0, 0) + if err != nil || len(page.Commands) != 3 || page.NextSeq != 1 || page.Commands[1].Status != api.CommandUnfinished { + t.Fatalf("mixed page = %+v, %v", page, err) + } +} + +// An ended line makes a record terminal whatever its status: a command +// ended unfinished (exit never known) must not hold NextSeq back (#17410). +func TestReadNextSeqPassesAnEndedUnfinishedRecord(t *testing.T) { + dir := t.TempDir() + l := openLog(t, dir, Policy{}) + for i := range 4 { + seq, err := l.Started(Start{Command: []string{"cmd", string(rune('a' + i))}}) + if err != nil { + t.Fatal(err) + } + end := End{ExitCode: intp(0)} + if i == 1 { + end = End{Reason: "launcher error"} + } + if err := l.Ended(seq, end); err != nil { + t.Fatal(err) + } + } + page, err := Read(dir, 0, 0) + if err != nil || len(page.Commands) != 4 || page.NextSeq != 4 || page.More { + t.Fatalf("page = %+v, %v", page, err) + } + if rec := page.Commands[1]; rec.Status != api.CommandUnfinished || rec.EndedAt == nil || rec.ExitCode != nil { + t.Fatalf("ended unfinished = %+v", rec) + } + page, err = Read(dir, 0, 2) + if err != nil || len(page.Commands) != 2 || page.NextSeq != 2 || !page.More { + t.Fatalf("page 1 = %+v, %v", page, err) + } + page, err = Read(dir, page.NextSeq, 2) + if err != nil || len(page.Commands) != 2 || page.NextSeq != 4 || page.More { + t.Fatalf("page 2 = %+v, %v", page, err) + } +} + +// More is set only on a page whose cursor moved: with an in-flight command +// first on the page, the documented "page while More" loop would otherwise +// re-request the same since_seq forever (#17410). +func TestReadMoreOnlyWhenNextSeqAdvances(t *testing.T) { + dir := t.TempDir() + l := openLog(t, dir, Policy{}) + for i := range 6 { + seq, err := l.Started(Start{Command: []string{"cmd", string(rune('a' + i))}}) + if err != nil { + t.Fatal(err) + } + if i == 1 { + continue + } + if err := l.Ended(seq, End{ExitCode: intp(0)}); err != nil { + t.Fatal(err) + } + } + // Seq 2 is in flight. The first page still moves the cursor past seq 1. + page, err := Read(dir, 0, 2) + if err != nil || len(page.Commands) != 2 || page.NextSeq != 1 || !page.More { + t.Fatalf("page 1 = %+v, %v", page, err) + } + // From there seq 2 leads the page and the cursor cannot move. + page, err = Read(dir, page.NextSeq, 2) + if err != nil || len(page.Commands) != 2 || page.Commands[0].Seq != 2 || page.NextSeq != 1 || page.More { + t.Fatalf("pinned page = %+v, %v", page, err) + } +} + func TestOutputKeepsHeadAndTailPerPolicy(t *testing.T) { dir := t.TempDir() l := openLog(t, dir, Policy{HeadBytes: 4, TailBytes: 3}) diff --git a/src/crux/cmdlog/log.go b/src/crux/cmdlog/log.go index 47714eba18..20b1f48940 100644 --- a/src/crux/cmdlog/log.go +++ b/src/crux/cmdlog/log.go @@ -5,8 +5,10 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "path/filepath" + "slices" "sort" "sync" "time" @@ -39,16 +41,43 @@ type Log struct { // Open returns the Log for runDir, resuming the seq counter from a file // that already exists so a restarted runner never reuses a number. +// +// A run has one live writer at a time (a contained run dispatches one +// command; a session's steps run one at a time), so a started seq with no +// ended line on disk belongs to a writer that is gone and will never end +// it. Open appends an unfinished ended line with OrphanReason for each, +// so a crash leaves a terminal record instead of one that pins every +// follower's NextSeq behind it for the rest of the run. func Open(runDir string, pol Policy) (*Log, error) { l := &Log{path: filepath.Join(runDir, FileName), pol: pol.defaults(), next: 1, open: map[int64]time.Time{}} lines, err := readLines(l.path) if err != nil && !errors.Is(err, ErrNotFound) { return nil, err } + // orphans folds the lines the way Read does: a started line opens its + // seq, a later ended line closes it. + orphans := map[int64]time.Time{} for _, ln := range lines { if ln.Seq >= l.next { l.next = ln.Seq + 1 } + switch ln.Event { + case EventStarted: + orphans[ln.Seq] = ln.At + case EventEnded: + delete(orphans, ln.Seq) + } + } + if len(orphans) == 0 { + return l, nil + } + now := l.pol.Now() + reason := l.pol.Scrub(OrphanReason) + for _, seq := range slices.Sorted(maps.Keys(orphans)) { + ms := now.Sub(orphans[seq]).Milliseconds() + if err := l.append(line{Seq: seq, Event: EventEnded, At: now, DurationMs: &ms, Status: api.CommandUnfinished, Reason: reason}); err != nil { + return nil, err + } } return l, nil } @@ -118,7 +147,13 @@ func (l *Log) append(ln line) error { // Read folds runDir's log into records after sinceSeq (exclusive), at // most limit of them (DefaultPageSize when zero, MaxPageSize at most). -// A started line with no ended line is an unfinished record. +// A started line with no ended line is an unfinished record still in +// flight. NextSeq never advances past an in-flight record, so a follower +// re-receives it until its ended line lands (idempotent by seq); a record +// with an ended line is terminal whatever its status, an unfinished one +// whose exit was never known included. More is false on a page whose +// NextSeq could not move past sinceSeq, so a pager never re-requests the +// same page in a loop. func Read(runDir string, sinceSeq int64, limit int) (api.CommandPage, error) { lines, err := readLines(filepath.Join(runDir, FileName)) if err != nil { @@ -132,9 +167,6 @@ func Read(runDir string, sinceSeq int64, limit int) (api.CommandPage, error) { } bySeq := map[int64]*api.CommandRecord{} for _, ln := range lines { - if ln.Seq <= sinceSeq { - continue - } switch ln.Event { case EventStarted: bySeq[ln.Seq] = &api.CommandRecord{ @@ -153,6 +185,9 @@ func Read(runDir string, sinceSeq int64, limit int) (api.CommandPage, error) { } all := make([]api.CommandRecord, 0, len(bySeq)) for _, rec := range bySeq { + if rec.Seq <= sinceSeq { + continue + } all = append(all, *rec) } sort.Slice(all, func(i, j int) bool { return all[i].Seq < all[j].Seq }) @@ -162,7 +197,14 @@ func Read(runDir string, sinceSeq int64, limit int) (api.CommandPage, error) { } if n := len(page.Commands); n > 0 { page.NextSeq = page.Commands[n-1].Seq + for _, rec := range page.Commands { + if rec.EndedAt == nil { + page.NextSeq = max(rec.Seq-1, sinceSeq) + break + } + } } + page.More = page.More && page.NextSeq > sinceSeq return page, nil } diff --git a/src/crux/config/origin_labels.go b/src/crux/config/origin_labels.go index 79e342b0a1..ba04902ad6 100644 --- a/src/crux/config/origin_labels.go +++ b/src/crux/config/origin_labels.go @@ -91,7 +91,8 @@ const agentLabelPrefix = "agent/" // origin/. var KnownOriginLanes = []string{ "architect", "ci-maintainer", "dedupe", "guide", "outreach", "quality", - "reviewer", "scanner", "sec-check", "strategist", "supervisor", "tester", + "redteam", "reviewer", "scanner", "sec-check", "strategist", "supervisor", + "tester", } // GitHubLabelDescriptionMax is GitHub's cap on a label description; a diff --git a/src/crux/config/origin_labels_test.go b/src/crux/config/origin_labels_test.go index 012465c65d..3f97795a99 100644 --- a/src/crux/config/origin_labels_test.go +++ b/src/crux/config/origin_labels_test.go @@ -128,7 +128,7 @@ func TestOriginVocabularyIsConsistent(t *testing.T) { t.Errorf("source %q missing from KnownOriginSources", must) } } - for _, lane := range []string{"reviewer", "scanner", "quality", "ci-maintainer", "sec-check", "architect", "guide", "strategist", "outreach", "dedupe", "supervisor", "tester"} { + for _, lane := range []string{"reviewer", "scanner", "quality", "ci-maintainer", "sec-check", "architect", "guide", "strategist", "outreach", "dedupe", "redteam", "supervisor", "tester"} { if seen[lane] { t.Errorf("agent lane %q must not be an origin source", lane) } diff --git a/src/crux/config/watchdog.go b/src/crux/config/watchdog.go index 5307e622a1..4ec92f45a3 100644 --- a/src/crux/config/watchdog.go +++ b/src/crux/config/watchdog.go @@ -42,6 +42,12 @@ type WatchdogLivenessConfig struct { // window exists because a launching CLI legitimately passes through both // states. "" = 5m. ShellPromptAfter string `yaml:"shell_prompt_after,omitempty"` + // LoginStreak is how many consecutive watchdog polls must see login + // chrome before the pane is classified auth-required and an operator is + // paged; fewer sightings report Unknown. A relaunched CLI flashes login + // chrome while re-validating its token, so one sighting is not a logout. + // 0 = 3; 1 disables the guard. + LoginStreak int `yaml:"login_streak,omitempty"` } // WatchdogRestartConfig holds the CrashLoopBackOff-analog knobs. diff --git a/src/crux/runs/cmdlog_test.go b/src/crux/runs/cmdlog_test.go index afb4c5f936..ae68006151 100644 --- a/src/crux/runs/cmdlog_test.go +++ b/src/crux/runs/cmdlog_test.go @@ -87,6 +87,10 @@ func TestLogStatusFollowsTheOutcome(t *testing.T) { if rec.Status != tc.want || (tc.exit == nil) != (rec.ExitCode == nil) || (tc.exit != nil && *tc.exit != *rec.ExitCode) || rec.EndedAt == nil { t.Fatalf("record = %+v want %s exit=%v", rec, tc.want, tc.exit) } + // Every outcome is terminal, unfinished included: a follower moves on. + if page.NextSeq != rec.Seq || page.More { + t.Fatalf("page = %+v", page) + } }) } } @@ -106,6 +110,34 @@ func TestCommandsWithoutALogIsAnEmptyPage(t *testing.T) { } } +// A command the previous process dispatched and never ended is ended +// unfinished at restart, so a follower's next_seq is not pinned on it +// forever (#17410). +func TestReconcileEndsTheCommandARunLeftInFlight(t *testing.T) { + f := withCmdLog(newFixture(t, blocking())) + rec, _, err := f.svc.Store.Create(runstate.Record{Owner: "operator"}) + if err != nil { + t.Fatal(err) + } + log, err := f.svc.CmdLog(f.svc.Store.Path(rec.ID)) + if err != nil { + t.Fatal(err) + } + if _, err := log.Started(cmdlog.Start{Command: []string{"make"}}); err != nil { + t.Fatal(err) + } + if _, err := f.svc.Reconcile(); err != nil { + t.Fatal(err) + } + page, err := f.svc.Commands(rec.ID, 0, 0) + if err != nil || len(page.Commands) != 1 || page.NextSeq != 1 || page.More { + t.Fatalf("Commands = %+v, %v", page, err) + } + if got := page.Commands[0]; got.Status != api.CommandUnfinished || got.EndedAt == nil || got.ExitCode != nil || got.Reason != cmdlog.OrphanReason { + t.Fatalf("record = %+v", got) + } +} + func TestAnOpenerFailureDoesNotStopTheRun(t *testing.T) { f := newFixture(t, newFakeLauncher(func(context.Context, sandbox.LaunchSpec) (sandbox.Result, error) { return sandbox.Result{Stdout: "ran"}, nil diff --git a/src/crux/runs/service.go b/src/crux/runs/service.go index bb35bab36d..e4ee93a71b 100644 --- a/src/crux/runs/service.go +++ b/src/crux/runs/service.go @@ -176,7 +176,8 @@ func (s *Service) Configured() bool { return s.Backend != nil } // Reconcile marks every run left accepted, running or waiting by a previous // process unfinished, and with it any step (S6) that run still records as -// running. Call it once at serve start, before accepting requests. +// running and any command (S4) its log still records as in flight. Call it +// once at serve start, before accepting requests. func (s *Service) Reconcile() ([]runstate.Record, error) { recs, err := s.Store.Reconcile(ReconcileReason) // A run the previous process left in flight ended unobserved; its done @@ -185,6 +186,13 @@ func (s *Service) Reconcile() ([]runstate.Record, error) { if _, serr := (agentstep.Store{RunDir: s.Store.Path(rec.ID)}).Reconcile(ReconcileReason, s.Store.Now()); serr != nil && err == nil { err = serr } + // Reopening its command log ends the command it left in flight + // (cmdlog.Open), so a follower's next_seq is not pinned behind it + // forever. Like every other cmdlog failure, an unopenable log is + // skipped rather than holding up the restart. + if s.CmdLog != nil { + _, _ = s.CmdLog(s.Store.Path(rec.ID)) + } s.signalDone(rec.ID, api.SignalDoneData{Status: rec.Status}, rec.Reason) } return recs, err @@ -458,10 +466,22 @@ func (s *Service) validateWorkspace(caller Caller, req api.ContainedRunRequest, if !pathUnder(path, s.Config.WorkspaceRoots) { return &ForbiddenError{fmt.Sprintf("workspace_path %q is not under this server's workspace_roots", path)} } - if st, err := os.Stat(path); err != nil || !st.IsDir() { + // The lexical check above cannot see symlinks: /x pointing at / + // passes it, and a previous run can plant such a link in its rw + // workspace. Resolve the path, check the resolved form against the + // resolved roots, and mount the resolved path so the backend never + // follows a link the check did not see. + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + return &RequestError{fmt.Sprintf("workspace_path %q is not a directory", path)} + } + if !pathUnder(resolved, resolvedRoots(s.Config.WorkspaceRoots)) { + return &ForbiddenError{fmt.Sprintf("workspace_path %q resolves outside this server's workspace_roots", path)} + } + if st, err := os.Stat(resolved); err != nil || !st.IsDir() { return &RequestError{fmt.Sprintf("workspace_path %q is not a directory", path)} } - p.workspace = path + p.workspace = resolved return nil } @@ -511,6 +531,26 @@ func pathUnder(path string, roots []string) bool { return false } +// resolvedRoots returns roots with symlinks resolved, so a root that is +// itself reached through a link (a symlinked /tmp, a bind-mount alias) +// still contains the resolved paths beneath it. A root that cannot be +// resolved (it does not exist) is kept as written: nothing resolves +// under a missing directory, so it admits nothing it should not. +func resolvedRoots(roots []string) []string { + out := make([]string, 0, len(roots)) + for _, root := range roots { + root = filepath.Clean(strings.TrimSpace(root)) + if root == "" || root == "." { + continue + } + if r, err := filepath.EvalSymlinks(root); err == nil { + root = r + } + out = append(out, root) + } + return out +} + // execute runs one accepted run to a terminal status. Every exit path // writes the record and then the run's done signal; nothing is left // accepted or running by this process. diff --git a/src/crux/runs/service_test.go b/src/crux/runs/service_test.go index 73cdb96750..bac0c9cc27 100644 --- a/src/crux/runs/service_test.go +++ b/src/crux/runs/service_test.go @@ -70,7 +70,13 @@ func newFixture(t *testing.T, launcher *fakeLauncher) *fixture { if err != nil { t.Fatal(err) } - root := filepath.Join(t.TempDir(), "ws") + // Resolved so a symlinked TMPDIR does not make the mounted (resolved) + // workspace differ from f.workspace(). + tmp, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + root := filepath.Join(tmp, "ws") if err := os.MkdirAll(filepath.Join(root, "proj"), 0o755); err != nil { t.Fatal(err) } @@ -435,6 +441,12 @@ func (p provisionFunc) Provision(ctx context.Context, dir string, wt api.Contain func TestValidationErrors(t *testing.T) { f := newFixture(t, blocking()) ws := f.workspace() + // A link under a root naming a directory outside it: the lexical + // prefix check admits it, the resolved check must not. + escape := filepath.Join(f.root, "escape") + if err := os.Symlink(filepath.Dir(f.root), escape); err != nil { + t.Fatal(err) + } wt := &api.ContainedRunWorktree{Repo: "https://github.com/hivecommons/hive", Commit: testSHA} cases := []struct { name string @@ -472,6 +484,7 @@ func TestValidationErrors(t *testing.T) { {"workspace outside roots", api.ContainedRunRequest{Command: []string{"x"}, WorkspacePath: filepath.Dir(f.root)}, &ForbiddenError{}, "workspace_roots"}, {"workspace sibling prefix", api.ContainedRunRequest{Command: []string{"x"}, WorkspacePath: f.root + "2"}, &ForbiddenError{}, "workspace_roots"}, {"workspace missing", api.ContainedRunRequest{Command: []string{"x"}, WorkspacePath: filepath.Join(ws, "nope")}, &RequestError{}, "not a directory"}, + {"workspace symlink escape", api.ContainedRunRequest{Command: []string{"x"}, WorkspacePath: escape}, &ForbiddenError{}, "resolves outside"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -501,6 +514,32 @@ func TestValidationErrors(t *testing.T) { } } +// A root reached through a link, and a link that stays inside the root, +// are still admitted; the run mounts the resolved directory, never the +// link the check followed. +func TestWorkspacePathSymlinksResolveInsideRoots(t *testing.T) { + f := newFixture(t, newFakeLauncher(func(context.Context, sandbox.LaunchSpec) (sandbox.Result, error) { + return sandbox.Result{}, nil + })) + alias := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(f.root, alias); err != nil { + t.Fatal(err) + } + if err := os.Symlink(f.workspace(), filepath.Join(f.root, "inner")); err != nil { + t.Fatal(err) + } + f.svc.Config.WorkspaceRoots = []string{alias} + for _, path := range []string{filepath.Join(alias, "proj"), filepath.Join(alias, "inner")} { + run := f.start(api.ContainedRunRequest{WorkspacePath: path, Command: []string{"x"}}) + if spec := f.spec(); spec.Workspace != f.workspace() { + t.Fatalf("%s mounted %q, want resolved %q", path, spec.Workspace, f.workspace()) + } + if done := f.wait(run.ID); done.Workdir != f.workspace() { + t.Fatalf("%s recorded workdir %q", path, done.Workdir) + } + } +} + func TestNotConfiguredServesRecordsButRefusesCreates(t *testing.T) { store, err := runstate.Open(t.TempDir()) if err != nil { diff --git a/src/crux/serve/families_test.go b/src/crux/serve/families_test.go index b9c4d77172..b47d8cd696 100644 --- a/src/crux/serve/families_test.go +++ b/src/crux/serve/families_test.go @@ -884,6 +884,7 @@ func TestServeWithoutHostOrBackground(t *testing.T) { if len(rt.Background()) != 0 { t.Fatal("background loops started while disabled") } + t.Setenv("PATH", fakeTmuxDir(t)) var h api.Health newFamServer(t).expect(http.MethodGet, api.PathHealth, nil, http.StatusOK, &h) if len(h.Background) != 0 { diff --git a/src/crux/serve/health_test.go b/src/crux/serve/health_test.go new file mode 100644 index 0000000000..7aa3a7d71d --- /dev/null +++ b/src/crux/serve/health_test.go @@ -0,0 +1,47 @@ +package serve + +import ( + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/crux/api" +) + +// fakeTmuxDir returns a directory holding an executable named tmux, for a +// PATH that resolves it without needing a real install. +func fakeTmuxDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "tmux"), []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + return dir +} + +func TestHealthTmuxMissingIs503(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + var h api.Health + newFamServer(t).expect(http.MethodGet, api.PathHealth, nil, http.StatusServiceUnavailable, &h) + if h.Tmux != "" || h.Version != api.Version { + t.Fatalf("health: %+v", h) + } + // The body is also an api.Error, so api.Client callers see the cause. + if h.Code != api.CodeUnavailable || !strings.Contains(h.Error, "tmux not found on PATH") { + t.Fatalf("health error: %+v", h) + } +} + +func TestHealthTmuxPresentIs200(t *testing.T) { + if _, err := exec.LookPath("tmux"); err != nil { + t.Skip("tmux not installed") + } + var h api.Health + newFamServer(t).expect(http.MethodGet, api.PathHealth, nil, http.StatusOK, &h) + if h.Tmux == "" { + t.Fatalf("health: %+v", h) + } +} diff --git a/src/crux/serve/metrics.go b/src/crux/serve/metrics.go index ec58dd36a0..4ea8b016c7 100644 --- a/src/crux/serve/metrics.go +++ b/src/crux/serve/metrics.go @@ -8,6 +8,7 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/trace" ) @@ -16,9 +17,10 @@ import ( // they sit on the global providers, which are OTel's delegating no-ops until a // host registers an SDK provider, so recording costs nothing by default. // -// Attributes are bounded: the HTTP method, the mux route pattern (for example -// "GET /v1/agents/{name}", never the concrete path or an agent name; routeUnmatched -// when no route matched) and the status class. Never a path, token or body. +// Attributes are bounded: the HTTP method (standard set, else _OTHER), the mux +// route pattern (for example "GET /v1/agents/{name}", never the concrete path or +// an agent name; routeUnmatched when no route matched) and the status class. +// Never a path, token or body. const ( instrumentationName = "github.com/hivecommons/hive/crux/serve" @@ -27,9 +29,13 @@ const ( routeUnmatched = "unmatched" + statusClass1xx = "1xx" statusClass2xx = "2xx" + statusClass3xx = "3xx" statusClass4xx = "4xx" statusClass5xx = "5xx" + + methodOther = "_OTHER" ) var ( @@ -95,8 +101,25 @@ func statusClass(status int) string { return statusClass5xx case status >= 400: return statusClass4xx - default: + case status >= 300: + return statusClass3xx + case status >= 200: return statusClass2xx + default: + return statusClass1xx + } +} + +// boundedMethod maps a client-supplied method onto the standard set, and +// everything else onto _OTHER, as OTel HTTP semconv does for +// http.request.method. +func boundedMethod(method string) string { + switch method { + case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, + http.MethodDelete, http.MethodOptions, http.MethodConnect, http.MethodTrace: + return method + default: + return methodOther } } @@ -113,25 +136,35 @@ func instrument(next http.Handler) http.Handler { } // The mux records the matched pattern on the request it dispatches. req := r.WithContext(ctx) + // A handler panic unwinds through here (net/http recovers it further + // up), so record in a defer and count it as a 5xx; the panic then + // continues untouched. + returned := false + defer func() { + status := rec.status + if status == 0 { + status = http.StatusOK + } + if !returned { + status = http.StatusInternalServerError + span.SetStatus(codes.Error, "handler panic") + } + route := req.Pattern + if route == "" { + route = routeUnmatched + } + attrs := []attribute.KeyValue{ + attrMethod.String(boundedMethod(r.Method)), + attrRoute.String(route), + attrStatusClass.String(statusClass(status)), + } + span.SetName(route) + span.SetAttributes(attrs...) + span.End() + globalRequestMetrics().record(ctx, time.Since(start), attrs) + }() next.ServeHTTP(out, req) - - status := rec.status - if status == 0 { - status = http.StatusOK - } - route := req.Pattern - if route == "" { - route = routeUnmatched - } - attrs := []attribute.KeyValue{ - attrMethod.String(r.Method), - attrRoute.String(route), - attrStatusClass.String(statusClass(status)), - } - span.SetName(route) - span.SetAttributes(attrs...) - span.End() - globalRequestMetrics().record(ctx, time.Since(start), attrs) + returned = true }) } diff --git a/src/crux/serve/metrics_test.go b/src/crux/serve/metrics_test.go index bed6214a24..823724d53a 100644 --- a/src/crux/serve/metrics_test.go +++ b/src/crux/serve/metrics_test.go @@ -8,6 +8,7 @@ import ( "testing" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/codes" sdkmetric "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" sdktrace "go.opentelemetry.io/otel/sdk/trace" @@ -100,10 +101,48 @@ func TestRequestMetricsKeyedByRoutePattern(t *testing.T) { } } +func TestRequestMetricsBoundTheMethod(t *testing.T) { + for _, tc := range []struct{ method, want string }{ + {http.MethodGet, http.MethodGet}, + {http.MethodPatch, http.MethodPatch}, + {"BREW", methodOther}, + {"get", methodOther}, + } { + t.Run(tc.method, func(t *testing.T) { + reader := useTestMetrics(t) + h := instrument(http.NotFoundHandler()) + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, "/", nil)) + + var rm metricdata.ResourceMetrics + if err := reader.Collect(context.Background(), &rm); err != nil { + t.Fatalf("Collect: %v", err) + } + var methods []string + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + if data, ok := m.Data.(metricdata.Sum[int64]); ok { + for _, dp := range data.DataPoints { + v, _ := dp.Attributes.Value(attrMethod) + methods = append(methods, v.AsString()) + } + } + } + } + if len(methods) != 1 || methods[0] != tc.want { + t.Errorf("methods = %v, want [%s]", methods, tc.want) + } + }) + } +} + func TestStatusClassBoundaries(t *testing.T) { for status, want := range map[int]string{ + http.StatusContinue: statusClass1xx, + 199: statusClass1xx, http.StatusOK: statusClass2xx, - 399: statusClass2xx, + 299: statusClass2xx, + http.StatusFound: statusClass3xx, + 399: statusClass3xx, http.StatusBadRequest: statusClass4xx, 499: statusClass4xx, http.StatusInternalServerError: statusClass5xx, @@ -236,3 +275,62 @@ func TestRecordedStatusIsTheOneTheClientSaw(t *testing.T) { }) } } + +func TestRedirectIsCountedAs3xx(t *testing.T) { + reader := useTestMetrics(t) + instrument(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/elsewhere", http.StatusFound) + })).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + + if got := collectStatusClasses(t, reader); len(got) != 1 || got[0] != statusClass3xx { + t.Errorf("status classes = %v, want [%s]", got, statusClass3xx) + } +} + +// net/http recovers a handler panic above instrument, so the span and the +// sample must be recorded while the panic unwinds, and the panic must still +// propagate. +func TestPanickingHandlerIsRecordedAs5xx(t *testing.T) { + exp := useTestTracer(t) + reader := useTestMetrics(t) + h := instrument(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic("boom") })) + + var recovered any + func() { + defer func() { recovered = recover() }() + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + }() + if recovered != "boom" { + t.Fatalf("recovered = %v, want the handler's panic re-raised", recovered) + } + if got := collectStatusClasses(t, reader); len(got) != 1 || got[0] != statusClass5xx { + t.Errorf("status classes = %v, want [%s]", got, statusClass5xx) + } + spans := exp.GetSpans() + if len(spans) != 1 { + t.Fatalf("spans = %d, want the panicking request's span ended", len(spans)) + } + if spans[0].Status.Code != codes.Error { + t.Errorf("span status = %v, want error", spans[0].Status.Code) + } +} + +func collectStatusClasses(t *testing.T, reader *sdkmetric.ManualReader) []string { + t.Helper() + var rm metricdata.ResourceMetrics + if err := reader.Collect(context.Background(), &rm); err != nil { + t.Fatalf("Collect: %v", err) + } + var classes []string + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + if sum, ok := m.Data.(metricdata.Sum[int64]); ok { + for _, dp := range sum.DataPoints { + class, _ := dp.Attributes.Value(attrStatusClass) + classes = append(classes, class.AsString()) + } + } + } + } + return classes +} diff --git a/src/crux/serve/serve.go b/src/crux/serve/serve.go index 1f4e18f1b3..bb0f4e8e83 100644 --- a/src/crux/serve/serve.go +++ b/src/crux/serve/serve.go @@ -34,6 +34,7 @@ import ( "github.com/hivecommons/hive/crux/internal/privatedir" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/agent/tmux" "github.com/hivecommons/hive/crux/api" "github.com/hivecommons/hive/crux/checkout" "github.com/hivecommons/hive/crux/config" @@ -388,7 +389,16 @@ func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) { hc := s.HiveCallback() h.HiveCallback = &hc } - s.writeJSON(w, http.StatusOK, h) + status := http.StatusOK + if path, err := tmux.LookPath(); err != nil { + // The body doubles as an api.Error so api.Client reports the cause. + status = http.StatusServiceUnavailable + h.Error = fmt.Sprintf("tmux not found on PATH: %v", err) + h.Code = api.CodeUnavailable + } else { + h.Tmux = path + } + s.writeJSON(w, status, h) } func (s *Server) handleList(w http.ResponseWriter, _ *http.Request) { diff --git a/src/crux/watchdog/classify.go b/src/crux/watchdog/classify.go index 565a104aff..bb8c8fb81e 100644 --- a/src/crux/watchdog/classify.go +++ b/src/crux/watchdog/classify.go @@ -1,6 +1,7 @@ package watchdog import ( + "fmt" "strings" "time" ) @@ -67,6 +68,13 @@ type Observation struct { // agent spawns a second concurrent CLI, the race cliBootGraceSeconds was // added for on the manager side. StartedAt time.Time + // LastLaunchAt is when the CLI process was most recently (re)launched + // into the pane; zero when the manager has not recorded one. StartedAt + // dates the agent, not the process: a kick restart, memory-drain recycle + // or watchdog restart hours into an agent's life spawns a fresh CLI that + // repeats the whole startup handshake (login chrome included), so boot + // grace is measured from the later of the two. + LastLaunchAt time.Time // AuthAvailable/AuthKnown carry the manager's owner-aware per-agent // credential-file verdict (AgentAuthState, #4619/#4641): AuthKnown=false // means the probe could not determine an answer and the reconciler must @@ -208,9 +216,12 @@ func Classify(obs Observation, now time.Time, s Settings) Classification { // Boot grace outranks every dead verdict. A launching agent legitimately // has no tmux session, no pane, and no CLI marker for the first seconds of // its life; without this, the watchdog would restart it underneath itself - // and spawn a second concurrent CLI. An agent with no StartedAt cannot be - // dated, so it gets no grace rather than an unbounded one. - booting := !obs.StartedAt.IsZero() && now.Sub(obs.StartedAt) < s.BootGrace + // and spawn a second concurrent CLI. An agent with no launch timestamp + // cannot be dated, so it gets no grace rather than an unbounded one. The + // grace is dated from the most recent CLI launch, not the agent's first: + // a relaunched CLI boots exactly like a new one (#17320). + launchedAt := obs.lastLaunch() + booting := !launchedAt.IsZero() && now.Sub(launchedAt) < s.BootGrace if !obs.SessionExists { if booting { @@ -234,11 +245,16 @@ func Classify(obs Observation, now time.Time, s Settings) Classification { // branch. Observed on a hosted spoke: rolling the pod paged quality, // scanner and ci-maintainer 3 minutes in, one event each, never // repeated -- all three were authenticated and working the whole time. + // Observed again 22h into the same agents' lives when their CLIs were + // relaunched mid-life (#17320): the grace was dated from the agent's + // first start, so the relaunch flash got none. Hence lastLaunch above, + // and the reconciler's ApplyLoginStreak on top for the relaunches the + // manager cannot date (the CLI re-executing itself, for one). // // Unknown rather than Ready: a login screen is not health, and this // says only that it is too early to conclude anything. An agent that // genuinely needs a human still shows the same chrome once grace - // elapses and pages on the very next tick. + // elapses and pages once the streak is met. if booting { return Classification{ClassUnknown, "pane shows login chrome inside boot grace"} } @@ -290,3 +306,26 @@ func Classify(obs Observation, now time.Time, s Settings) Classification { } return Classification{ClassUnknown, "pane matched no known signature"} } + +// lastLaunch is the later of the agent's start and its most recent CLI +// relaunch — the instant boot grace is measured from. +func (o Observation) lastLaunch() time.Time { + if o.LastLaunchAt.After(o.StartedAt) { + return o.LastLaunchAt + } + return o.StartedAt +} + +// ApplyLoginStreak is the watchdog's counterpart to the pane poller's +// loginStreak guard: an auth-required verdict only stands once login chrome +// has been seen on `required` consecutive polls, `streak` being the count +// including this one. Below that it is downgraded to unknown — the honest +// verdict for a CLI that may simply be mid-handshake after a relaunch the +// manager could not date (#17320). Any other class passes through untouched; +// a required streak below one disables the guard. +func ApplyLoginStreak(cls Classification, streak, required int) Classification { + if cls.Class != ClassAuthRequired || required <= 1 || streak >= required { + return cls + } + return Classification{ClassUnknown, fmt.Sprintf("login chrome seen %d/%d polls", streak, required)} +} diff --git a/src/crux/watchdog/classify_login_grace_test.go b/src/crux/watchdog/classify_login_grace_test.go index 5174f2f1e8..dcd5dc2360 100644 --- a/src/crux/watchdog/classify_login_grace_test.go +++ b/src/crux/watchdog/classify_login_grace_test.go @@ -114,3 +114,89 @@ func TestClassifyLoginPromptObservationInsideBootGrace(t *testing.T) { t.Errorf("past grace: Classify() = %v (%q), want %v", got.Class, got.Reason, ClassAuthRequired) } } + +// TestClassifyLoginChromeAfterMidLifeRelaunch pins #17320: 22h into their +// lives, three copilot agents had their CLIs relaunched and each flashed login +// chrome for ~0.5s while re-validating the token. StartedAt dated the agent, +// not the process, so the relaunch got no grace and one sighting paged. +func TestClassifyLoginChromeAfterMidLifeRelaunch(t *testing.T) { + s := classifySettings() + base := Observation{ + Backend: "copilot", + SessionExists: true, + Pane: "Please run /login to authenticate", + ShowsLoginPrompt: true, + StartedAt: fresh(22 * time.Hour), + LastChange: fresh(time.Second), + } + + cases := []struct { + name string + lastLaunchAt time.Time + want PaneClass + }{ + {"relaunch seconds ago is inside grace", fresh(3 * time.Second), ClassUnknown}, + {"relaunch past grace pages", fresh(s.BootGrace + time.Second), ClassAuthRequired}, + {"no relaunch recorded falls back to StartedAt", time.Time{}, ClassAuthRequired}, + // A stale LastLaunchAt (older than StartedAt) must never shrink the + // grace a fresh StartedAt already grants. + {"older relaunch than StartedAt does not win", fresh(48 * time.Hour), ClassAuthRequired}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + obs := base + obs.LastLaunchAt = tc.lastLaunchAt + if got := Classify(obs, testClock, s); got.Class != tc.want { + t.Errorf("Classify() = %v (%q), want %v", got.Class, got.Reason, tc.want) + } + }) + } + + t.Run("relaunch grace also covers a missing session", func(t *testing.T) { + obs := base + obs.SessionExists = false + obs.LastLaunchAt = fresh(3 * time.Second) + if got := Classify(obs, testClock, s); got.Class != ClassUnknown { + t.Errorf("Classify() = %v (%q), want %v", got.Class, got.Reason, ClassUnknown) + } + }) + t.Run("fresh StartedAt still grants grace when LastLaunchAt is older", func(t *testing.T) { + obs := base + obs.StartedAt = fresh(3 * time.Second) + obs.LastLaunchAt = fresh(time.Hour) + if got := Classify(obs, testClock, s); got.Class != ClassUnknown { + t.Errorf("Classify() = %v (%q), want %v", got.Class, got.Reason, ClassUnknown) + } + }) +} + +// TestApplyLoginStreak is the classifier-side half of the relaunch guard: a +// relaunch the manager cannot date still flashes login chrome, so the verdict +// must survive several consecutive polls before it pages. +func TestApplyLoginStreak(t *testing.T) { + auth := Classification{ClassAuthRequired, "pane shows a login/credential screen"} + cases := []struct { + name string + in Classification + streak int + required int + want PaneClass + wantReason string + }{ + {"first sighting is unknown", auth, 1, 3, ClassUnknown, "login chrome seen 1/3 polls"}, + {"second sighting is unknown", auth, 2, 3, ClassUnknown, "login chrome seen 2/3 polls"}, + {"streak at threshold pages", auth, 3, 3, ClassAuthRequired, auth.Reason}, + {"streak past threshold keeps paging", auth, 7, 3, ClassAuthRequired, auth.Reason}, + {"required of one disables the guard", auth, 1, 1, ClassAuthRequired, auth.Reason}, + {"required of zero disables the guard", auth, 1, 0, ClassAuthRequired, auth.Reason}, + {"non-auth verdicts pass through", Classification{ClassReady, "CLI ready signature present"}, 0, 3, ClassReady, "CLI ready signature present"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ApplyLoginStreak(tc.in, tc.streak, tc.required) + if got.Class != tc.want || got.Reason != tc.wantReason { + t.Errorf("ApplyLoginStreak(%v, %d, %d) = %v (%q), want %v (%q)", tc.in.Class, tc.streak, tc.required, got.Class, got.Reason, tc.want, tc.wantReason) + } + }) + } +} diff --git a/src/crux/watchdog/login_streak.go b/src/crux/watchdog/login_streak.go new file mode 100644 index 0000000000..20e68509bb --- /dev/null +++ b/src/crux/watchdog/login_streak.go @@ -0,0 +1,20 @@ +package watchdog + +import "time" + +// classifyLocked runs the pane state machine for one agent and layers the +// reconciler's per-agent login streak on top: auth-required only stands once +// the pane has shown login chrome on Settings.LoginStreak consecutive polls. +// A relaunched CLI flashes login chrome for a fraction of a second while it +// re-validates its token, and the manager cannot date every relaunch (the CLI +// re-executing itself, for one), so one sighting must not page an operator +// (#17320). Caller holds r.mu. +func (r *Reconciler) classifyLocked(rec *agentRecord, obs Observation, now time.Time) Classification { + cls := Classify(obs, now, r.settings) + if cls.Class == ClassAuthRequired { + rec.loginStreak++ + } else { + rec.loginStreak = 0 + } + return ApplyLoginStreak(cls, rec.loginStreak, r.settings.LoginStreak) +} diff --git a/src/crux/watchdog/login_streak_test.go b/src/crux/watchdog/login_streak_test.go new file mode 100644 index 0000000000..219dbcac22 --- /dev/null +++ b/src/crux/watchdog/login_streak_test.go @@ -0,0 +1,87 @@ +package watchdog + +import ( + "context" + "strings" + "testing" +) + +// TestAuthLoginStreak pins the reconciler half of #17320: with the default +// LoginStreak, login chrome must persist across consecutive polls before +// Authenticated flips False and an operator is paged. A relaunched CLI that +// flashes login chrome on one poll and is back at its prompt on the next never +// pages; a pane genuinely stuck at login still does once the streak is met. +func TestAuthLoginStreak(t *testing.T) { + loginObs := Observation{ + Backend: "copilot", SessionExists: true, + Pane: loginPane, ShowsLoginPrompt: true, + StartedAt: launchedLongAgo, + } + readyObs := Observation{ + Backend: "copilot", SessionExists: true, + Pane: "● reviewing PR #12", HasCLIMarker: true, + StartedAt: launchedLongAgo, + } + settings := fastSettings() + settings.LoginStreak = DefaultLoginStreak + + t.Run("one-poll relaunch flash never pages", func(t *testing.T) { + fleet := newFakeFleet("a1") + alerter := newFakeAlerter() + r := newTestReconciler(t, settings, fleet, alerter, newFakeClock()) + + fleet.setObs("a1", loginObs) + r.Tick(context.Background()) + auth, _ := FindCondition(r.Conditions("a1"), ConditionAuthenticated) + if auth.Reason == "PaneShowsLogin" { + t.Fatalf("Authenticated = %+v after one sighting, want not PaneShowsLogin", auth) + } + if alerter.has(authAlertID("a1")) { + t.Fatal("one login sighting paged the operator") + } + if got := r.Conditions("a1"); !hasReadyReasonContaining(got, "login chrome seen 1/3 polls") { + t.Fatalf("Ready condition should carry the streak reason, got %+v", got) + } + + fleet.setObs("a1", readyObs) + r.Tick(context.Background()) + fleet.setObs("a1", loginObs) + r.Tick(context.Background()) + fleet.setObs("a1", loginObs) + r.Tick(context.Background()) + // Two sightings after a reset are still below the threshold. + if alerter.has(authAlertID("a1")) { + t.Fatal("streak must reset when the pane leaves login chrome") + } + }) + + t.Run("login chrome on every poll pages at the threshold", func(t *testing.T) { + fleet := newFakeFleet("a1") + alerter := newFakeAlerter() + r := newTestReconciler(t, settings, fleet, alerter, newFakeClock()) + fleet.setObs("a1", loginObs) + + for i := 1; i < DefaultLoginStreak; i++ { + r.Tick(context.Background()) + if alerter.has(authAlertID("a1")) { + t.Fatalf("paged after %d/%d sightings", i, DefaultLoginStreak) + } + } + r.Tick(context.Background()) + auth, _ := FindCondition(r.Conditions("a1"), ConditionAuthenticated) + if auth.Status != ConditionFalse || auth.Reason != "PaneShowsLogin" { + t.Fatalf("Authenticated = %+v at the streak threshold, want False/PaneShowsLogin", auth) + } + if !alerter.has(authAlertID("a1")) { + t.Fatal("a pane stuck at login must still page once the streak is met") + } + if fleet.restartCount() != 0 { + t.Fatal("auth-required must never restart") + } + }) +} + +func hasReadyReasonContaining(conds []Condition, want string) bool { + ready, ok := FindCondition(conds, ConditionReady) + return ok && strings.Contains(ready.Message, want) +} diff --git a/src/crux/watchdog/reconciler.go b/src/crux/watchdog/reconciler.go index 22ac20caf5..34fa1a4df0 100644 --- a/src/crux/watchdog/reconciler.go +++ b/src/crux/watchdog/reconciler.go @@ -286,9 +286,9 @@ type agentRecord struct { // alert fire once, not every tick. CrashLooping bool // LastClass is the previous liveness verdict, for transition logging. - LastClass PaneClass - // restartInFlight is true while a restart goroutine is running; the - // reconciler never stacks a second restart on a wedged one. + LastClass PaneClass + loginStreak int // consecutive polls showing login chrome; see classifyLocked + // restartInFlight: a restart goroutine is running; never stack another on a wedged one. restartInFlight bool // restartStartedAt dates the in-flight restart so a wedge past the hard // timeout is alerted on (the control-plane guard for failure mode 4). @@ -564,11 +564,11 @@ func (r *Reconciler) reconcileAgent(ctx context.Context, name string, now time.T r.logger.Warn("watchdog: agent unobservable", "agent", name, "error", err) return } - cls := Classify(obs, now, r.snapshotSettings()) paused := r.fleet.IsPaused(name) r.mu.Lock() rec := r.recordLocked(name) + cls := r.classifyLocked(rec, obs, now) if cls.Class != rec.LastClass { r.logger.Info("watchdog: liveness transition", "agent", name, "from", string(rec.LastClass), "to", string(cls.Class), "reason", cls.Reason) diff --git a/src/crux/watchdog/reconciler_test.go b/src/crux/watchdog/reconciler_test.go index 2681c920f4..d09228daae 100644 --- a/src/crux/watchdog/reconciler_test.go +++ b/src/crux/watchdog/reconciler_test.go @@ -308,6 +308,9 @@ func fastSettings() Settings { s.Mode = ModeHeal s.ProbeInterval = 0 // every Tick sweeps; interval gating has its own test s.RestartTimeout = 50 * time.Millisecond + // One sighting pages: the auth tests here assert the paging branch itself; + // the multi-poll streak guard has its own test (TestAuthLoginStreak). + s.LoginStreak = 1 return s } diff --git a/src/crux/watchdog/settings.go b/src/crux/watchdog/settings.go index df9f6a3cca..1202e3a61c 100644 --- a/src/crux/watchdog/settings.go +++ b/src/crux/watchdog/settings.go @@ -39,6 +39,12 @@ const ( // Kept numerically equal to that constant rather than importing it, // because pkg/agent imports pkg/watchdog and the reverse would cycle. DefaultBootGrace = 60 * time.Second + // DefaultLoginStreak is how many consecutive watchdog polls must see + // login chrome before the pane is classified auth-required and an + // operator is paged. Mirrors the pane poller's loginStreakRestartMin: a + // relaunched CLI flashes login chrome for well under a second while it + // re-validates its token, and a single sighting is not a logout (#17320). + DefaultLoginStreak = 3 ) // defaultBackoff is the RFC restart ladder; the last entry is the cap. @@ -130,6 +136,7 @@ type Settings struct { StuckOverlayAfter time.Duration ShellPromptAfter time.Duration BootGrace time.Duration + LoginStreak int Backoff []time.Duration CrashLoopAfter int HealthyReset time.Duration @@ -154,6 +161,7 @@ func DefaultSettings() Settings { StuckOverlayAfter: DefaultStuckOverlayAfter, ShellPromptAfter: DefaultShellPromptAfter, BootGrace: DefaultBootGrace, + LoginStreak: DefaultLoginStreak, Backoff: defaultBackoff(), CrashLoopAfter: DefaultCrashLoopAfter, HealthyReset: DefaultHealthyReset, @@ -207,6 +215,11 @@ func SettingsFrom(cfg config.WatchdogConfig) (Settings, []error) { s.StuckOverlayAfter = resolveDuration("watchdog.liveness.stuck_overlay_after", cfg.Liveness.StuckOverlayAfter, DefaultStuckOverlayAfter, &errs) s.ShellPromptAfter = resolveDuration("watchdog.liveness.shell_prompt_after", cfg.Liveness.ShellPromptAfter, DefaultShellPromptAfter, &errs) + if cfg.Liveness.LoginStreak < 0 { + errs = append(errs, fmt.Errorf("watchdog.liveness.login_streak: negative value %d, using default %d", cfg.Liveness.LoginStreak, DefaultLoginStreak)) + } else if cfg.Liveness.LoginStreak > 0 { + s.LoginStreak = cfg.Liveness.LoginStreak + } s.HealthyReset = resolveDuration("watchdog.restart.healthy_reset", cfg.Restart.HealthyReset, DefaultHealthyReset, &errs) s.NoProductionFor = resolveDuration("watchdog.readiness.no_production_for", cfg.Readiness.NoProductionFor, DefaultNoProductionFor, &errs) diff --git a/src/crux/watchdog/settings_test.go b/src/crux/watchdog/settings_test.go index 44fa32f327..3447e1cce8 100644 --- a/src/crux/watchdog/settings_test.go +++ b/src/crux/watchdog/settings_test.go @@ -23,6 +23,7 @@ func TestSettingsFromZeroValueIsRFCDefaults(t *testing.T) { s.StuckOverlayAfter != want.StuckOverlayAfter || s.ShellPromptAfter != want.ShellPromptAfter || s.CrashLoopAfter != want.CrashLoopAfter || + s.LoginStreak != want.LoginStreak || s.HealthyReset != want.HealthyReset || s.NoProductionFor != want.NoProductionFor || s.RestartTimeout != want.RestartTimeout { @@ -41,6 +42,7 @@ func TestSettingsFromExplicitValues(t *testing.T) { Liveness: config.WatchdogLivenessConfig{ StuckOverlayAfter: "3m", ShellPromptAfter: "90s", + LoginStreak: 5, }, Restart: config.WatchdogRestartConfig{ Backoff: []string{"30s", "1m"}, @@ -58,7 +60,7 @@ func TestSettingsFromExplicitValues(t *testing.T) { t.Fatal("explicit enabled:false must map to mode off, and auth_probe:false must win") } if s.ProbeInterval != time.Minute || s.StuckOverlayAfter != 3*time.Minute || - s.ShellPromptAfter != 90*time.Second || s.CrashLoopAfter != 2 || + s.ShellPromptAfter != 90*time.Second || s.CrashLoopAfter != 2 || s.LoginStreak != 5 || s.HealthyReset != 10*time.Minute || s.NoProductionFor != 2*time.Hour { t.Fatalf("explicit values not honored: %+v", s) } @@ -73,6 +75,7 @@ func TestSettingsFromInvalidValuesFallBackLoudly(t *testing.T) { Liveness: config.WatchdogLivenessConfig{ StuckOverlayAfter: "not-a-duration", ShellPromptAfter: "-5m", + LoginStreak: -1, }, Restart: config.WatchdogRestartConfig{ Backoff: []string{"1m", "banana"}, @@ -83,14 +86,16 @@ func TestSettingsFromInvalidValuesFallBackLoudly(t *testing.T) { } s, errs := SettingsFrom(cfg) // One error per invalid field: probe interval, two liveness durations, - // backoff entry, crash-loop count, healthy reset, no-production-for. - const wantErrs = 7 + // login streak, backoff entry, crash-loop count, healthy reset, + // no-production-for. + const wantErrs = 8 if len(errs) != wantErrs { t.Fatalf("want %d config errors, got %d: %v", wantErrs, len(errs), errs) } want := DefaultSettings() if s.ProbeInterval != want.ProbeInterval || s.StuckOverlayAfter != want.StuckOverlayAfter || s.ShellPromptAfter != want.ShellPromptAfter || s.CrashLoopAfter != want.CrashLoopAfter || + s.LoginStreak != want.LoginStreak || s.HealthyReset != want.HealthyReset || s.NoProductionFor != want.NoProductionFor { t.Fatalf("invalid fields must fall back to defaults: %+v", s) } diff --git a/src/deploy/entrypoint.sh b/src/deploy/entrypoint.sh index ad1d774c31..111d79e2dd 100644 --- a/src/deploy/entrypoint.sh +++ b/src/deploy/entrypoint.sh @@ -1017,7 +1017,13 @@ if [ "$IS_KUBERNETES" = "true" ]; then # deliberately NOT merged — it is frozen at provision and every field it # could contribute is either already here or re-asserted by the hub on # the next heartbeat (~30s), including hub.is_public. - if cp "$HIVE_CONFIG_BOOT" "$HIVE_CONFIG_PATH" 2>/dev/null; then + # + # #17468: on hosted spokes the copy-config init container links the + # config path to the runtime config, so the two are one file. cp would + # refuse ("are the same file") and land in the read-only branch below. + if [ "$HIVE_CONFIG_PATH" -ef "$HIVE_CONFIG_BOOT" ]; then + echo "[entrypoint] K8s mode — booting from runtime config $HIVE_CONFIG_BOOT ($HIVE_CONFIG_PATH links to it; ConfigMap is a seed, not merged)" + elif cp "$HIVE_CONFIG_BOOT" "$HIVE_CONFIG_PATH" 2>/dev/null; then echo "[entrypoint] K8s mode — booting from runtime config $HIVE_CONFIG_BOOT (ConfigMap is a seed, not merged)" else export HIVE_CONFIG="$HIVE_CONFIG_BOOT" diff --git a/src/deploy/k8s/error-pages.yaml b/src/deploy/k8s/error-pages.yaml index 79e983ac0f..5922b56473 100644 --- a/src/deploy/k8s/error-pages.yaml +++ b/src/deploy/k8s/error-pages.yaml @@ -60,6 +60,50 @@ data: # "ok": false is the field clients key off (issue #4241). error.json: | {"ok":false,"error":"hive unavailable","detail":"This hive is restarting or its API is temporarily unreachable. The request was NOT applied - retry shortly."} + # Served when the controller intercepts a 403 or 404. These are NOT "retry + # shortly" states: the upstream answered, and the resource is missing or + # forbidden. Before these documents existed, an intercepted 404 fell through + # to the 503 "Hive is restarting" page with an auto-refresh, which Google + # Search Console reported as "Soft 404" on hive.hivecommons.dev and which + # told a human a healthy hub was down (#17431). No spinner, no refresh. + notfound.json: | + {"ok":false,"error":"not found","detail":"No such page or API route on this hive. The request was NOT applied."} + notfound.html: | + + + + + + + Hive — Page Not Found + + + +
+
🔍
+

Page not found

+

The page you're looking for doesn't exist on this hive or has moved.

+

Back to the front page

+
+ + # Served for a 401 intercepted on the hive-api-xhr Ingress (the dashboard's # XHR routes under /api/, see src/pkg/hub/saas_provision.go). That Ingress # deliberately has no auth-signin: fetch() cannot follow the cross-origin @@ -118,7 +162,13 @@ data: # ingress-nginx sends a request here when a hive Ingress intercepts one of # the upstream statuses named in its custom-http-errors annotation ("502,503" # on the hive Ingress, "401,502,503" on the hive-api-xhr Ingress -- see - # src/pkg/hub/saas_provision.go). It rewrites the + # src/pkg/hub/saas_provision.go), or in the controller's GLOBAL + # `custom-http-errors` ConfigMap key for an Ingress with no annotation of + # its own (the hub's). Keep that global list to "502,503,504": with 403 and + # 404 in it, every missing page on hive.hivecommons.dev was intercepted and + # -- because this backend had no 404 branch -- answered as a 503 "Hive is + # restarting" page (#17431). The 403/404 branches below are the safety net + # if the global list ever grows again. It rewrites the # URI to "/" and passes the original request's metadata in headers: # # X-Code the intercepted upstream status, e.g. "502" @@ -165,10 +215,15 @@ data: # 401 gets its own document: it is intercepted from the hive-api-xhr # Ingress (issue #7405) and means "sign in again", not "retry shortly". error_page 401 /unauthorized.$hive_error_ext; + # 403 and 404 share the not-found document: the upstream answered and the + # resource is missing or off-limits, so no spinner and no auto-refresh. + error_page 403 404 /notfound.$hive_error_ext; location = /error.html { internal; } location = /error.json { internal; } location = /unauthorized.html { internal; } location = /unauthorized.json { internal; } + location = /notfound.html { internal; } + location = /notfound.json { internal; } # Probed by the kubelet directly, never through the Ingress, so it is not # affected by the status mapping below. @@ -181,6 +236,8 @@ data: # Reflect the intercepted status back to the caller. `return` answers # every method, so a POST is no longer served a static file with 200. if ($http_x_code = "401") { return 401; } + if ($http_x_code = "403") { return 403; } + if ($http_x_code = "404") { return 404; } if ($http_x_code = "500") { return 500; } if ($http_x_code = "502") { return 502; } if ($http_x_code = "504") { return 504; } diff --git a/src/docs/acmm-policy-matrix.md b/src/docs/acmm-policy-matrix.md index e8b43ae4f8..554f87508a 100644 --- a/src/docs/acmm-policy-matrix.md +++ b/src/docs/acmm-policy-matrix.md @@ -127,7 +127,7 @@ Delivery agents open GitHub issues — bugs, docs gaps, CI problems, security vu | brainstorm | advisory | `brainstorm-advisory.md` | | reviewer | converse | `reviewer-queue.md` | -### L5 — Semi-Autonomous (Semi-Automated) (14 agents) +### L5 — Semi-Autonomous (Semi-Automated) (15 agents) **Permission boundary:** agents open issues and PRs, but do not merge autonomously. Agent PRs get literal `hold` from the level gate for human @@ -145,6 +145,10 @@ manual hold; `hive/` records provenance only. checklist per repository (near-duplicates, common root causes, unlinked PR/issue pairs and already-resolved items), parked with `--needs-decision`. It never closes or edits anyone else's items. +- Redteam ([red-team agent](redteam.md)) is opt-in: paused in every mode, and + refused every repository until its `repos:` scope names the one holding the + `ioscan` red-team corpus. It adds measured attack cases there in + `hold`-labelled PRs and never posts attack text anywhere else. Per-repo opt-in `auto_merge.queue_on_approve_and_unhold` (off by default) lets a person finish an agent PR in one step: when one trusted merger both submits an APPROVED review on an agent PR's current head and removes its level `hold`, Hive queues the PR for auto-merge on green CI exactly as the dashboard's queue button does. Nothing else counts as consent, and the self-merge floor stays at L6. See [hive-merge.md](hive-merge.md#one-human-step-at-l5-approve-and-unhold). @@ -163,9 +167,10 @@ Per-repo opt-in `auto_merge.queue_on_approve_and_unhold` (off by default) lets a | dedupe | issues-only | `dedupe-issues.md` | | telemetry (paused) | holdgated | `telemetry-holdgated.md` | | operations (paused) | holdgated | `operations-holdgated.md` | +| redteam (paused) | holdgated | `redteam-holdgated.md` | | brainstorm | advisory | `brainstorm-advisory.md` | -### L6 — Autonomous (15 agents) +### L6 — Autonomous (16 agents) **Permission boundary:** autonomous delivery lanes can open issues/PRs and eligible PRs can merge on green CI. Auto-merge is off below L6. Switching to @@ -186,7 +191,8 @@ authority. de-escalates, recommends closure and may close escalated `needs-human` Hive PRs at L6, but never merges. Dedupe stays recommendation-only. Telemetry and operations stay paused and use `ISSUES_AND_PRS`, despite their `full` - template names; they never merge their own PRs. + template names; they never merge their own PRs. Redteam stays paused, keeps + its hold-gated template and labels every PR `hold`, even at L6. #### Review and decision gates @@ -241,6 +247,7 @@ workflow is missing or `sentinel-alert` is present, Hive surfaces | dedupe | issues-only | `dedupe-issues.md` | | telemetry (paused) | full | `telemetry-full.md` | | operations (paused) | full | `operations-full.md` | +| redteam (paused) | holdgated | `redteam-holdgated.md` | | brainstorm | advisory | `brainstorm-advisory.md` | ## What hive will say on GitHub at each level @@ -310,6 +317,7 @@ older PR is still in the inbox, only unlabelled on GitHub. Roster history: [#8023](https://github.com/hivecommons/hive/issues/8023) and [#13574](https://github.com/hivecommons/hive/issues/13574). 8. **Telemetry and operations are L5/L6-only opt-in agents.** Below L5 they are absent from the pack roster and dashboard, do not spawn panes, and cannot be kicked. At L5–L6 they use a paused cadence in every governor mode until an operator opts in; they may open issues and PRs but never merge. +9. **Redteam is an L5/L6-only opt-in agent that needs a scope.** It is paused in every governor mode, and with no `repos:` scope it serves no repository at all — the one agent for which an empty scope means nothing rather than everything. See [Red-team agent](redteam.md). ## ioscan hardening defaults per level diff --git a/src/docs/advisory-staleness.md b/src/docs/advisory-staleness.md index 15e37f3a75..e9010d1411 100644 --- a/src/docs/advisory-staleness.md +++ b/src/docs/advisory-staleness.md @@ -15,6 +15,11 @@ never re-derives it. ## The gates +0. **Forge unreachable** — a beat carrying `ForgeUnreachable` is never stale, + whatever the digest's age or error. The spoke cannot reach its GitHub host + from the pod, so an ageing digest is a symptom of the egress fault rather + than a wedge of its own; the row shows a `forge unreachable (github_host)` + pill instead (#17433). 1. **Participation** — no post time *and* no error means "not an advisory hive (or a spoke too old to report)". Unknown, never stale. 2. **Reported error** — flagged with its cause, unless the App is still @@ -49,6 +54,7 @@ never re-derives it. | Pure PR/merge hive | Suppressed | Suppressed | unchanged (expected suppression) | | Every agent paused or off-schedule, digest ageing | Flagged stale — the pause itself lit the pill | Suppressed — no agents, no findings, no digest | Gate 3 (`allAgentsQuietByDesign`, #4528); counted as `hidden_stale` in diagnostics | | Spoke heartbeat collect timed out, beat carries cached/minimal stats (`statsStale`) | `advisory-stale` alert raised from the last-good `advisoryLastPostedAt` while fresh digests were posting | No fleet alert — the post time is not a fresh observation | The hub alert rule skips `StatsStale` beats (#12842); health verdict already reads "heartbeat stats stale" | +| Spoke cannot reach its GitHub host from the pod (`ForgeUnreachable`) | Generic stale pills lit the row while the real fault was cluster egress | No stale-advisory pill — the row shows `forge unreachable (github_host)` instead | `advisoryStale` returns early on `ForgeUnreachable` beats (#17433) | ## Diagnostics diff --git a/src/docs/advisory.md b/src/docs/advisory.md index b3054f2df7..68240d9f64 100644 --- a/src/docs/advisory.md +++ b/src/docs/advisory.md @@ -18,6 +18,7 @@ governor: staleness_days: 7 pr_autoclose: true update_interval_s: 0 # 0 = default (~60s cycle); 30–3600 to slow the refresh + digest_min_interval: 1h # a CHANGED digest is rewritten at most this often; 0 = every changed cycle target: github # github (default) | linear linear_issue: "" # required when target is linear, e.g. ONB-123 ``` @@ -370,6 +371,23 @@ Details worth knowing: - Values outside the band are rejected by the dashboard API and clamped (with a one-time warning in the hive log) when hand-edited into `hive.yaml`. +### One comment, rewritten at most hourly + +The digest lives in exactly one comment per advisory issue, anchored by an +`` marker and closed by an +`Updated N times · last ` footer; the counter is read back from the +comment itself, so it continues across restarts. `update_interval_s` paces how +often the hive *checks*; `governor.advisory.digest_min_interval` (default `1h`, +**Settings → Advisory → Rewrite floor for a changed digest**) bounds how often +a *changed* body is actually written. Live counts in the Advice block drift on +every eval cycle, which used to rewrite the comment every ~5 minutes; now the +first change after the window is written and later drift waits for the next +window. An unchanged digest never writes. The baseline is the comment's own +`updated_at` on GitHub, so a restarted governor never reposts inside the +window; `0` disables the floor. The governor log line +`advisory digest comment written` marks the cycles that really reached GitHub +(`posted advisory digest` is logged for every healthy cycle, skipped or not). + ## Where the digest is posted `governor.advisory.target` — default `github`. Chooses which tracker hosts the diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index e9e7fb593a..d9acd1392a 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -980,7 +980,7 @@ You don't have to design a roster. Hive ships six **ACMM packs** (see [What is a Applying a level **reconciles the whole roster**, not just the diff: missing agents are created (as overlay files in `/data/agent-configs/`), existing agents are merged — pack values fill blanks, but your explicit `backend:`, `model:`, and `enabled: false` always win — and the level's `kick_template`, `mode` and `on_demand` are updated so the agent's *policy* matches the level (an `on_demand` you toggled yourself in the agent's settings dialog is operator-owned and left alone; leaving on-demand starts the agent, entering it stops it). One caveat for `backend:` edited by hand in `hive.yaml` or `hive.yaml.runtime` after a pack has been applied: the edit is honoured only when that agent entry carries **no** `backend_owner:` line, so delete the owner line (`pack` or `operator`) alongside your `backend:` change, and the next apply stamps the kept backend `backend_owner: operator` (#13221). A failed agent doesn't abort the rest; the level is only recorded as cleanly applied when every agent reconciled. One exception to "pack values fill blanks": a `backend:` the pack itself wrote may be moved onto the hive's inference gateway, as described under [Disabling a backend spoke-wide](#disabling-a-backend-spoke-wide) ([#14678](https://github.com/hivecommons/hive/issues/14678)). A failed agent doesn't abort the rest; the level is only recorded as cleanly applied when every agent reconciled. -The L5 roster is the canonical worked example — twelve agents, nine on the governor timer, two opt-in agents paused in every governor mode, plus one on demand: +The L5 roster is the canonical worked example — thirteen agents, nine on the governor timer, three opt-in agents paused in every governor mode, plus one on demand: | Agent | | Mode | Cadence (all governor modes) | |---|---|---|---| @@ -996,6 +996,7 @@ The L5 roster is the canonical worked example — twelve agents, nine on the gov | experimenter ⚗️ | self-improvement experiment campaigns through an engine (default Nous, inline); never files issues/PRs, never promotes | not in any pack — opt in by hand | 24h suggested | | telemetry 📡 | managed-project instrumentation | ISSUES_AND_PRS | paused | | operations 🚨 | managed-project operational practice | ISSUES_AND_PRS | paused | +| redteam 🎭 | measured attacks on hive defenses ([red-team agent](redteam.md)) | ISSUES_AND_PRS | paused | | brainstorm 💡 | ideation | ADVISORY | on demand | At L5, every agent PR gets a `hold` label automatically. The system proposes; it does not merge autonomously. @@ -1042,6 +1043,8 @@ preselected as suggestions in the tab. They remain unsaved until an operator reviews them and clicks **Save**; after that, the persisted declaration governs future telemetry and operations work. +Redteam is also L5/L6-only and paused until an operator opts in from **Agents → Cadences**. Unlike any other agent it also needs a `repos:` scope: without one it is refused every repository. See [Red-team agent](redteam.md#turning-it-on). + ## Live-linked agent definitions (`definition_source`) An agent can be linked to a whole portable `AgentDefinition` YAML file living in a GitHub repo, so an edit to that file propagates into the agent's config on the next reload or startup — no redeploy, no dashboard edit. This is the whole-agent analogue of `promptTemplate`/prompt-source live-linking (see [Policy and prompt templates](../policies/README.md)); both are implemented as graceful-fallback resolvers in `src/pkg/promptsrc` and `src/pkg/defsrc` respectively. diff --git a/src/docs/agent-knowledge-and-memory.md b/src/docs/agent-knowledge-and-memory.md index 3f6392b28d..9cbac7e37b 100644 --- a/src/docs/agent-knowledge-and-memory.md +++ b/src/docs/agent-knowledge-and-memory.md @@ -161,6 +161,14 @@ flowchart LR 600 characters), the runtime's scrubbed pane tail (`pane_lines`, verbatim) and each candidate as `slug — title — summary` with the same ≤300-character summary phase 1 would type. Entry bodies never reach the model. +- **Endpoint path.** A bare host gets `/v1/chat/completions`, a base ending in + `/v1` gets `/chat/completions`, and an endpoint already ending in + `/chat/completions` is used as-is. For the Copilot API set + `endpoint: https://api.githubcopilot.com/chat/completions` with + `api_key_file: /data/copilot-user-token`. Do not use the bare + `https://api.githubcopilot.com` host: it would get `/v1/chat/completions` + appended, and the Copilot API has no `/v1` prefix, so the call 404s (and + under `on_error: silence` the advisor is disabled silently). - **Call.** One chat completion per decision: `temperature: 0`, about 120 output tokens, `timeout_s`, and the `user` field set to `hive-knowledge-advisor:` so proxy spend logs attribute cost per diff --git a/src/docs/agent-watchdog.md b/src/docs/agent-watchdog.md index 23cfd86fdd..8b6ee4e26f 100644 --- a/src/docs/agent-watchdog.md +++ b/src/docs/agent-watchdog.md @@ -28,9 +28,16 @@ launched, running, unpaused agent: restarts until a human (or the resume API) intervenes. A continuous-ready window of `healthy_reset` (default 30m) clears the failure counter. 4. **Auth probing** — a pane sitting at a login screen sets - `Authenticated=False` and raises an alert but deliberately does **not** - restart: restarting into a dead credential is the 1042-restart loop the - RFC documents. Provider-level credential probes reuse the rotation + `Authenticated=False` (reason `PaneShowsLogin`) and raises an alert but + deliberately does **not** restart: restarting into a dead credential is + the 1042-restart loop the RFC documents. Two guards keep a CLI's own + startup handshake from paging anyone: login chrome is ignored inside the + boot grace of the agent's most recent CLI (re)launch — a kick restart or + memory-drain recycle hours into an agent's life boots exactly like a fresh + start — and it must persist for `liveness.login_streak` consecutive polls + (default 3; one sighting reports `Ready=Unknown` with reason + `login chrome seen 1/3 polls`) before it counts, mirroring the pane + poller's own `loginStreak` guard. Provider-level credential probes reuse the rotation package's probers (Claude OAuth usage, Codex app-server handshake, Agy headless usage, DeepSeek balance) and the owner-aware per-agent credential check (per-agent `$HOME` layouts, 0600 session files). @@ -138,6 +145,7 @@ governor: liveness: stuck_overlay_after: 10m shell_prompt_after: 5m + login_streak: 3 # consecutive polls of login chrome before auth-required restart: backoff: [1m, 2m, 4m, 8m, 16m] crash_loop_after: 5 diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 8feed7e871..997f320412 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: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/health` | Public | Basic health probe | `pkg/dashboard/server.go:1827` | +| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1828` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1829` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1835` | +| `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:1840` | +| `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:1841` | +| `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:1844` | +| `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:1845` | +| `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:1846` | +| `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:1847` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1848` | | `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:1918` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1922` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | @@ -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: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` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1849` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1850` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1851` | ## 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: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/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:395` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:396` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:397` | +| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:387` | +| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:388` | +| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:389` | +| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:390` | +| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:391` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:392` | +| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:393` | +| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:570` | | `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: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/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:566` | +| `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:567` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:262` | @@ -263,17 +263,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: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/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:541` | +| `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:544` | +| `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:545` | +| `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:549` | | `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: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/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:553` | +| `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:554` | +| `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:557` | +| `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:559` | +| `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:562` | +| `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:563` | | `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:337` | | `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:338` | | `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:339` | @@ -320,12 +320,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, from memory while this process holds the job and otherwise from the operator-action ledger (`from_ledger: true`; status, requester, start, verdict and rule, with the outcome's words in `notes` or `error`), so the last result outlives the 30-minute in-memory eviction and a restart. A job still running when the hive restarts is never resumed: the next process marks its ledger record `failed` (*interrupted by a hive restart before it finished, and not resumed …*) with a `repo_item_decision_delegated_failed` audit entry, and the operator asks again. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go: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` | +| `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:589`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:382`, `pkg/dashboard/api_acmm_eval.go` | +| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:383` | +| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](acmm-advisor.md) | `pkg/dashboard/api.go:384` | +| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`, and on the needs-human advice `why` (plain-language reasons with counts) and `help`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](advisory.md#owner-advice) | `pkg/dashboard/api.go:386`, `pkg/dashboard/api_hive_advice.go` | +| `POST` | `/api/repos/{owner}/{repo}/issues/{number}/release` | Owner or repo write/maintain/admin | Execute the typed `kind=release` owner step the hub proposed on a parked issue, with the same live preconditions as `/hive approve` ([#12635](https://github.com/hivecommons/hive/issues/12635)). Tag and target are resolved from the trusted owner-step, never from the request. Returns 503 when the GitHub client or config is unavailable; 409 when the repository is `label_driven` (the same refusal `/hive approve` gets there), when `release_on_approve` is off, or when a live precondition fails (`error` carries the refusal reason, which is also posted on the issue); 502 when the release write itself fails. Success returns `{ok, repo, number, tag, url, minStatusSeq}` plus `warning` if the follow-up issue comment failed after the release was created. | `pkg/dashboard/api.go:375`, `pkg/dashboard/api_issue_release.go` | ## Cost, tokens, telemetry @@ -349,37 +349,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: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/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `tag` (comma-separated; a fact must carry every tag), `state` (comma-separated lifecycle states or `all`; only facts in those states are listed, and any state other than `approved` requires a verified owner and returns 403 otherwise), `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:402` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:403` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](public-knowledge-mcp.md)) | `pkg/dashboard/api.go:412` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:404` | +| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](knowledge-toc.md)) | `pkg/dashboard/api.go:405` | +| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:406` | +| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](knowledge-toc.md)) | `pkg/dashboard/api.go:407` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:413` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:418` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Knowledge Create | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:420` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:426` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:427` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:428` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:429` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:430` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:431` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:432` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:433` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:434` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:435` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:436` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:437` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:438` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:439` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:440` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:441` | | `GET` | `/api/config/knowledge/connectors` | Dashboard auth/session | Knowledge connectors config (name, type, layer, scope, env/file auth reference) and registered types | `pkg/dashboard/api.go` | | `PUT` | `/api/config/knowledge/connectors` | Owner only | Replace `knowledge.connectors` after validation; inline secrets rejected | `pkg/dashboard/api.go` | | `GET` | `/api/config/knowledge/connectors/status` | Dashboard auth/session | Per-connector status pill, last sync, pages/facts, last error, plus the `publish` mirror status | `pkg/dashboard/api.go` | @@ -387,34 +387,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: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/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:451` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:454` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:457` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:458` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:459` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | | `GET` | `/api/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: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/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:451` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:454` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:457` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:458` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:459` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | | `GET` | `/api/knowledge/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` | @@ -485,10 +485,10 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/claims` | Dashboard auth | Every live worker claim (`{enabled, claims:[…]}`); `enabled:false` when `claims.enabled: false` | `pkg/dashboard/claims_api.go:53` | -| `GET` | `/api/claims/{owner}/{repo}/{number}` | Dashboard auth | `{held, claim}` for one issue | `pkg/dashboard/claims_api.go:54` | -| `POST` | `/api/claims/{owner}/{repo}/{number}` | Signed-in / hub-proxied / GitHub-token caller claims as a **human** under their login; a verified owner token claims as the owner | Body `{force, ttl_s, session}`. 200 with `outcome` `claimed`/`renewed`/`taken_over`; 409 with `outcome` `held` (same rank, retry with `force`) or `refused` (higher rank holds it) and a `hint` | `pkg/dashboard/claims_api.go:55` | -| `DELETE` | `/api/claims/{owner}/{repo}/{number}` | Same identity rules | Body `{force, reason}`. Releases your claim or a lower-ranked holder's; `force` with a verified owner role releases regardless of holder | `pkg/dashboard/claims_api.go:56` | +| `GET` | `/api/claims` | Dashboard auth | Every live worker claim (`{enabled, claims:[…]}`); `enabled:false` when `claims.enabled: false` | `pkg/dashboard/claims_api.go:54` | +| `GET` | `/api/claims/{owner}/{repo}/{number}` | Dashboard auth | `{held, claim}` for one issue | `pkg/dashboard/claims_api.go:55` | +| `POST` | `/api/claims/{owner}/{repo}/{number}` | Signed-in / hub-proxied / GitHub-token caller claims as a **human** under their login; a verified owner token claims as the owner | Body `{force, ttl_s, session}`. 200 with `outcome` `claimed`/`renewed`/`taken_over`; 409 with `outcome` `held` (same rank, retry with `force`) or `refused` (higher rank holds it) and a `hint` | `pkg/dashboard/claims_api.go:56` | +| `DELETE` | `/api/claims/{owner}/{repo}/{number}` | Same identity rules | Body `{force, reason}`. Releases your claim or a lower-ranked holder's; `force` with a verified owner role releases regardless of holder | `pkg/dashboard/claims_api.go:57` | ### `/api/v1` contributor subpaths @@ -525,70 +525,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: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` | +| `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:496` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:497` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:498` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:499` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:500` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:502` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:503` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:504` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:505` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:506` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:508` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:509` | +| `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:510` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:511` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:512` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:515` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:516` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:517` | +| `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:520` | +| `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:521` | +| `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:522` | +| `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:523` | +| `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:501` | +| `POST` | `/api/nous/artifacts/sync` | Owner only | Nous Artifact Sync | `pkg/dashboard/api.go:518` | +| `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:519` | ## Inception | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `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` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:466` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:467` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:469` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:470` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:471` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:473` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:474` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:475` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:476` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:477` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:478` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:479` | ## Beads | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `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` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:525` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:526` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:527` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:528` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:529` | ## 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:535` | +| `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:536` | | `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` | @@ -602,11 +602,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: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/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:484` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:487` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:488` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:490` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:491` | | `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` | @@ -622,11 +622,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: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/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:400` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:463` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:464` | +| `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:493` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:531` | | `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` | @@ -654,7 +654,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:1852` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1856` | ## Hub SaaS 102 routes — see [api-reference/hub-saas.md](api-reference/hub-saas.md). @@ -678,34 +678,34 @@ always resolved server-side from the validated token. | `GET` | `/api/hub/clusters` | Hub auth | List Clusters | `pkg/hub/saas.go:531` | | `GET` | `/api/hub/image-pulls` | Hub auth | Per-Release Image Pull Series | `pkg/hub/saas.go:377` | | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:522` | -| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1784` | -| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1785` | -| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1719` | -| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1720` | -| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1721` | -| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat | `pkg/hub/server.go:1722` | -| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1723` | -| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1731` | -| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1732` | -| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1733` | -| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1734` | +| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1790` | +| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1791` | +| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1725` | +| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1726` | +| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1727` | +| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat | `pkg/hub/server.go:1728` | +| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1729` | +| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1737` | +| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1738` | +| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1739` | +| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1740` | | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | -| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1742` | -| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1752` | -| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1753` | -| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1754` | -| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1755` | -| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1756` | -| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1757` | -| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1758` | -| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1759` | -| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1762` | -| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1765` | -| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1766` | -| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1773` | -| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1774` | -| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1775` | -| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1792` | -| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1797` | -| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1799` | +| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1748` | +| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1758` | +| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1759` | +| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1760` | +| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1761` | +| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1762` | +| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1763` | +| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1764` | +| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1765` | +| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1768` | +| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1771` | +| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1772` | +| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1779` | +| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1780` | +| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1781` | +| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1798` | +| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1803` | +| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1805` | diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index 793eaa305c..a0d2f6ae70 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -23,27 +23,20 @@ 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: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/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:541` | +| `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:544` | +| `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:545` | +| `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:549` | | `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: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/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:553` | +| `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:554` | +| `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:559` | +| `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: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` | | `DELETE` | `/api/agents/{name}` | Owner only | Agent Delete | `pkg/dashboard/api.go:340` | -| `GET` | `/api/agents/{name}/log` | Dashboard auth/session | Agent Full Log | `pkg/dashboard/api.go:138` | -| `GET` | `/api/agents/{name}/terminal-urls` | Dashboard auth/session | Agent Terminal URLs | `pkg/dashboard/api.go:142` | -| `GET` | `/api/agents/{name}/kicks` | Dashboard auth/session | Agent Kick Log List | `pkg/dashboard/api.go:145` | -| `GET` | `/api/agents/{name}/kicks/{id}` | Dashboard auth/session | Agent Kick Log Get | `pkg/dashboard/api.go:146` | -| `GET` | `/agents/{name}/kicks` | Dashboard auth/session | Agent Kick History Page (HTML) | `pkg/dashboard/api.go:147` | -| `POST` | `/api/agents/{name}/login-code` | Owner only | Agent Login Code | `pkg/dashboard/api.go:169` | - ### Kick is asynchronous diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 322b6c8637..f8773debdf 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: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` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1849` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1850` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1851` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index 7e4559dc3f..aa5396d4e3 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: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` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:525` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:526` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:527` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:528` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:529` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 5434295193..a200c150b3 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -73,19 +73,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `DELETE` | `/api/config/governor/agents/{name}` | Owner only | Governor Remove Agent | `pkg/dashboard/api.go:326` | | `PUT` | `/api/config/governor/repos` | Owner only | Governor Repos | `pkg/dashboard/api.go:327` | | `POST` | `/api/config/governor/repos/check-access` | Dashboard auth/session | Governor Repo Check Access | `pkg/dashboard/api.go:331` | -| `PUT` | `/api/config/github` | Owner only | Config GitHub; `agent_github_api_hourly_cap` sets the fleet default `agents.github_api_hourly_cap` (a whole number, 0 = no cap, `null` = remove the key so the default 300 applies), applies to the proxy without a restart, audited as `config_github` with the old and new cap; the answer echoes `agent_github_api_hourly_cap` and `agent_github_api_hourly_cap_set` | `pkg/dashboard/api.go:332` | -| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps; `settings.agent_github_api_hourly_cap` (the fleet default as applied) and `settings.agent_github_api_hourly_cap_set` (whether the key is written), with `settings.defaults.agent_github_api_hourly_cap` (300) | `pkg/dashboard/api.go:335` | -| `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` | +| `PUT` | `/api/config/github` | Owner only | Config GitHub | `pkg/dashboard/api.go:332` | +| `GET` | `/api/config/github/forge-apps` | Dashboard auth/session | Config GitHub Forge Apps | `pkg/dashboard/api.go:335` | +| `GET` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Get | `pkg/dashboard/api.go:395` | +| `PUT` | `/api/config/sidebar` | Dashboard auth/session | Sidebar Set | `pkg/dashboard/api.go:396` | +| `GET` | `/api/config/backends` | Dashboard auth/session | Backends | `pkg/dashboard/api.go:397` | +| `GET` | `/api/compliance/status` | Merger or owner | Evaluated compliance controls for the frameworks in `compliance.frameworks` (`compliance.Report`, JSON): per control `meets`/`deviates`/`off`/`not_covered` with current vs recommended value per mapped setting, a summary, and the non-certification disclaimer — see [Compliance](../compliance.md) ([#11078](https://github.com/hivecommons/hive/issues/11078)) | `pkg/dashboard/api.go:387` | +| `GET` | `/api/compliance/posture` | Merger or owner | Posture-check catalogue, effective interval / window / history retention, and the latest run (`compliance.PostureRun`: schedule/manual trigger, `triggered_by` identity, and per-check `pass`/`fail`/`skip`/`error`, detail, control ids, evidence refs); `?since=` (RFC 3339, `YYYY-MM-DD` or a look-back such as `168h`) adds every run since then, oldest first, capped at 1000 — see [Compliance](../compliance.md#posture-checks-catalogue) ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:388` | +| `POST` | `/api/compliance/posture/run` | Merger or owner | Run the posture checks now, attributed to the authenticated user, and record the pass in the history; audited as `compliance_posture_run`; `409` when no framework is selected or a pass is already running ([#11079](https://github.com/hivecommons/hive/issues/11079)) | `pkg/dashboard/api.go:389` | +| `GET` | `/api/compliance/posture/history` | Owner only | Posture history for `?since=`/`?until=` (default the last 30 days) as one series per check: points (`at`, `status`), status counts, `last_fail_at` and the latest result with detail and evidence refs; at most the 1000 most recent runs — see [Compliance](../compliance.md#evidence-exports-and-attestations) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:390` | +| `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:391` | +| `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:392` | +| `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:393` | +| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:570` | | `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,15 +94,15 @@ 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: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/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:566` | +| `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:567` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:253` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:256` | -| `PUT` | `/api/config/governor/features` | Owner only | Governor Features; `writebackKinds` replaces the whole `writeback.kinds` map (a kind sent as `null` or `{}` is dropped). Wrapped by the admin MCP `governor.feature_settings` and `writeback.kind_policy` operations | `pkg/dashboard/api.go:262` | +| `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:262` | | `GET` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Get | `pkg/dashboard/api.go:263` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Governor General Advanced Set | `pkg/dashboard/api.go:264` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:268` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:269` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set | `pkg/dashboard/api.go:269` | | `PATCH` | `/api/config/auto-merge` | Owner only | Partially update auto-merge settings, including nested `merge_train`; omitted fields stay unchanged; returns effective settings and bot-author metadata | `pkg/dashboard/api_config_automerge.go` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:275` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:277` | diff --git a/src/docs/api-reference/contribute.md b/src/docs/api-reference/contribute.md index 95b00b9151..594f974588 100644 --- a/src/docs/api-reference/contribute.md +++ b/src/docs/api-reference/contribute.md @@ -67,10 +67,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/claims` | Dashboard auth | Every live worker claim (`{enabled, claims:[…]}`); `enabled:false` when `claims.enabled: false` | `pkg/dashboard/claims_api.go:53` | -| `GET` | `/api/claims/{owner}/{repo}/{number}` | Dashboard auth | `{held, claim}` for one issue | `pkg/dashboard/claims_api.go:54` | -| `POST` | `/api/claims/{owner}/{repo}/{number}` | Signed-in / hub-proxied / GitHub-token caller claims as a **human** under their login; a verified owner token claims as the owner | Body `{force, ttl_s, session}`. 200 with `outcome` `claimed`/`renewed`/`taken_over`; 409 with `outcome` `held` (same rank, retry with `force`) or `refused` (higher rank holds it) and a `hint` | `pkg/dashboard/claims_api.go:55` | -| `DELETE` | `/api/claims/{owner}/{repo}/{number}` | Same identity rules | Body `{force, reason}`. Releases your claim or a lower-ranked holder's; `force` with a verified owner role releases regardless of holder | `pkg/dashboard/claims_api.go:56` | +| `GET` | `/api/claims` | Dashboard auth | Every live worker claim (`{enabled, claims:[…]}`); `enabled:false` when `claims.enabled: false` | `pkg/dashboard/claims_api.go:54` | +| `GET` | `/api/claims/{owner}/{repo}/{number}` | Dashboard auth | `{held, claim}` for one issue | `pkg/dashboard/claims_api.go:55` | +| `POST` | `/api/claims/{owner}/{repo}/{number}` | Signed-in / hub-proxied / GitHub-token caller claims as a **human** under their login; a verified owner token claims as the owner | Body `{force, ttl_s, session}`. 200 with `outcome` `claimed`/`renewed`/`taken_over`; 409 with `outcome` `held` (same rank, retry with `force`) or `refused` (higher rank holds it) and a `hint` | `pkg/dashboard/claims_api.go:56` | +| `DELETE` | `/api/claims/{owner}/{repo}/{number}` | Same identity rules | Body `{force, reason}`. Releases your claim or a lower-ranked holder's; `force` with a verified owner role releases regardless of holder | `pkg/dashboard/claims_api.go:57` | ### `/api/v1` contributor subpaths diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 6d4952da55..d708350499 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -25,8 +25,9 @@ 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:535` | +| `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:536` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:72` | +| `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:75` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:73` | | `POST` | `/api/self-upgrade` | Owner only | Self Upgrade | `pkg/dashboard/api.go:74` | | `GET` | `/api/backup/status` | Owner only | Backup Status — `available:false` with a reason when no encryption key is configured | `pkg/dashboard/api.go:79` | @@ -39,19 +40,18 @@ 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: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/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:484` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:487` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:488` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:490` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:491` | | `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: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/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:580` | | `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` | @@ -60,12 +60,13 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:190` | | `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:202` | | `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:203` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:204` | | `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:205` | -| `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go: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/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:400` | +| `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:463` | +| `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:464` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:493` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:531` | | `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` | @@ -73,11 +74,6 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `GET` | `/api/leaderboard` | Public | Leaderboard API | `pkg/dashboard/api_contribute.go:367` | | `GET` | `/api/leaderboard/teams` | Public | Team Leaderboards | `pkg/dashboard/api_contribute.go:368` | | `GET` | `/api/leaderboard/style` | Public | Leaderboard Style | `pkg/dashboard/api_contribute.go:369` | -| `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:75` | - - - -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:204` | | `GET` | `/api/leaderboard/battle-log` | Public | Scrubbed public Battle Log activity feed for leaderboard widgets. | `pkg/dashboard/battle_log.go:108` | | `GET` | `/api/leaderboard/hive-of-week` | Public | Featured weekly project metadata, configured render URLs (empty when none), gource source URL, and embed snippets. | `pkg/dashboard/battle_log.go:109` | | `GET` | `/api/leaderboard/gource-log` | Public | Gource custom log source for a project/week, derived from public hive event data. | `pkg/dashboard/battle_log.go:110` | @@ -88,7 +84,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:1852` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1856` | ### Activity observation provenance diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 43dee31e8b..b6f2cadf98 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: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; `ghRateLimits.agent_caps` `{fleet_cap, fleet_cap_set, window_s, agents: [{agent, cap, source: agent|base_agent|fleet, base_agent, calls}]}` is the GitHub API budget panel's per-agent proxy cap (0 = no cap) and the calls the proxy counted against it in the current sliding hour (`calls` is null for an uncapped agent, which the proxy does not count) | `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/health` | Public | Basic health probe | `pkg/dashboard/server.go:1827` | +| `GET` | `/api/health/deep` | Public | Deep health probe; the `webhooks` check (`status`, `detail`, `mode`, `mode_reason_code`, `rejected_1h`) warns when deliveries arrive but cannot be used — no `GITHUB_WEBHOOK_SECRET`, signature mismatch, undecodable payload — and never changes the overall verdict | `pkg/dashboard/server.go:1828` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1829` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1835` | +| `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; `ghRateLimits.agent_caps` `{fleet_cap, fleet_cap_set, window_s, agents: [{agent, cap, source: agent|base_agent|fleet, base_agent, calls}]}` is the GitHub API budget panel's per-agent proxy cap (0 = no cap) and the calls the proxy counted against it in the current sliding hour (`calls` is null for an uncapped agent, which the proxy does not count) | `pkg/dashboard/server.go:1840` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1841` | +| `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:1844` | +| `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:1845` | +| `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:1846` | +| `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:1847` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1848` | | `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/hub-server.md b/src/docs/api-reference/hub-server.md index 77128c0600..a7ca0e57f6 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -33,37 +33,37 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/hub/clusters` | Hub auth | List Clusters | `pkg/hub/saas.go:531` | | `GET` | `/api/hub/image-pulls` | Hub auth | Per-Release Image Pull Series | `pkg/hub/saas.go:377` | | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:522` | -| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1784` | -| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1785` | -| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1719` | -| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1720` | -| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1721` | -| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat | `pkg/hub/server.go:1722` | -| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1723` | -| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1731` | -| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1732` | -| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1733` | -| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1734` | +| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1790` | +| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1791` | +| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1725` | +| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1726` | +| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1727` | +| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat. A request carrying `X-Hive-Activity-Update` is an activity-only update ([#15963](https://github.com/hivecommons/hive/issues/15963)): body `{"activity_update":{"hive_id","activity"}}`, the same per-hive bearer, accepted only for a hive already in the registry (`404` otherwise); it replaces the in-memory activity digest and nothing else, and the signed response carries `ok`, `activity_etag` and `activity_events_ack` (the highest activity event sequence number the hub holds for the hive, [#15964](https://github.com/hivecommons/hive/issues/15964); full heartbeat responses carry it too) | `pkg/hub/server.go:1728` | +| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1729` | +| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1737` | +| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1738` | +| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1739` | +| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1740` | | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | -| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1742` | -| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1752` | -| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1753` | -| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1754` | -| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1755` | -| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1756` | -| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1757` | -| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1758` | -| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1759` | -| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1762` | -| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1765` | -| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1766` | -| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1773` | -| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1774` | -| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1775` | -| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1792` | -| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1797` | -| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1799` | +| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1748` | +| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1758` | +| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1759` | +| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1760` | +| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1761` | +| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1762` | +| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1763` | +| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1764` | +| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1765` | +| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1768` | +| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1771` | +| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1772` | +| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1779` | +| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1780` | +| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1781` | +| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1798` | +| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1803` | +| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1805` | | `GET` | `/activity` | Signed-in user | Fleet activity page ([#16063](https://github.com/hivecommons/hive/issues/16063)): read-only, data-free shell that polls `/api/hub/activity` every 15 s with `If-None-Match`. No session → `307` to `/login`; blocked user → `403`. Own Content-Security-Policy (scripts and styles from `'self'` only, `script-src-attr`/`style-src-attr` `'none'`), `Cache-Control: no-cache` + content `ETag`. See [Hub Fleet activity page](../hub-fleet-activity.md) | `pkg/hub/activity_page.go` | | `GET` | `/activity/public` | Public | Public-safe Fleet activity page ([#15966](https://github.com/hivecommons/hive/issues/15966)): the same data-free shell as `/activity`, served without a session; on this path the page polls `/api/hub/activity/public` with `credentials: 'omit'`. Source of the `twitch.tv/hivecommonsfleet` broadcast. Same CSP and cache headers as `/activity`. See [Hub Fleet activity page](../hub-fleet-activity.md#public-safe-view) | `pkg/hub/activity_public.go` | | `GET` | `/activity/assets/{name}` | Public | The shared tracker assets the Fleet activity page loads, byte-identical: the row asset (`pkg/webassets/trackerrow`, [#16062](https://github.com/hivecommons/hive/issues/16062)) and the `am.*` URL-view and display-playlist helpers (`pkg/webassets/trackerview`, [#16064](https://github.com/hivecommons/hive/issues/16064)); only names in `trackerrow.Files` or `trackerview.Files`, else `404`. `Cache-Control: no-cache` + content `ETag` | `pkg/hub/activity_page.go` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 25b2dffa1b..003f651972 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: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` | +| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:466` | +| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:467` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:468` | +| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:469` | +| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:470` | +| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:471` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:472` | +| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:473` | +| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:474` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:475` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:476` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:477` | +| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:478` | +| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:479` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index 13ea40724f..11843884c7 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: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/knowledge` | Dashboard auth/session | Paginated knowledge facts: `type` filter, `limit` (default 50, max 200; invalid/non-positive values use the default), `offset` (default 0). Returns `enabled`, `facts`, `count` (this page), `total`, `limit`, `offset`, `has_more`; ordered by layer then slug. Offsets are not snapshot cursors: concurrent edits may shift pages. | `pkg/dashboard/api.go:402` | +| `GET` | `/api/knowledge/export` | Dashboard auth/session | Knowledge Export | `pkg/dashboard/api.go:403` | +| `POST` | `/mcp/knowledge` | Public (read-only) when the dashboard setting or `HIVE_PUBLIC_KNOWLEDGE` is on; otherwise 404 to a signed-in caller and 401 to one who is not | Public Knowledge MCP endpoint — `initialize`, `tools/list`, `tools/call` for `knowledge_search`/`knowledge_toc`/`knowledge_get`/`knowledge_export` ([docs](../public-knowledge-mcp.md)) | `pkg/dashboard/api.go:412` | +| `GET` | `/api/knowledge/search` | Dashboard auth/session | Knowledge Search | `pkg/dashboard/api.go:404` | +| `GET` | `/api/knowledge/toc` | Dashboard auth/session | Scoped knowledge table of contents: capped, body-free entries (`id`, `title`, `type`, `layer`, `repo`, `tags`, `status`, `confidence`, `updated`, `size_bytes`, `source`) plus `total`/`returned`/`truncated`. Query: `layers`, `repos`, `types`, `tags` (comma-separated), `limit` (default 50, max 200), `include_states` (operator opt-in for `draft`/`deprecated`/`superseded`/`all`), `format=prompt` with `max_chars` for a bounded markdown rendering, `agent` to apply that agent's `knowledge.agent_scopes` entry (the other parameters can only narrow it). Approved knowledge only by default ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:405` | +| `GET` | `/api/knowledge/effective` | Dashboard auth/session | Effective knowledge for one agent (`agent` required): the agent's `knowledge.agent_scopes` entry (unrestricted when it has none) intersected with the request scope (approved only unless `include_states` is set). Returns `scope` (resolved scope applied, with `configured`), `included` TOC entries, `excluded` entries each with a `reason` (`lifecycle`, `layer`, `repo`, `type` or `tag` — first failing check, in that order), `included_total`/`excluded_total`/`included_returned`/`excluded_returned` and `truncated`; `limit` caps each list (default 50, max 200) ([docs](../knowledge-toc.md#effective-knowledge)) | `pkg/dashboard/api.go:406` | +| `GET` | `/api/knowledge/entry/{id}` | Dashboard auth/session | Full read of one knowledge entry: `markdown` (front-matter plus body) and the fact. Takes the same scope, `include_states` and `agent` query as the table of contents and returns 404 for an entry outside it ([docs](../knowledge-toc.md)) | `pkg/dashboard/api.go:407` | +| `POST` | `/api/knowledge/cli-memory/drain-legacy` | Owner only | One-shot drain of the shared home's legacy Claude memory (`/data/home/.claude/projects/*/memory`) into `state: draft` entries in `bead-synth-wiki`, tagged `cli-memory` and `agent:shared`, deduplicated by content hash. Body `{"truncate": bool}` (default false) empties only files whose every fact is now stored. Returns `store`, `agent`, `sources`, `drained`, `dupes`, `skipped`, `truncate`, `truncated`, `kept`, `errors`; 409 when the vault is not connected. Audited as `knowledge_drain_legacy_memory` ([docs](../knowledge-lifecycle.md#auto-memory-drafts)) | `pkg/dashboard/api.go:409` | +| `GET` | `/api/knowledge/public` | Dashboard auth/session | Public Knowledge MCP sharing status (`enabled`, `tags`, `source`, endpoint URL) | `pkg/dashboard/api.go:413` | +| `PUT` | `/api/knowledge/public` | Owner only | Persist public Knowledge MCP sharing setting; overrides env vars until changed | `pkg/dashboard/api.go:414` | +| `GET` | `/api/knowledge/health` | Dashboard auth/session | Knowledge Health | `pkg/dashboard/api.go:415` | +| `GET` | `/api/knowledge/stats` | Dashboard auth/session | Knowledge Stats | `pkg/dashboard/api.go:416` | +| `GET` | `/api/knowledge/graph` | Dashboard auth/session | Knowledge Graph | `pkg/dashboard/api.go:417` | +| `GET` | `/api/knowledge/fact-history` | Dashboard auth/session | Fact History | `pkg/dashboard/api.go:418` | +| `POST` | `/api/knowledge/create` | Dashboard auth/session | Create one fact (`title`, `body`, `type`, `tags`, `layer`, `confidence`, `state`). `state` is `approved` (default) or `draft`; a draft is written with `state: draft` into the local channel named by `layer` (400 when there is none, 409 when its title already names an entry). A request tagged `cli-memory` must be a draft carrying only `cli-memory`, `agent:`, `cli:`, `memhash:` and `repo:/` tags (400 otherwise) | `pkg/dashboard/api.go:419` | +| `POST` | `/api/knowledge/import` | Dashboard auth/session | Knowledge Import | `pkg/dashboard/api.go:420` | +| `POST` | `/api/knowledge/promote` | Dashboard auth/session | Knowledge Promote | `pkg/dashboard/api.go:426` | +| `GET` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs List | `pkg/dashboard/api.go:427` | +| `POST` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Add | `pkg/dashboard/api.go:428` | +| `DELETE` | `/api/knowledge/subscriptions` | Dashboard auth/session | Knowledge Subs Remove | `pkg/dashboard/api.go:429` | +| `PUT` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Update | `pkg/dashboard/api.go:430` | +| `DELETE` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Delete | `pkg/dashboard/api.go:431` | +| `GET` | `/api/knowledge/{layer}` | Dashboard auth/session | Knowledge Layer | `pkg/dashboard/api.go:432` | +| `GET` | `/api/knowledge/{layer}/{slug}` | Dashboard auth/session | Knowledge Fact | `pkg/dashboard/api.go:433` | +| `PUT` | `/api/knowledge/enabled` | Owner only | Knowledge Toggle | `pkg/dashboard/api.go:434` | +| `GET` | `/api/knowledge/bead-synthesizer` | Dashboard auth/session | Bead Synth Status | `pkg/dashboard/api.go:435` | +| `PUT` | `/api/knowledge/bead-synthesizer/enabled` | Owner only | Bead Synth Toggle | `pkg/dashboard/api.go:436` | +| `GET` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults List | `pkg/dashboard/api.go:437` | +| `POST` | `/api/knowledge/vaults` | Owner only | Vaults Connect | `pkg/dashboard/api.go:438` | +| `DELETE` | `/api/knowledge/vaults` | Dashboard auth/session | Vaults Disconnect | `pkg/dashboard/api.go:439` | +| `POST` | `/api/knowledge/vaults/reindex` | Dashboard auth/session | Vaults Reindex | `pkg/dashboard/api.go:440` | +| `GET` | `/api/knowledge/vaults/{name}/facts` | Dashboard auth/session | Vault Facts | `pkg/dashboard/api.go:441` | | `GET` | `/api/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: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/git-sources` | Dashboard auth/session | Git Sources List | `pkg/dashboard/api.go:451` | +| `POST` | `/api/knowledge/git-sources` | Owner only | Git Sources Connect | `pkg/dashboard/api.go:452` | +| `DELETE` | `/api/knowledge/git-sources` | Owner only | Git Sources Disconnect | `pkg/dashboard/api.go:453` | +| `POST` | `/api/knowledge/obsidian/sync` | Dashboard auth/session | Obsidian Sync | `pkg/dashboard/api.go:454` | +| `GET` | `/api/knowledge/documents` | Dashboard auth/session | Documents List | `pkg/dashboard/api.go:455` | +| `POST` | `/api/knowledge/documents` | Dashboard auth/session | Documents Import | `pkg/dashboard/api.go:456` | +| `GET` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Get | `pkg/dashboard/api.go:457` | +| `DELETE` | `/api/knowledge/documents/{slug}` | Dashboard auth/session | Document Delete | `pkg/dashboard/api.go:458` | +| `POST` | `/api/knowledge/documents/{slug}/reimport` | Dashboard auth/session | Document Reimport | `pkg/dashboard/api.go:459` | +| `GET` | `/api/knowledge/context7/search` | Dashboard auth/session | Context7 Search | `pkg/dashboard/api.go:460` | +| `POST` | `/api/knowledge/cleanup-orphans` | Dashboard auth/session | Cleanup Orphans | `pkg/dashboard/api.go:461` | +| `GET` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channels List | `pkg/dashboard/api.go:424` | +| `POST` | `/api/knowledge/channels` | Dashboard auth/session | Knowledge Channel Create | `pkg/dashboard/api.go:425` | | `GET` | `/api/knowledge/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 c754debb7c..8ae2940fd3 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: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` | +| `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:496` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:497` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:498` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:499` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:500` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:502` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:503` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:504` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:505` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:506` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:507` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:508` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:509` | +| `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:510` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:511` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:512` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:513` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:514` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:515` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:516` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:517` | +| `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:520` | +| `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:521` | +| `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:522` | +| `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:523` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 1a3ee83ccc..efe2e1a43a 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -15,19 +15,19 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:362`, `pkg/dashboard/api_repo_hold.go` | -| `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage, job_id}` (`job_id` is the let-hive-decide job a record is for); `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. 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` | +| `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, from memory while this process holds the job and otherwise from the operator-action ledger (`from_ledger: true`; status, requester, start, verdict and rule, with the outcome's words in `notes` or `error`), so the last result outlives the 30-minute in-memory eviction and a restart. A job still running when the hive restarts is never resumed: the next process marks its ledger record `failed` (*interrupted by a hive restart before it finished, and not resumed …*) with a `repo_item_decision_delegated_failed` audit entry, and the operator asks again. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/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` | +| `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:371`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:372`, `pkg/dashboard/api_maintainer_notes.go` | +| `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:373`, `pkg/dashboard/api_maintainer_notes.go` | +| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:377`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:378` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:380` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:589`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:368`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | +| `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:382`, `pkg/dashboard/api_acmm_eval.go` | +| `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:383` | +| `GET` | `/api/acmm-recommendation` | Dashboard auth/session | Advisory level-up recommendation (`acmmadvisor.Recommendation`, JSON): never changes the applied level — see [ACMM advisor](../acmm-advisor.md) | `pkg/dashboard/api.go:384` | +| `GET` | `/api/hive-advice` | Dashboard auth/session | Weekly owner advice (`hiveadvisor.Result`, JSON) shared with the advisory digest: recommendations with `items`, `links` (Overview export paths) and `bands`; `bands[]` rule text; `counts` naming the governor actionable queue vs. the Overview total. Which recommendations show is frozen for 7 days; their numbers refresh every call — see [Owner advice](../advisory.md#owner-advice) | `pkg/dashboard/api.go:386`, `pkg/dashboard/api_hive_advice.go` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index e99d4e8efe..486d69b0cd 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:1918` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1922` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:90` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:91` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:92` | diff --git a/src/docs/config-layering.md b/src/docs/config-layering.md index 6a32ea2fe4..22db035928 100644 --- a/src/docs/config-layering.md +++ b/src/docs/config-layering.md @@ -115,7 +115,11 @@ ambiguity cost real debugging time. **On Kubernetes it is the boot input after the first boot** (#2392). When a non-empty `/data/hive.yaml.runtime` (or the legacy `hive.yaml.bak`) exists, the -entrypoint copies it over the config path and boots from it; the ConfigMap seed +binary boots from it, either directly through the `/etc/hive/hive.yaml` link +(on a spoke whose `copy-config` init container carries the #17468 `ln -sf`; +the entrypoint then skips the copy) or, on a spoke not yet linked (older init +command, or legacy `hive.yaml.bak` only), by the entrypoint copying the runtime +config over the config path. Either way the ConfigMap seed is not used and the overlay merge does not run. Only when neither exists (first boot, or a hive reprovisioned onto a PVC without one) does the entrypoint start from the seed, merge `/data/hive.yaml.dashboard` over it, and *write* the result @@ -123,7 +127,7 @@ to `hive.yaml.runtime`. `Config.Save()` rewrites it on every save. With neither file and no seed, the entrypoint exits 1. The `copy-config` init container only seeds the config path when the PVC has no runtime config (#2402). -**Outside Kubernetes it is a live boot input, and the source of truth.** There is no +**Outside Kubernetes, `hive.yaml.runtime` is a live boot input, and the source of truth.** There is no ConfigMap and no overlay in that mode, so the entrypoint restores this file over the config path on every boot (or points `HIVE_CONFIG` straight at it, and pins the same path into the launch argv as `--config`, when the config path is @@ -136,6 +140,36 @@ outside Kubernetes because this file already plays that role. > not an input" and mentioned Docker only in passing. That was wrong for every > non-Kubernetes hive, where the file is precisely an input. +**Which file to edit on a hosted spoke** ([#17468](https://github.com/hivecommons/hive/issues/17468)). +`/etc/hive` is an `emptyDir`, so nothing written there survives a restart on +its own. The three files are: + +| File | Role | Survives restart | +|---|---|---| +| `/data/hive.yaml.runtime` | the persisted boot source after first boot; `Config.Save()` writes it on every save | yes (PVC) | +| `/data/hive.yaml.dashboard` | secret-free overlay merged over the ConfigMap seed **only** on a boot with no runtime config (first boot, reprovision) | yes (PVC) | +| `/etc/hive/hive.yaml` | the config path the binary loads; once a runtime config exists, the init container makes it a **symlink** to `/data/hive.yaml.runtime` | only through the link | + +On a spoke provisioned (or whose deployment manifest was re-applied) after +#17468, editing `/etc/hive/hive.yaml` edits the runtime config, and `kubectl +rollout restart` keeps the change. `Config.Save()` writes the config path in +place (no temp-file rename), so saves do not replace the link. The link exists +only where the init container carries the `ln -sf`: it is written into the +provision manifest, and hub upgrades (`kubectl set image`) do not rewrite the +init command, so spokes provisioned earlier keep the old `cp`-only command and +lose edits to `/etc/hive/hive.yaml` on restart. A spoke carrying only the +legacy `hive.yaml.bak` is never linked (that file is never written), and on +first boot the path is a plain copy of the seed until the next restart. + +To check, read the `boot: config source of truth` log line: if `boot_source` +differs from `persisted_path`, the path is **not** linked, so edit +`persisted_path` instead. To pick up the new init command, re-apply the +deployment; inspect the current one with the jsonpath one-liner in +[HUB_DISASTER_RECOVERY.md](../../docs/HUB_DISASTER_RECOVERY.md). The binary logs `boot: config source of truth` at startup +with `loaded_from`, `boot_source` (symlinks resolved) and `persisted_path`, and +`/api/config/export` reports the same file as `metadata.persisted_path` — +edit that one. + ### Which mode am I in? There is no Docker-specific or Podman-specific code path. The entrypoint and diff --git a/src/docs/dashboard-copy-inventory.md b/src/docs/dashboard-copy-inventory.md index c37c0538c1..b9441cd69e 100644 --- a/src/docs/dashboard-copy-inventory.md +++ b/src/docs/dashboard-copy-inventory.md @@ -67,6 +67,7 @@ The new hover, verbatim (title line omitted): | `stageTrackerTriageNeededCaption` (`stageTrackerCaption` 015, `stageTrackerNewState` hold text) | row caption, feed | 110 ("Actionable, but no maintainer has looked at it yet; waiting for triage — triage needed: carries needs triage": *triage* ×3 after the chevron word) / 84 ("New · waiting for a maintainer's triage (add `triage/accepted`); the hive's next pass in 7m") | 31 ("Triage needed — accept or close"; the next-mover and next-pass narration stay on the chevron hover) | `TestStageTracker_TriageNeededStage`, `TestStageTracker_ReporterTrustHoldReadsTriageNeeded`, `TestStageTrackerNewState` | | `stageTrackerLeadActionHtml` (`tracker-actions.js`) | the row header's inline lead button (chip slot) | — (the lead sat in the ⋯ menu only) | the menu entry's label (1–4), its hint as the hover | `TestStageTrackerLeadActionInline`, `TestStageTrackerMaintainerRowsHaveLeadAction` | | Toasts (`STAGE_TRACKER_ACTING_CAPTIONS`, acted labels) | toast | 2–4 each | unchanged | — | +| `stageTrackerHumanGateHtml` + `stageTrackerHumanGateStatusText` / `stageTrackerHumanGateTip` / `stageTrackerHumanGateVerbs` (`tracker-human-gate.js`, [#17470](https://github.com/hivecommons/hive/issues/17470)) | the one human-gate pill in the chip slot: status segment, its hover, the verb buttons, the `…` menu | three or four controls for one gate — *Needs human · review* chevron word (3) + `sentinel` chip (1) + `Approve ▸` (1) + `Let hive decide ▸` (3) — and no verb at all for a sentinel alert or a held 090 (*Held · sentinel · confirm intent*, 4) | one pill: *Needs human · review, sentinel* (4) + fixed verbs per reason (1–2 words each, ≤ 3 visible, the rest behind `…`); hover = one line per reason (`review: `, `sentinel: `); *settling…* (1) after a verb runs | `TestStageTrackerHumanGateRows`, `TestStageTrackerHumanGateWiring`, `TestStageTrackerSentinelLaneText` | | `stageTrackerStripItems` holder token + `stageTrackerClaimantIconKind` (`tracker-row-strip.js`, `tracker-row.js`) on the PR in progress chevron ([#15541](https://github.com/hivecommons/hive/issues/15541)) | lit chevron word, chevron hover | *PR in progress* (bare; the holder token only reached PRs from review on) | *PR in progress · scanner ⬡*, *PR in progress · @odttlnt's clanker 🤖*, *PR in progress · @clubanderson 👤* — the same token and hover line as *Claimed ·*; the name ellipsizes before the one-line sub-row wraps; a detour word that already names them (*Returned to @bob's clanker*) does not repeat them | `TestStageTrackerClaimantChevronJS`, `TestStageTrackerPRClaimant`, `TestStageTrackerClaimantStage` | | `stageTrackerHolderPresenceHtml` (`tracker-words.js`) after the holder token; `stageTrackerOfflineAuthorCaption` + `stageTrackerWaitingOn` at stage None (Go) | lit chevron holder suffix, chevron hover, row caption | *PR in progress · @odttlnt's clanker 🤖* (no live state; a fork PR the gate kept label-less read as unclassified even when the engine held it at 085) | *PR in progress · @odttlnt's clanker 🤖 · ■ offline 3h* (muted; *· ○ not registered* for a login with no profile here; nothing when online); caption "@odttlnt's clanker is offline 3h; a green PR is reviewed and merged without its author — hive adopts it only once it is returned (red CI, conflicts or review asks) and nothing is pushed for 15m"; a suppressed-label 085 record keeps *Needs human decision* | `TestStageTrackerHolderPresenceJS`, `TestStageTrackerUnclassifiedClankerPROfflineCaption`, `TestStageTrackerSuppressedDecisionRecordKeepsStage` | | `stageTrackerLinkedPRProgress` (Go) + `stageTrackerEventText` / `stageTrackerNestedOpenPRs` (`tracker-motion.js`, `tracker-row-layout.js`) on an adoption pair ([#15495](https://github.com/hivecommons/hive/issues/15495)) | issue row caption, feed line, inline lead button | *fell back to Covered by pr — Covered by PR #15537 — Review swarm requested; … ; PR #15508 — Hive adopted this PR … — changes requested* (48) and a *Let hive decide — all 2 PRs* lead on a row with nothing to decide | *Covered by #15537 (adopted from @mendezr's #15508) — in CI / review* (11); the feed says *moved to* when an issue stops mirroring its PR; the pair counts as one open PR so no lead button | `TestStageTrackerLinkedPRProgressCollapsesAdoptionPair`, `TestStageTrackerAdoptionPairIsOneOpenPR`, `TestStageTrackerEventTextUnmirroredCoveredByPR` | @@ -123,10 +124,10 @@ old name). | `stageTrackerOrdinal` | chevron, hover, popover | — | `1st 2nd 3rd 4th … 11th 12th 13th 21st 22nd 23rd` | same | | `stageTrackerTrainStalledWord` + `STAGE_TRACKER_TRAIN_HEAD_STALL_WORD` | chevron label (stalled train), Merge queue popover | *Merge queue stalled · head #15425 waiting for a maintainer (untrusted author) 1h21m* — painted `--yellow` on the amber active chevron, so the row read as an **empty** chevron (#15529, #15530) | rider: *Merge queue · stalled — waiting on #15425 (needs maintainer merge) · 1h21m*; head row: *Merge queue · stalled — needs maintainer merge · 1h21m*; the why comes from `head_state` (`needs-human` → *needs maintainer merge* / *needs a human decision*, `ci` → *waiting for CI*, `soaking` → *soak overran*, `ready` → *waiting for a merge sweep*, `merging` → *merge call in flight*, `fixing` → *being fixed by its author*, `unknown` → *head not in this view*); an unmapped `merge_train.state` falls back to its humanised name + place (*Waiting for front · 3rd*), never `''`; `.ham-seg.active .ham-queue-stalled` inherits the chevron's text colour | `TestStageTrackerMergeTrainStateSlugsNeverLeak` (every state × stalled × head_state × place), `TestStageTrackerMergeTrainPayloadStates` | | `stageTrackerTrainQueueTip` | chevron hover | *Behind #15253 … Estimated turn: ~25m.* / *Front of the merge queue* | *2nd of 6 in the merge queue · behind #15253 · ETA ~25m.* / *1st of 6 in the merge queue · merges next · ETA ~4m.*; *· merge sweep running* lives here only (one label per chevron, #15416) | same | -| `stageTrackerTrainHeaderText` + `stageTrackerTrainIconHtml` | train header chip | `⛓ merge train · 2 PRs · front #15400` | 🚆 (inline-SVG railcar, hover *Merge queue*) `merge train · 2 PRs · 1st: #15400` | `TestStageTrackerMergeTrain` | +| `stageTrackerTrainHeaderText` + `stageTrackerTrainIconHtml` | train header chip | `⛓ merge train · 2 PRs · front #15400` | (inline-SVG merge sign, hover *Merge queue*) `merge train · 2 PRs · 1st: #15400` | `TestStageTrackerMergeTrain` | | `stageTrackerQueueMemberState` (`tracker-queue.js`) | Merge queue popover | *front of the queue* | *merges next* | `TestStageTrackerMergeQueuePopover` | | `stageTrackerAnchor` (`tracker-row-anchor.js`) | which column lights | a 1st-in-train head at 050/070 lit **CI / Review** | every train state lights **Merge queue** | `TestStageTrackerMergeTrainStatesLightMergeColumn` | -| `stageTrackerHeaderHtml` | column header | *Merge gate* | 🚆 *Merge queue* (same icon as the chip and the 080 chevron) | `TestStageTrackerHeader…` | +| `stageTrackerHeaderHtml` | column header | *Merge gate* | *Merge queue* led by the merge-sign icon (same icon as the chip and the 080 chevron) | `TestStageTrackerHeader…` | | Go: `prstage.MergeTrain.Sentence`, `stageTrackerMergeTrainFrontCaption`, `eta_basis` | gate reason, caption, hover | *front of the merge train (1st of 3)*, *Front of a merge train of N PRs* | *1st in the merge queue; merges next (1st of 3)*, *1st in a merge queue of N PRs* | `TestParseMergeTrainRejectsMalformed` | | "merge gate" in decision copy (`delegatedecision` glossary, ladder, dashboard decided/new/vocabulary) | glossary, ⋯ hints, PR comments | *the merge gate merges it once every check passes* | *the merge queue merges it …* | `TestStageTrackerDecisionGlossaryMirrorsGo` | diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 17f77ffa7a..40e5dcba92 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -77,7 +77,7 @@ Side stages share a column rather than adding columns: | 045 Needs human decision | Actionable on an issue. A pre-045 issue still wearing 085 is drawn here until reconciliation. | | 070 Fixing / 071 Needs author / 072 Returned to contributor | CI / Review: Hive repairs its own PR at 070; a human author acts at 071; a contributor agent gets its PR back at 072. `needs-rebase` explains a repair here, not at 050. | | 074 Adopted by hive | CI / Review while the Hive repairs adopted work; pending, green or red pushes remain 074 until the merge gate takes it. | -| 085 Needs human decision / 090 Ready for human merge | Merge queue on a PR. Read the decision or merge reason rather than assuming Hive will merge it. | +| 085 Needs human decision / 090 Ready for human merge | A human gate is a pill on the PR's real stage, not a stage of its own ([#17327](https://github.com/hivecommons/hive/issues/17327), [#17453](https://github.com/hivecommons/hive/issues/17453)). A 085 PR whose head is short of merge-ready — checks running, red or unreported; the review verdict pending or asking for a person — lights **CI / Review** (the CI track while checks run or are not green, the Review track while its verdict is what waits), with an amber marker on the lit track and the one **👤 Needs human · …** gate pill carrying the question and the verbs (see *Settling a human gate*); PR in progress is passed, Merge queue empty. Only a 085 PR that is merge-ready (review approved, CI green on this head), queued or merging, and every 090, sits in the **Merge queue** column — read the decision or merge reason rather than assuming Hive will merge it. A 090 held by a sentinel alert or a `hold` label keeps its own column word with the amber marker; the gate pill names the reason (`sentinel`, `hold`) and Hive never merges it while the gate stands ([#17470](https://github.com/hivecommons/hive/issues/17470)). | | 060 / 080 / 095 / 100 | Separate gate states; use the [merge-gate reference](#merge-queue-pills--legend) below for exact words and countdowns. | The author legend is a blue Hive hexagon, purple contributor-agent robot or teal human silhouette. The kind is `author/*`, inferred from the snapshot if its label is absent; the link tooltip names the login. On Claimed, the actor is the claim holder; on PR in progress and Returned to contributor it is the author. Hive owns review, adoption and auto-merge work; a human owns a human decision or manual merge. The payload's `stage_actor` is the authoritative actor (see [Who is on it](#who-is-on-it-actor-icons)). @@ -149,7 +149,7 @@ An Open issue waiting on a maintainer's triage reads **Triage needed · since 28 At most one health chip sits over the strip's cap, with `+N` for the rest: `stalled`, `regressed`, `hold`, `needs-human`, `needs-decision` (“needs human decision”), `needs-triage` (“triage needed”), `needs-rebase`, `blocked` or `draft`. At 015 the chevron already names triage; before claim, a lingering `needs-triage` can be a chip (010/017/045). At 020+ it is stale and omitted from chip/stage text: `stale_labels` supplies a muted *Stale label* tooltip until the sweep removes it ([#14586](https://github.com/hivecommons/hive/issues/14586)). -A genuine backward hop sets `regressed`; the first forward hop clears it. Lapsed claims 020→010, 030↔020 flicker and 040→010 after a partial merge are not regressions. A regression parked on a person is red. Otherwise it is a muted dashed **stage ↓**, yields to other modifiers and does not enter **Needs attention**: “the hive is handling it — no action needed; clears on the next forward step.” See [The regressed marker](../labels-and-control-signals/stage-labels.md#the-regressed-marker-when-it-is-set-when-it-clears). +A genuine backward hop sets `regressed`; the first forward hop clears it. Lapsed claims 020→010, 030↔020 flicker and 040→010 after a partial merge are not regressions. A regression parked on a person is red. Otherwise it is a muted dashed **stage reset** — **stage reset by push** when a new head caused the fall ([#17335](https://github.com/hivecommons/hive/issues/17335)) — yields to other modifiers and does not enter **Needs attention**: “the hive is handling it — no action needed; clears on the next forward step.” See [The regressed marker](../labels-and-control-signals/stage-labels.md#the-regressed-marker-when-it-is-set-when-it-clears). The reason, actor, nudges, repository, flags and recent stage hops live on the `#N` tooltip (the PR link for a nested row). Titles wrap before their column edges and show full text on hover. Hairlines and whole-row hover keep the chip and age attached to the right row ([#14640](https://github.com/hivecommons/hive/issues/14640)). Passed/upcoming chevrons, kind/author icons, chips and `since` have no separate hover text. @@ -241,21 +241,36 @@ Durations, the flash timing (`--ham-move-flash-ms`, `--ham-move-flash-gap-ms`, ` #### Sentinel alert -A pull request the suspicious-activity sentinel flagged — it wears the `sentinel-alert` label (`sentinel.label`), or the review evidence bundle for its current head records sentinel findings — carries `sentinel_alert: true` in the tracker payload (with `sentinel_findings` and a short `sentinel_reason` when the bundle has them); a webhook label change flips it live. In the **Needs human decision** lane the lit chevron's own words read **Sentinel alert · needs human** (danger-tinted, the same wording in the cell's `title` and `aria-label`, and in the compact caption), so a maintainer reads the security implication before the stage mechanics; in every other lane at or past the merge gate (080, 090, 095, 100) the row shows a compact danger-tinted `sentinel` chip ahead of `needs rebase` / `regressed` / `stalled`; before the gate the chip is held back with the other merge-gate pills (see *Pills before the merge gate*) while `sentinel_alert` stays truthful in the payload. +A pull request the suspicious-activity sentinel flagged — it wears the `sentinel-alert` label (`sentinel.label`), or the review evidence bundle for its current head records sentinel findings — carries `sentinel_alert: true` in the tracker payload (with `sentinel_findings` and a short `sentinel_reason` when the bundle has them); a webhook label change flips it live. **A sentinel alert is a gate, not a stage** (owner decision 2026-11-08, [#17327](https://github.com/hivecommons/hive/issues/17327)): the column is the PR's real progress (CI, Review, or Merge queue once checks are green and the verdict approves) and the alert rides along as a pill. The lit chevron never names the alert ([#17470](https://github.com/hivecommons/hive/issues/17470) — *Held · sentinel · confirm intent* and *Sentinel alert · needs human* are gone): a green, reviewed, flagged PR stands at `090` in the **Merge queue** column with its own column word and the amber `ham-human-gated` marker, never *Queued for merge*; a PR still running CI lights CI the same way. The alert is a reason of the row's one **👤 Needs human · sentinel** gate pill, whose hover is the sentinel reason and whose verbs are **Confirm safe** and **Let hive decide** (see *Settling a human gate*); a `hold` / `do-not-merge*` label is the `hold` reason of the same pill, with the holder and reason from the hold data. Where the gate pill does not render (a draft, a merged head) the row shows the compact danger-tinted `sentinel` chip ahead of `needs rebase` / `regressed` / `stalled` instead; before the merge gate the chip is held back with the other merge-gate pills (see *Pills before the merge gate*) while `sentinel_alert` stays truthful in the payload. -The tooltip reads "Sentinel flagged security-relevant changes at ``: ``" (a generic description stands in when the bundle has no reason). An issue carried by one flagged PR shows the lane text too, and a nested PR sub-row shows its own. The *Decide…* dialogs for a flagged PR open with a ⚠ line per flagged PR naming the sentinel reason, and *Approve* is styled as a dangerous action. +The tooltip reads "Sentinel flagged security-relevant changes at ``: ``" (a generic description stands in when the bundle has no reason). An issue carried by one flagged PR carries the gate pill too, and a nested PR sub-row carries its own. The *Decide…* dialogs for a flagged PR open with a ⚠ line per flagged PR naming the sentinel reason, and *Approve* is styled as a dangerous action. The payload also carries `sentinel_details`: one entry per finding with its `rule` (`sensitive_path`, `permission_escalation`, `ci_gate_weakening`, …), `summary`, the flagged `paths` (sorted, at most 10 per finding) and `more_paths` for any cut. The *Let hive decide* dialog's ▼ Details and the ⚠ chip tooltip list them under the sentinel line — `· sensitive_path: .github/workflows/release.yml (+N more)` — so the person can see *which* files tripped the sentinel, not just how many; `/api/sentinel` serves the same `findings` per row, and the hive's "reviewed, intended" decision comment on a trusted author's flagged PR names the same files after the reason. The findings come from the head's review evidence bundle or the sweep's own record; nothing is re-fetched from GitHub. -A person's *Approve* through that dialog **is** the human review the alert asked for: it removes the `sentinel-alert` label when present and records a `sentinel_acknowledged` human action keyed to the head in the review evidence bundle, so a bundle-only alert (findings but no label — hivecommons/crux#30) clears too; the payload then reads `sentinel_alert: false` with `sentinel_reason` suffixed `— acknowledged by @login`, the findings stay on record, and a new head starts over. +**Confirm safe** on the gate pill is the alert's own answer: it posts the person's confirmation as a comment (``, their words after it) and then removes the `sentinel-alert` label (`POST …/items/{number}/sentinel-confirm`, audited as `repo_item_sentinel_confirm`). A person's *Approve* through the decision dialog **is** also the human review the alert asked for: it removes the `sentinel-alert` label when present and records a `sentinel_acknowledged` human action keyed to the head in the review evidence bundle, so a bundle-only alert (findings but no label — hivecommons/crux#30) clears too; the payload then reads `sentinel_alert: false` with `sentinel_reason` suffixed `— acknowledged by @login`, the findings stay on record, and a new head starts over. -The delegated *Let hive decide* path never clears it. Hovering the lit chevron of a parked row names the parking stage itself (`Needs human decision`), not the 080 column it rides on; `Next move` follows the real stage (human at 085, hive at 080). Lane text and chip update in place on refresh (keyed reconcile, no flash). +The delegated *Let hive decide* path never clears it. Hovering the lit chevron of a parked row names the parking stage itself (`Needs human decision`) when it sits in the Merge queue column, and *· needs a person: * on the lit CI / Review track when the head is not merge-ready ([#17453](https://github.com/hivecommons/hive/issues/17453)); `Next move` follows the real stage (human at 085 and at a held 090, hive at 080). A held row's stage never advances the merge: the lanes and the dashboard's one-click shortcuts check the gate itself, so a parked PR never merges unattended. The gate pill and the chip update in place on refresh (keyed reconcile, no flash). + +#### Settling a human gate + +Every row a person must settle carries exactly **one** control for it ([#17470](https://github.com/hivecommons/hive/issues/17470); owner, 2026-11-10: "I don't see a consistent way to settle each of these using the UI"): a segmented pill, `[👤 Needs human · ] [verb] [verb] [verb] [… more]`, in the row's pill strip. The status segment names *why* — `review`, `decision`, `sentinel`, `hold`, comma-separated when they stack — and carries the reviewer's question or the sentinel rule as its hover (and, when the row carries a decision, the decision popover on click; the question also stays in the expander line). The verbs are fixed per reason, so the same reason always offers the same answers; stacked reasons union their verbs in reason order, de-duplicated, at most three visible with the rest behind a `…` menu (the same popover pattern as the row's ⋯ menu); on the stacked head (≤ 1100px) and the phone card the status folds to its icon and only the first verb stays inline, the rest behind the `…`, so the pill is one line and leaves the title its room. "Needs human" is never a chevron word: the lit chevron is the row's real stage with the amber `ham-human-gated` outline as the bar's only cue. The `sentinel`, `hold`, `needs-human` and `needs-decision` chips step aside when the pill renders; `↻ N` retry and the notes button stay separate. + +| Reason | Set by | Verbs | What gets posted | +|---|---|---|---| +| `review` | the review verdict requires a human on this head (`review_activity.state: human_decision`) | **Approve** · **Request changes…** · **Let hive decide** | Approve posts `/lgtm` + `/approve` on the current head (`…/items/{n}/decision`, `approve`); Request changes opens a modal whose text is posted as `/hive decision ` (`decision: direction`), the author agent pushes a new head; Let hive decide records a `/hive decision` under the hive's policy. | +| `decision` | `stage/085-needs-decision` on a PR, `045` on an issue, or a `needs-decision` / `needs-human` modifier | **Decide…** · **Approve as-is** (PR rows; *Approve* when stacked with `review`) · **Let hive decide** | Decide opens a modal with the question pre-filled; the answer is posted as `/hive decision `; Approve as-is is the GitHub approval of the head as it stands; Let hive decide as above. An issue with no PR offers Decide… and Let hive decide only. | +| `sentinel` | the `sentinel-alert` label or blocking findings on this head (`sentinel_alert`, not the trusted-author notice) | **Confirm safe** · **Let hive decide** | Confirm safe comments `` with the person's words and removes the sentinel label (`POST …/items/{n}/sentinel-confirm`, audited `repo_item_sentinel_confirm`); Let hive decide never clears the alert. | +| `hold` | a `hold` / `do-not-merge*` label (`hold`, `modifiers: hold`) | **Release hold** · **Let hive decide** | Release hold removes the label (`POST …/items/{n}/hold`, `{"held": false}`); Let hive decide as above. | + +Every verb runs `runRowAction` — the row menu's own path: the in-app confirm or prompt modal (never a native dialog), the result toast saying what was posted, the acting row — and the pill reads **settling…** (dashed outline, verbs disabled) until the next snapshot re-renders the row. A verb the viewer cannot run is greyed with the reason, never hidden. The review verdict's own question is not a second reason: a `requires_human` verdict on a 085 PR reads `review` alone; `review, sentinel` when the sentinel also flags it. + +A **secondary row of a shared PR** — an issue drawn under another listed issue's row because one PR closes both ([#17333](https://github.com/hivecommons/hive/issues/17333)) — never renders a gate pill or an amber chevron of its own; its *decision pending on #N* chip is a link that scrolls to and focuses the row that carries the gate. #### Unauthorized pill A pull request the hive cannot move because its GitHub App lacks a permission for the next step — it wears `hive:unauthorized` ([#14589](https://github.com/hivecommons/hive/issues/14589)); first case: approving held `action_required` workflow runs needs `actions: write` — carries the `unauthorized` modifier in the tracker payload, drawn in the far-right pill column exactly like `stalled` / `hold` / `draft` but muted (dashed, `--text-muted`), never red: it is nothing wrong, just a step only a person may take. -It counts under **Needs attention**. Before the merge gate only the held-workflow-runs step shows (see *Pills before the merge gate*). Its tooltip (payload `unauthorized`) names the missing permission and the human step; on the **Needs human decision** lane the lit chevron and the caption read **Awaiting human: approve workflow runs** (payload `unauthorized_step`, from the `unauthorized:` stage reason). The pill, label and payload fields clear themselves in the tick the step is no longer needed. +It counts under **Needs attention**. Before the merge gate only the held-workflow-runs step shows (see *Pills before the merge gate*). Its tooltip (payload `unauthorized`) names the missing permission and the human step; on the **Needs human decision** lane the caption reads **Awaiting human: approve workflow runs** (payload `unauthorized_step`, from the `unauthorized:` stage reason) and the row lights its real stage — the CI / Review track, amber-marked — with the `unauthorized` pill carrying the step ([#16524](https://github.com/hivecommons/hive/issues/16524), [#17453](https://github.com/hivecommons/hive/issues/17453)). The pill, label and payload fields clear themselves in the tick the step is no longer needed. #### Merge train @@ -275,10 +290,12 @@ A lone ticket draws no header: one owner (or one waiter) is the base-refresh loc holder, not a train, so its row comment carries the role and verification state and the header's count and front only appear once two recorded tickets share the base. A refreshed owner is the usual lone ticket — `update-branch` moves its head, so the -ticket reads *Recorded preparation owner · unverified · Head changed* until it merges -or is released; that is expected, not a dropped batch. +ticket reads *Recorded first for the base refresh · ticket issued for an earlier head · +re-checked on * until it merges or is released; that is expected, not a dropped +batch. The row never says *preparation* or *unverified* — those are the scheduler's +words, kept in the data ([#17335](https://github.com/hivecommons/hive/issues/17335)). -When several approved PRs to the same base touch the same files, the automerge lanes merge them one at a time ([#15117](https://github.com/hivecommons/hive/issues/15117)). The tracker renders every train contiguously, in merge order, with a thin left rail linking the rows and a header chip `🚆 merge train · 4 PRs · 1st: #15074` — the glyph is an inline-SVG railcar (14px, currentColor, hover *Merge queue*), the same icon the **Merge queue** column header and its chevrons wear; overlapping files are listed beside it. Pill wording per state is the PR's place in the queue (the owner's words — `front` and `queued-behind` appear nowhere a person reads): the head reads "Queued for merge · 1st of 4 · ~13m" (its own soak left plus the next pass); the others "Queued for merge · 2nd of 4 · ~4m", "Queued for merge · 3rd of 4", … (`1st 2nd 3rd 4th … 11th 12th 13th 21st`, always with the queue length, countdown to its turn); when the page draws more than one train each queue word ends with its train's tag — "Queued for merge · 1st of 2 · train main.go" (the first overlapping file's basename, else the head `#N`) — and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*, so two "1st"s on one page tell apart (one train → no tag); the header and every member row of a train share one rail accent (`.ham-train-k0…k3`, cycling in page order); once the front merged and the hive is rebasing a conflicting sibling, "Rebasing · attempt 1/2"; when the loop guard (`auto_merge.merge_train.max_rebase_attempts`) is spent, "Needs human decision · rebase failed twice" at stage/085 with the decision option "Rebase, then merge as maintainer". +When several approved PRs to the same base touch the same files, the automerge lanes merge them one at a time ([#15117](https://github.com/hivecommons/hive/issues/15117)). The tracker renders every train contiguously, in merge order, with a thin left rail linking the rows and a header chip `merge train · 4 PRs · 1st: #15074` led by the queue icon — the glyph is an inline-SVG merge sign — an up arrow with a lane curving in from the lower right, the W4-1 road sign (14px, currentColor, hover *Merge queue*; [#17459](https://github.com/hivecommons/hive/issues/17459)), the same icon the **Merge queue** column header and its chevrons wear; overlapping files are listed beside it. Pill wording per state is the PR's place in the queue (the owner's words — `front` and `queued-behind` appear nowhere a person reads): the head reads "Queued for merge · 1st of 4 · ~13m" (its own soak left plus the next pass); the others "Queued for merge · 2nd of 4 · ~4m", "Queued for merge · 3rd of 4", … (`1st 2nd 3rd 4th … 11th 12th 13th 21st`, always with the queue length, countdown to its turn); when the page draws more than one train each queue word ends with its train's tag — "Queued for merge · 1st of 2 · train main.go" (the first overlapping file's basename, else the head `#N`) — and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*, so two "1st"s on one page tell apart (one train → no tag); the header and every member row of a train share one rail accent (`.ham-train-k0…k3`, cycling in page order); once the front merged and the hive is rebasing a conflicting sibling, "Rebasing · attempt 1/2"; when the loop guard (`auto_merge.merge_train.max_rebase_attempts`) is spent, "Needs human decision · rebase failed twice" at stage/085 with the decision option "Rebase, then merge as maintainer". The tooltip lists the PRs ahead and the overlapping files. Waiting siblings are never red, never `needs human`; a `needs-rebase` label on one is reported under `stale_labels`, the train repairs it. Each item carries `merge_gate.state` (`queued-behind` / `rebasing` / `rebase-exhausted` / `front`, with an honest `reason` such as `behind #15074 in merge train (3rd of 4, overlapping files: stage_tracker.go, index.html)`) and `merge_train{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, members}`; the id is `#` and `members` is the whole roster in merge order. @@ -292,10 +309,10 @@ The tooltip lists the PRs ahead and the overlapping files. Waiting siblings are **Queue position, countdown, stall** ([#15395](https://github.com/hivecommons/hive/issues/15395)). The queued chip is its place in the queue and nothing else — **Queued for merge · 2nd of 6 · ~4m** — so it reads the same whether or not a merge sweep is evaluating it: the sweep is the spinning ⬡ glyph and a *Checking now…* line in the hover, never a change of words (one label per chevron), and no state slug (`queued-behind`, `front`) ever reaches the page. The hover is the place sentence — *2nd of 6 in the merge queue · behind #15253 (soaking, 12m left) · ETA ~25m (2 ahead · head soaking 12m · next pass in 40s). Hive merges one at a time, in order.*; the head's reads *1st of 6 in the merge queue · merges next · ETA ~13m.* — or, when the head is on a person or on CI, the blocker instead of a clock: *… behind #15253 (waiting for a maintainer (untrusted author)) · no estimate until #15253 moves.* Every train state — the 1st included — lights the **Merge queue** column, whatever numeric stage the lane holds the head at (the train's facts are mirrored onto a head still at 050/060; hive's own #15400 once lit CI / Review beside its 2nd-place sibling) — a head under repair is no member (below) and lights CI / Review. The server adds to each member's `merge_train`: `length`, `head_number`, `head_state` (`needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown`), `head_reason` (plain words), `head_since`, `eta_s`, `eta_at`, `eta_basis`, `late`, `stalled`, `stalled_s`. -**One PR per issue** ([#15395](https://github.com/hivecommons/hive/issues/15395)). Two open PRs declaring the same `Fixes #N` never both ride the queue (hive's own #15402 and #15407, both for #15396, once sat side by side as "waiting its turn"). Before the trains are grouped the sweep keeps one PR per closing issue — a green head (not conflicting, not blocked on a red required check) beats a red one; among equals the earlier-opened wins — and holds the other out of every train with the stage reason `merge-train:duplicate-of#:/0:0/0:`. The held row's gate reads `duplicate-of:` (`merge_gate.duplicate_of`, `merge_gate.duplicate_issue`), its chip **Duplicate of #15402 · needs a pick** with no clock, it carries no `merge_train`, and it wears `needs-decision` so both PRs sit under their issue with the hold visible. *Let hive decide* on either row takes the existing supersede path (rule `one-pr-per-issue`): on the held PR it closes it as superseded by the kept one with a credit comment, through the same write gate as every delegate close; on the kept PR it releases it and names the duplicate the queue holds (or, if the kept PR has since gone red, only recommends the fix — the queue re-picks on its next pass, so an earlier red PR yields to a later green one). +**One PR per issue** ([#15395](https://github.com/hivecommons/hive/issues/15395)). Two open PRs declaring the same `Fixes #N` never both ride the queue (hive's own #15402 and #15407, both for #15396, once sat side by side as "waiting its turn"). Before the trains are grouped the sweep keeps one PR per closing issue, judging heads at the merge gate only ([#17439](https://github.com/hivecommons/hive/issues/17439)): a same-issue PR whose CI is still running or whose review is outstanding carries no hold and no `needs-decision` — its row reads CI / Review like any other — and is held at the merge point if it gets there behind the issue's kept PR. The first PR at the merge point keeps the issue; among several already at the gate a green head (not conflicting) beats a conflicting one and then the earlier-opened wins; the pick then stands until the kept PR closes or is blocked for good, so a check that goes red mid-run never flips it. The other PR, once at the gate, is held out of every train with the stage reason `merge-train:duplicate-of#:/0:0/0:`. The held row's gate reads `duplicate-of:` (`merge_gate.duplicate_of`, `merge_gate.duplicate_issue`), its chip **Duplicate of #15402 · needs a pick** with no clock, it carries no `merge_train`, and it wears `needs-decision` so both PRs sit under their issue with the hold visible. *Let hive decide* on either row takes the existing supersede path (rule `one-pr-per-issue`): on the held PR it closes it as superseded by the kept one with a credit comment, through the same write gate as every delegate close; on the kept PR it releases it and names the duplicate the queue holds (or, if the kept PR has since gone red, only recommends the fix — the queue keeps its pick until the kept PR closes or is blocked for good). - **Countdown to auto-merge.** `eta_s` is the member's own remaining soak, plus — for each PR ahead — its remaining soak or, with no clock of its own, one sweep (the lanes' floor cadence), plus the wait for the next sweep tick; `eta_basis` is the short reading ("2 ahead · head soaking 12m · next pass in 40s"). The chip's `· ~4m` counts down in place from `eta_at` on the same tick as the soak clock, and `eta_at` is anchored server-side to the member's first estimate at its position (re-anchored only when a fresh estimate runs more than a sweep longer), so a poll re-render never resets it. Past the estimate it reads *any moment now*; past twice the first estimate `late` is set and the chip reads *running late* with the estimate kept in the hover. Always a `~`: an estimate, not a promise. A head on a person, on CI or being fixed — or a member that is itself a person's — carries no estimate and the blocker instead. -- **Merge queue popover.** The sticky bar's **🚆 Merge queue N** chip (hidden with no train) opens a popover listing every train in merge order — ordinal, #, title, state in words, ETA — with the head's blocker on the front row; same pattern as the **Merged** popover (click outside / Escape closes). +- **Merge queue popover.** The sticky bar's **Merge queue N** chip (led by the merge-sign icon) (hidden with no train) opens a popover listing every train in merge order — ordinal, #, title, state in words, ETA — with the head's blocker on the front row; same pattern as the **Merged** popover (click outside / Escape closes). - **Who rides.** A PR GitHub reports conflicting (`mergeable: CONFLICTING` / `DIRTY`) on its own, or one at **072 Returned to contributor** (by label or by the hive's stage record), is neither a member nor counted in the queue's length and draws no train idle comment — hive's own #15307 once read `queued-behind#15424:4/6` while conflicting at 072. A conflicting PR rides only while the train itself is repairing it (its rebase was requested behind a merged head and the loop guard still has attempts). - **Stall warning.** Once the head has sat in one stage longer than `governor.merge_train_stall_warn_s` (default 3600) and is not merging — a soaking head counts only once its own clock has overrun — every member's chip turns to **Merge queue · stalled — waiting on #15253 (waiting for CI) · 3h** (the head's own row: **Merge queue · stalled — waiting for CI · 3h**; an untrusted-author head reads *needs maintainer merge*), the popover marks the train, and the activity log records one `merge train stalled` line per train per hour. @@ -314,7 +331,7 @@ Issues on their own stages (Open, 010, 020, 045) keep every pill: a `needs-human | `hold` | actionable now | always, whether set by a person or Hive; release rules still depend on provenance | | `draft` | actionable now | always (the author's move) | | `stalled` | actionable now | always | -| `regressed` | actionable now | always; muted `stage ↓` unless the row is parked on a person (see above) | +| `regressed` | actionable now | always; muted `stage reset` (`stage reset by push` after a new head) unless the row is parked on a person (see above) | | `needs-rebase`, `blocked`, `triage needed`, `possible dupe` | actionable now | always | | `unauthorized` — `unauthorized:approve-workflow-runs` | actionable now | always — the carve-out: held workflow runs mean CI cannot even start, and waiting for the gate would waste the whole CI / review cycle (rationguard#397 at 072) | | `unauthorized` — any other step (merge, branch update, no step named) | merge gate | PR at stage/080 or later | @@ -327,7 +344,7 @@ Issues on their own stages (Open, 010, 020, 045) keep every pill: a `needs-human `stage/071-needs-author` is a person's PR: a human-authored pull request sent back by a maintainer's CHANGES_REQUESTED review or by the review swarm. The same verdict on a clanker-authored PR (`author/clanker`, or an author resolved to a contributor's hive agent) routes to `stage/072-returned-to-contributor`, whichever lane carried it. The actor is the owning contributor, the caption reads `Returned to @thatguywob's hive — @clubanderson requested changes`, and the normal contributor nudge goes to that hive ([hivecommons/hive#15159](https://github.com/hivecommons/hive/pull/15159): a human's out-of-cycle review on a clanker PR parked it at 071 under a maintainer's name). -The 071/072 chevron names the routing — `Needs @sam`, `Returned to @thatguywob's hive` — and a sentinel finding on such a row is a ` · sentinel` suffix on that word (the chip folds into it, the tooltip carries the finding). `Sentinel alert · needs human` is only the chevron word when the maintainer's review is still outstanding (085). A trusted human's CHANGES_REQUESTED review on the current head *is* the human those parks (sentinel alert, `hold`, workflow-path) were waiting for: the PR routes to 071/072 and the sentinel pass does not re-assert 085 until a new head re-arms the alert. +The 071/072 chevron names the routing — `Needs @sam`, `Returned to @thatguywob's hive` — and a sentinel finding on such a row is the `sentinel` reason of the gate pill beside it (the chip folds into the pill, its hover carries the finding); the chevron word never names it. A trusted human's CHANGES_REQUESTED review on the current head *is* the human those parks (sentinel alert, `hold`, workflow-path) were waiting for: the PR routes to 071/072 and the sentinel pass does not re-assert 085 until a new head re-arms the alert. A return placed by hand counts too: when a trusted maintainer swaps `stage/085` for `stage/071`/`stage/072` on the PR, the reconciler reads the label event once per head, records it as that maintainer's change request against the head, and keeps the stage. The hive's own label events and untrusted actors are not honoured. @@ -447,7 +464,7 @@ E.g. `At Merge queue — waiting on CI.` / `You chose Approve · 15:55 (5 min ag #### Legend — the three cues a row may carry -The *state pill* says where the item is and what it is waiting on (`hold`, `needs human`, `stage ↓` …). The *working* cue on the lit chevron says Hive is doing something in that stage now; its tooltip explains the work. The *decision badge* (history mark with count) says a person acted here and what followed. These are separate signals: a recorded decision does not mean the requested effect happened. +The *state pill* says where the item is and what it is waiting on (`hold`, `needs human`, `stage reset` …). The *working* cue on the lit chevron says Hive is doing something in that stage now; its tooltip explains the work. The *decision badge* (history mark with count) says a person acted here and what followed. These are separate signals: a recorded decision does not mean the requested effect happened. Plain words throughout — working / waiting on X / set back by Y / merged — nothing else blinks. @@ -455,15 +472,30 @@ Plain words throughout — working / waiting on X / set back by Y / merged — n An *active* chevron is filled amber and carries words; an inactive one is its icon alone (CI / Review: the ring, green when the last run on this head passed, red when it failed, neutral when not yet run), with the counts in its tooltip. On every strip: -1. **1 ≤ active ≤ 2.** At least one chevron is active — the column where the item is or where it is stuck. -2. **CI and Review resolve first.** A track is active only while it genuinely runs on the current head (a check-run in progress or queued, a ring not yet full; a reviewer running or queued). If either runs, the PR is waiting on it: the stage chevron (PR in progress, Merge queue …) renders settled-current — filled but still, icon only, its words in the tooltip — and nothing else is active. -3. **CI + Review is the only pair.** Two chevrons are active together only when both tracks run at once; every other combination is exactly one active chevron. The stage chevron is the ≥ 1 fallback: active only when no track is in motion. -4. **The PR in progress chevron speaks the PR's lifecycle** — draft, pushed, rebasing, *Unassigned · next: scanner*, *Waiting for @author · fix owed* — never a CI or review verdict. *CI failing*, *CI 4/11 · 1 failing* and *changes requested* are the CI and Review chevrons' words; the PR in progress tooltip keeps the red reason as detail. -5. **The CI and Review tooltips state what the track waits on — never "activity unknown".** With no verdict and no reviewer in flight the spoke derives the Review statement from what it already knows, in this order: the PR is merged or closed (*Review · n/a (closed)*), it is a draft (*Review · draft, not requested*), CI on the head has not finished (*Review · waiting for CI*), CI is done and nobody started (*Review · not started · hive reviewer next*, or *· needs reviewer* when the repo has no hive reviewer lane or the review swarm is off). A 050 row reads *Review 0/5 · in progress* only on a hive that dispatches reviewers; with the swarm off it falls through to these statements. A settled verdict explains itself — *Changes requested by the hive reviewer: 1 perspective posted findings … · 12m ago · quality ✓ · security ✗: token logged* — and stays known as its observation ages. The one no-data wording, *Review · no data for head f269349 yet · refreshing* (CI: *CI · no checks observed for head … yet · refreshing*), appears only when the spoke has fetched nothing for the head, and names the next step. +1. **Exactly one lit stage per row.** One chevron is active — the column where the item is or where it is stuck; later stages are shown dim, with a muted queued note when they are next ([#17335](https://github.com/hivecommons/hive/issues/17335): a push during review lit *CI 7/11 · 4 running* and *Review 5/5 · adjudicating* amber together). +2. **CI and Review resolve first.** A track is active only while it genuinely runs on the current head (a check-run in progress or queued, a ring not yet full; a reviewer running or queued). The CI count, its pending names and its motion cover tests only: Prow's `tide` merge-gate status (pending on every PR until it carries lgtm/approved and all presubmits are green), `enforce-guardrails` and the DCO sign-off context (`dco` / `DCO`) are merge gates, not checks, so a PR whose only pending context is `tide` reads *CI 18/18* and lights Review or the Merge queue — never *CI 18/19 · 'tide' running* (`github.IsMergeGateContext`; merge eligibility still enforces the gates). If either runs, the PR is waiting on it: the stage chevron (PR in progress, Merge queue …) renders settled-current — filled but still, icon only, its words in the tooltip — and nothing else is active. Settled-current is always the neutral fill: the Open column's draft, blocked, New and stale tints and the held-gate amber never repaint it, so the running track is the row's only coloured chevron ([#17461](https://github.com/hivecommons/hive/issues/17461): a draft PR with no stage yet read as a slate Open beside amber CI). + A CI word is motion only when GitHub reports it: a check run whose status is not `completed`, or a non-merge-gate commit status still `pending`. A required check with no run on the head is settled (*hasn't reported*), never *running*, however many of its neighbours are green; at `060 reviewed` with every reported check concluded, **Review** is the lit chevron and CI is its blocker only when red. A CI snapshot that still claims a check running or queued after `dashboard.stage_tracker.ci_activity_stale_m` (default 10 minutes) is re-listed from GitHub on the next tracker build regardless of the batch cache, ETag or stage, so a listing taken while checks were starting cannot stay lit for hours ([#17508](https://github.com/hivecommons/hive/issues/17508): *CI 2/3 · running* eight hours after every check had passed). +3. **CI leads Review.** When both tracks would light at once — CI running while the review is queued, in progress or being re-adjudicated — CI is the lit chevron and Review is dim with a small note (*re-review queued* after a push, *review in progress*, *review queued*); its words stay in the tooltip, ending *… behind CI*. The stage chevron is the fallback: active only when no track is in motion. +4. **The PR in progress chevron speaks the PR's lifecycle** — draft, pushed, rebasing, *Unassigned · next: scanner*, *Deferred · waiting on #N*, *Waiting for @author · fix owed* — never a CI or review verdict. *CI failing*, *CI 4/11 · 1 failing* and *changes requested* are the CI and Review chevrons' words; the PR in progress tooltip keeps the red reason as detail. +5. **A human gate is a pill, not a stage.** A PR parked at 085 for a person — a reviewer's question, a permission only a maintainer holds, a rerun to approve — with checks running, red or unreported, or its review verdict pending, is drawn at its real stage: CI (with motion while checks run) or Review is the one lit chevron, wearing an amber marker (`ham-human-gated`), and the ask is the one **👤 Needs human · …** gate pill in the row's pill strip (the question in its hover, the decision popover on click, the verbs beside it — see *Settling a human gate*); the lit track's tooltip ends *· needs a person: *. It never lights a *Needs human · decision* chevron in the PR in progress column while CI and Review spin dim ([#17453](https://github.com/hivecommons/hive/issues/17453): #17442 did, with CI 3/9 running; #17416 read *Needs human · review* the same way). Only a merge-ready, queued or merging 085 is a Merge queue matter. +6. **The CI and Review tooltips state what the track waits on — never "activity unknown".** With no verdict and no reviewer in flight the spoke derives the Review statement from what it already knows, in this order: the PR is merged or closed (*Review · n/a (closed)*), it is a draft (*Review · draft, not requested*), CI on the head has not finished (*Review · waiting for CI*), CI is done and nobody started (*Review · not started · hive reviewer next*, or *· needs reviewer* when the repo has no hive reviewer lane or the review swarm is off). A 050 row reads *Review 0/5 · in progress* only on a hive that dispatches reviewers; with the swarm off it falls through to these statements. A settled verdict explains itself — *Changes requested by the hive reviewer: 1 perspective posted findings … · 12m ago · quality ✓ · security ✗: token logged* — and stays known as its observation ages. The one no-data wording, *Review · no data for head f269349 yet · refreshing* (CI: *CI · no checks observed for head … yet · refreshing*), appears only when the spoke has fetched nothing for the head, and names the next step. + +On a red PR (CI failing or changes requested on the current head, or a 07x fix stage) the PR in progress word comes from pickup evidence: + +| Word | State | Fill | When | +|---|---|---|---| +| *Remediating · scanner · 4m* | `remediating` | amber, pulsing | A hive fix kick, a clanker claim or a working agent's action on the PR landed after the red signal. | +| *Fix pushed f269349 · re-review pending* | `fix_pushed` | done-style, green word | A new head landed after the red signal; CI and the re-review on it are the open work. | +| *Deferred · waiting on #17345 +1* | `deferred` | amber, still | A hive agent deferred this head ([#17347](https://github.com/hivecommons/hive/issues/17347)): its comment on the PR said *Deferring …* / *Deferred …* / *Waiting on #N*. The word names the first successor issue or PR it named (`+N` for more; *Deferred · by scanner* when it named none); the tooltip leads with the deferral's own reason (its first sentence), then every successor and the first one's link. When the deferral says a maintainer may close the PR, the row's lead action is `[Close now]`. | +| *Waiting on shared CI · #17463* | `deferred` | amber, still | The deferral waits on a fleet-wide `[shared-ci]` incident ([#17500](https://github.com/hivecommons/hive/issues/17500)): the agent's comment carried the `` marker and the relay recorded the incident number (`incident` pair; `deferral.incident` / `deferral.incident_url` in the payload). The word links the incident issue; the tooltip reads *`mutation` is failing fleet-wide; tracked in #17463. Lifts automatically when that issue closes.* It never reads *Deferred · by scanner*: the incident, not the agent, is the why. | +| *Waiting for @author · fix owed* | `waiting_owner` | amber, still | The author owes the next head (071/072). | +| *Unassigned · next: scanner* | `unassigned` | amber-red, still | Nobody picked it up and the hive did not defer it. | + +The relay records a deferral as an `agent_pr_deferred` audit entry bound to the PR's head at the time. A shared-CI deferral lifts without a person: once the incident issue closes, the shared-CI rerun sweep re-runs the PR's red workflow run (a run cut off by `timeout-minutes` is recorded as `cancelled` and counts as red), comments *Shared-CI incident #N closed — re-running ``* with the `` marker, and never repeats for that PR and incident; the fresh verdict then moves the row on. A fix kick, claim or push for the same head *after* the deferral returns the row to *Remediating* / *Fix pushed*; a new head clears the deferral, because the hive has to decide again. The deferring agent's own comment, or a later note on the PR, is never read as pickup. #### The row's lead action, inline -A row whose next move is yours does not hide its answer behind three dots. Beside the chips on the right of the header (and on a nested PR sub-row's own header), the row renders its **lead action** as a real `'; }", jsConstLine(t, html, "STAGE_TRACKER_MOD_PRIORITY"), + jsConstLine(t, html, "STAGE_TRACKER_HUMAN_MODS"), jsConstLine(t, html, "STAGE_TRACKER_MOD_TEXT"), jsConstLine(t, html, "STAGE_TRACKER_HANDLED_TEXT"), jsConstLine(t, html, "STAGE_TRACKER_DRAFT_TIP"), @@ -155,7 +156,10 @@ func TestStageTrackerHoldProvenanceJS(t *testing.T) { jsFunc(t, html, "stageTrackerDecisionOf"), jsFunc(t, html, "stageTrackerHoldPill"), jsFunc(t, html, "stageTrackerHoldTip"), + jsConstBlock(t, html, "STAGE_TRACKER_ICONS"), + jsFunc(t, html, "stageTrackerIcon"), jsFunc(t, html, "stageTrackerChipsHtml"), + stageTrackerManualMergeJS(t, html), }, "\n")+` const hold = { by: 'hive', source: 'reporter-trust', reason: 'reporter trust (issue #15017 by @Karibhou, contributor)', since: '2026-10-20T17:14:14Z', issue: 15017, reporter: 'Karibhou', association: 'contributor', pill: 'Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)' }; const decision = { question: 'The hive held this PR itself for reporter trust (issue #15017 by @Karibhou, contributor). Release the hold, or keep it?', asked_by: 'the hive', options: [ { action: 'release', label: 'Release hold', enabled: true } ] }; @@ -182,5 +186,28 @@ assert.strictEqual(stageTrackerHoldPill({ hold: null }), ''); assert.strictEqual(stageTrackerHoldTip({ hold: {} }, 0), ''); // Without the pill field the text is built from the parts. assert.strictEqual(stageTrackerHoldPill({ hold: { by: 'hive', reason: 'r' } }), 'Held by hive · r'); +// hivecommons/hive#17442 (#17453): a 085 PR with CI running and the review +// verdict pending lights its real stage, so the ask rides as the +// needs-decision pill — even on a payload that predates the server adding +// the modifier — and that pill opens the decision popover. +const ask = { question: 'Dependabot alerts need the security_events read permission. Grant it, or merge without the check?', asked_by: 'sec-check', options: [ { action: 'decide:approve', label: 'Approve', enabled: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true } ] }; +const running = { repo: 'hivecommons/hive', kind: 'pr', number: 17442, stage: 85, head: 'c0ffee1', modifiers: [], decision_needed: ask, + ci_activity: { head: 'c0ffee1', state: 'running', active: true, checks_passed: 3, checks_total: 9 }, + review_activity: { head: 'c0ffee1', state: 'human_decision', perspectives_done: 5, perspectives_total: 5 } }; +const rpill = stageTrackerChipsHtml(running); +assert.ok(rpill.includes('ham-mod-needs-decision') && rpill.includes('>needs human decision<'), rpill); +assert.ok(rpill.includes('ham-mod-ask') && rpill.includes('ham-mod-ico') && rpill.includes('needs human decision'), 'the ask pill wears the person icon with its words foldable: ' + rpill); +assert.ok(rpill.includes('ham-decision-trigger') && rpill.includes('data-ham-decision="hivecommons/hive/pr#17442"'), rpill); +assert.ok(!rpill.includes('+1'), 'one pill, not duplicated: ' + rpill); +// The server already carrying the modifier adds nothing twice. +const served = stageTrackerChipsHtml(Object.assign({}, running, { modifiers: ['needs-decision'] })); +assert.strictEqual((served.match(/ham-mod-needs-decision/g) || []).length, 1, served); +assert.ok(!served.includes('+1'), served); +// A pill that already names the person owed (unauthorized, hold) stands in: no needs-decision stacked behind it. +const gated = stageTrackerChipsHtml(Object.assign({}, running, { modifiers: ['unauthorized'] })); +assert.ok(!gated.includes('ham-mod-needs-decision') && !gated.includes('+1'), gated); +// A merge-ready 085 twin (approved + CI green) is the gate's: no invented pill. +const ready = stageTrackerChipsHtml(Object.assign({}, running, { ci_activity: { head: 'c0ffee1', state: 'passing' }, review_activity: { head: 'c0ffee1', state: 'approved' } })); +assert.ok(!ready.includes('ham-mod-needs-decision'), ready); `) } diff --git a/src/pkg/dashboard/stage_tracker_human_gate_test.go b/src/pkg/dashboard/stage_tracker_human_gate_test.go new file mode 100644 index 0000000000..53cec8f3a2 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_human_gate_test.go @@ -0,0 +1,292 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// stageTrackerHumanGateJS lifts the human-gate pill surface +// (tracker-human-gate.js) for every node harness that renders rows: the +// reason/verb tables and the pure helpers stageTrackerRowHtml composes. +func stageTrackerHumanGateJS(t *testing.T, html string) string { + t.Helper() + return strings.Join([]string{ + jsConstLine(t, html, "STAGE_TRACKER_GATE_MODS"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_WORD"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_SETTLING"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_VISIBLE"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_FOLD_QUERY"), + jsConstBlock(t, html, "STAGE_TRACKER_GATE_VERBS"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_ORDER"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_PR_ONLY"), + jsConstBlock(t, html, "STAGE_TRACKER_GATE_LABELS"), + jsConstLine(t, html, "STAGE_TRACKER_GATE_APPROVE_AS_IS"), + jsConstBlock(t, html, "STAGE_TRACKER_GATE_POSTS"), + jsFunc(t, html, "stageTrackerGateIsPR"), + jsFunc(t, html, "stageTrackerHumanGateReasons"), + jsFunc(t, html, "stageTrackerHumanGateVerbs"), + jsFunc(t, html, "stageTrackerHumanGateStatusText"), + jsFunc(t, html, "stageTrackerHumanGateTip"), + jsFunc(t, html, "stageTrackerHumanGateVerbState"), + jsFunc(t, html, "stageTrackerHumanGateVerbHtml"), + jsFunc(t, html, "stageTrackerHumanGateVisible"), + jsFunc(t, html, "stageTrackerHumanGateHtml"), + }, "\n") +} + +// TestStageTrackerHumanGateWiring pins the markup, CSS and action-path +// surface of the one human-gate control (hivecommons/hive#17470): the +// module is in the bundle, the chevron never wears a held/sentinel word, +// the CSS is token-only, and the verbs route through runRowAction. +func TestStageTrackerHumanGateWiring(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `function stageTrackerHumanGateReasons(item)`, + `function stageTrackerHumanGateHtml(item, shown, nowMs, subRows, opts)`, + `function stageTrackerHumanGateSettling(button)`, + `function stageTrackerWireHumanGate(el)`, + `const STAGE_TRACKER_GATE_WORD = 'Needs human';`, + `const STAGE_TRACKER_GATE_SETTLING = 'settling…';`, + `const STAGE_TRACKER_GATE_VISIBLE = 3;`, + `gateHere ? 'ham-human-gated' : ''`, + `.ham-human-gate {`, + `.ham-seg.active.ham-human-gated {`, + `.ham-human-gate.ham-gate-settling`, + `'gate:decide': 'Decide…'`, + `'gate:request-changes': 'Request changes…'`, + `'gate:confirm-sentinel': 'Confirm safe'`, + `/sentinel-confirm`, + `stageTrackerHumanGateSettling(b)`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing human-gate wiring %q", want) + } + } + for _, gone := range []string{ + `'Held · sentinel · confirm intent'`, + `'Held · hold'`, + `'Sentinel alert · needs human'`, + `heldGate ? 'ham-held' : ''`, + `.ham-seg.active.ham-held`, + `.ham-seg.active.ham-sentinel {`, + `function stageTrackerHeldWord(`, + `function stageTrackerSentinelAsSuffix(`, + } { + if strings.Contains(html, gone) { + t.Errorf("index.html still carries the chevron-word human gate %q", gone) + } + } + start := strings.Index(html, "/* ---- The human gate: one control per gated row") + if start < 0 { + t.Fatal("human-gate CSS/JS block not found") + } + cssStart := strings.Index(html, ".ham-human-gate {") + cssEnd := strings.Index(html[cssStart:], ".ham-gate-menu[hidden]") + if cssStart < 0 || cssEnd < 0 { + t.Fatal("human-gate CSS block not found") + } + if css := html[cssStart : cssStart+cssEnd]; strings.Contains(css, "#") || strings.Contains(css, "rgb(") || strings.Contains(css, "rgba(") { + t.Errorf("human-gate CSS must use tokens only, found a literal colour:\n%s", css) + } +} + +// TestStageTrackerHumanGateRows runs the row builders under node against the +// maintainer's screenshots (hivecommons/hive#17470, 2026-11-10): every gated +// row carries exactly ONE human-gate pill whose verbs follow its reasons, +// "Needs human" / "Held" never ride a chevron, the lit chevron is the real +// stage with the amber outline, and a secondary row of a shared PR renders +// no gate of its own — only the link to the row that does. +func TestStageTrackerHumanGateRows(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowsPreludeJS(t, html)+"\n"+ + jsFunc(t, html, "stageTrackerHumanAttentionOf")+"\n"+ + jsFunc(t, html, "stageTrackerNeedsHumanAsk")+"\n"+ + jsFunc(t, html, "stageTrackerHoldPill")+"\n"+ + jsFunc(t, html, "stageTrackerHoldTip")+"\n"+ + stageTrackerRowsFixtureJS+` +const seen = new Date(now - 60000).toISOString(); +const visible = (html) => strip(html).split('

')[0].replace(/]*class="config-tooltip[^"]*"[^>]*>[\s\S]*?<\/span>/g, '').replace(/<[^>]*>/g, ' '); +const gates = (html) => (html.match(/class="ham-human-gate"/g) || []).length; +const reasons = (html) => (/data-ham-gate-reasons="([^"]*)"/.exec(html) || [])[1] || ''; +const verbs = (html) => Array.from(html.matchAll(/data-ham-act="([^"]*)"[^>]*>([^<]*)<\/button>/g)).map(m => m[2]).filter((v, i, a) => a.indexOf(v) === i); +const gateWord = (html) => (/]*>[\s\S]*?([^<]*)<\/span>/.exec(html) || [])[1] || ''; +const gateTip = (html) => (/

]*>[\s\S]*?Confirm safe/.test(row), 'the fourth verb waits in the … menu template: ' + row); +assert.ok(!/ham-gate-menu-tpl[\s\S]*Let hive decide/.test(row), 'the menu holds only the folded verbs, not copies of the inline ones'); +assert.ok(!row.includes('ham-badge-sentinel') && !row.includes('ham-mod-needs-decision') && !row.includes('ham-lead-pill'), 'no sentinel chip, needs-decision pill or loose lead buttons beside the gate: ' + row); +assert.ok(row.includes('

') && row.includes('Needs human decision'), 'the expander line still names the decision'); + +// (b) crux#139 / PR #140: a green, reviewed PR at 090 with a sentinel +// alert and CI re-running. The lit chevron is CI; "Held · sentinel" is +// gone from the Merge queue chevron and is the gate's sentinel reason, +// which finally has its verb: Confirm safe. +const head140 = 'c0ffee1'; +const row140 = { repo: 'hivecommons/crux', number: 140, kind: 'pr', stage: 90, head: head140, author: 'hive[bot]', author_kind: 'hive', reason: 'a sentinel alert is open on this PR', + sentinel_alert: true, sentinel_reason: 'touches release signing (+2 more)', + ci_activity: { head: head140, state: 'running', active: true, caption: 'CI 18/19 · tide running', checks_passed: 18, checks_total: 19, source: 'checks', observed_at: seen }, + review_activity: { head: head140, state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }; +row = stageTrackerRowHtml(row140, stages, ctx); +assert.strictEqual(litChevrons(strip(row)), 1, 'one lit chevron: ' + strip(row)); +assert.ok(/

  • Merge queue'), 'the chevron reads its column: ' + strip(row)); + +// hold + decision stack: reasons in canonical order, verbs unioned. +const held = Object.assign({}, row17480, { number: 17490, modifiers: ['needs-decision', 'hold'], labels: ['do-not-merge/hold'], hold: { by: 'clubanderson', reason: 'wait for the release', since: seen } }); +row = stageTrackerRowHtml(held, stages, ctx); +assert.strictEqual(gates(row), 1, row); +assert.strictEqual(reasons(row), 'decision hold'); +assert.strictEqual(gateWord(row), 'Needs human · decision, hold'); +assert.deepStrictEqual(verbs(row), ['Decide…', 'Approve', 'Let hive decide', 'Release hold'], '"Approve as-is" only when the decision stands alone'); +assert.ok(gateTip(row).includes('Held by @clubanderson'), 'the hover names the holder: ' + gateTip(row)); +assert.ok(!row.includes('ham-mod-hold">hold'), 'the hold chip is folded into the gate'); + +// Verb sets per reason are fixed (the maintainer's "consistent way"). +const ids = (keys, item) => stageTrackerHumanGateVerbs(keys.map(key => ({ key, tip: '' })), item).map(v => v.label); +assert.deepStrictEqual(ids(['review']), ['Approve', 'Request changes…', 'Let hive decide']); +assert.deepStrictEqual(ids(['decision']), ['Decide…', 'Approve as-is', 'Let hive decide']); +assert.deepStrictEqual(ids(['sentinel']), ['Confirm safe', 'Let hive decide']); +assert.deepStrictEqual(ids(['hold']), ['Release hold', 'Let hive decide']); +assert.deepStrictEqual(ids(['review', 'decision', 'sentinel', 'hold']), ['Approve', 'Request changes…', 'Let hive decide', 'Decide…', 'Confirm safe', 'Release hold']); +// An issue with no PR has no head to approve or send back. +assert.deepStrictEqual(ids(['decision'], { kind: 'issue', stage: 45 }), ['Decide…', 'Let hive decide']); +assert.deepStrictEqual(ids(['hold'], { kind: 'issue', stage: 10 }), ['Release hold', 'Let hive decide']); + +// What is not a gate: a draft, a merged head, an informational notice. +assert.deepStrictEqual(stageTrackerHumanGateReasons(Object.assign({}, row140, { sentinel_notice: true })), []); +assert.deepStrictEqual(stageTrackerHumanGateReasons(Object.assign({}, row17480, { modifiers: ['needs-decision', 'draft'] })), []); +assert.deepStrictEqual(stageTrackerHumanGateReasons({ kind: 'pr', stage: 110, modifiers: ['merged', 'hold'] }), []); +assert.ok(!stageTrackerRowHtml({ repo: 'acme/console', number: 1, kind: 'pr', stage: 50 }, stages, ctx).includes('ham-human-gate'), 'a clean row has no gate'); + +// (d) secondary rows #17463 / #17476 of the shared PR #17480 (primary row +// #17451): no gate, no lit needs-human chevron of their own; the chip is +// the link to the primary row. +const prShared = Object.assign({}, row17480, { drawn_under: 17451, title: 'fix', url: 'https://x/17480' }); +const primary = { repo: 'hivecommons/hive', number: 17451, kind: 'issue', stage: 40, title: 'Issue 17451', linked_prs: [Object.assign({}, prShared, { also_closes: [{ number: 17463 }, { number: 17476 }] })] }; +const secondary = { repo: 'hivecommons/hive', number: 17463, kind: 'issue', stage: 40, title: 'Issue 17463', linked_prs: [prShared] }; +const shared = { parentOf: { 'hivecommons/hive/issue#17463': 'hivecommons/hive/issue#17451' }, children: { 'hivecommons/hive/issue#17451': ['hivecommons/hive/issue#17463'] }, prs: {}, collapsed: {} }; +const ctxS = Object.assign({}, ctx, { shared }); +const headRow = stageTrackerRowHtml(primary, stages, ctxS); +const childRow = stageTrackerRowHtml(secondary, stages, ctxS); +assert.strictEqual(gates(headRow), 1, 'the primary carries the gate: ' + headRow); +assert.strictEqual(gates(childRow), 0, 'the secondary carries none: ' + childRow); +assert.ok(!/Needs human/.test(visible(childRow)), 'no needs-human chevron on the secondary: ' + visible(childRow)); +assert.ok(!/ham-human-gated/.test(strip(childRow)), 'no amber outline on the secondary either: ' + strip(childRow)); +const link = /