diff --git a/.fossa.yml b/.fossa.yml new file mode 100644 index 0000000000..9092add37a --- /dev/null +++ b/.fossa.yml @@ -0,0 +1,37 @@ +# FOSSA CLI configuration for hivecommons/hive. +# Reference: https://github.com/fossas/fossa-cli/blob/master/docs/references/files/fossa-yml.md +version: 3 + +project: + # Stable project name in the CNCF FOSSA org (the action's `project:` input + # mirrors this so UI and CI agree). + name: hivecommons/hive + # Team NAME in the CNCF FOSSA org (team id 207492). Only applied when the + # project is first created; later changes must be made in the FOSSA UI. + team: Hive Commons + url: https://github.com/hivecommons/hive + link: https://hivecommons.dev + +# The Go workspace lives under src/ (src/go.work: root module + src/crux). +# FOSSA auto-discovers every manifest; list the shipped components explicitly +# so a future re-layout does not silently drop one. Shipped: the two Go +# modules, the spoke's runtime Node proxy (src/proxy) and the dashboard. +# Deliberately out of scope as repo tooling, not shipped code: +# discord/package.json and .github/scripts/package.json. +targets: + only: + - type: gomod + path: src + - type: gomod + path: src/crux + - type: npm + path: src/proxy + - type: npm + path: dashboard + +paths: + exclude: + - src/test + - src/examples + - examples + - docs diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 60f9e19c2f..8aa6ec59c7 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -71,3 +71,17 @@ updates: open-pull-requests-limit: 10 commit-message: prefix: "🌱 build(deps)" + + # discord/ runs on hosts as hive-discord.service; its lockfile pins + # discord.js's transitive undici, which has needed a hand bump. + - package-ecosystem: "npm" + directory: "/discord" + schedule: + interval: "weekly" + day: "monday" + labels: + - "dependencies" + - "no-changelog" + open-pull-requests-limit: 10 + commit-message: + prefix: "🌱 build(deps)" diff --git a/.github/scripts/hive-status-card.sh b/.github/scripts/hive-status-card.sh index d866cb4c6a..2f1ce5b31d 100755 --- a/.github/scripts/hive-status-card.sh +++ b/.github/scripts/hive-status-card.sh @@ -7,6 +7,15 @@ # hive-status-card.sh has REPO NUMBER SECTION exit 0 if the card has a matching section # hive-status-card.sh upsert REPO NUMBER MARKER BODY_FILE edit the comment carrying MARKER, else create it # +# Exit status of `has`: 0 = the card carries SECTION, 1 = it does not (or no +# card exists), 3 = the comments could not be read (the API call failed, or +# the response was not a JSON list of comment objects). A caller must treat 3 +# as a failure, never as absence: absence makes a workflow post, and posting +# on a read failure is exactly the duplicate this helper exists to prevent. +# `upsert` exits 3 for the same read failure without POSTing or PATCHing; +# a failed PATCH/POST exits non-zero with gh's status. On exit 3 a line +# starting `hive-status-card: error:` is written to stderr. +# # SECTION matches `` by exact KEY (e.g. # `issue-close`, `issue-partial:163`). Only when SECTION ends in `:` is it a # prefix (e.g. `issue-partial:` matches any `issue-partial:`), so @@ -28,24 +37,53 @@ set -euo pipefail GH_BIN="${GH_BIN:-gh}" HIVE_COMMENT_AUTHOR="${HIVE_COMMENT_AUTHOR:-github-actions[bot]}" +READ_ERROR=3 + +read_error() { + echo "hive-status-card: error: $*" >&2 + exit "$READ_ERROR" +} +# Prints the issue's comments as one validated flat JSON array, or exits +# READ_ERROR. Validation happens here so the matchers below never see a shape +# that would make Python exit 1 (which would read as "absent"). comments() { + local raw flat="1" if [ -n "${HIVE_COMMENTS_FILE:-}" ]; then - cat "$HIVE_COMMENTS_FILE" - return + raw=$(cat "$HIVE_COMMENTS_FILE") || read_error "cannot read HIVE_COMMENTS_FILE ${HIVE_COMMENTS_FILE}" + else + raw=$("$GH_BIN" api --paginate --slurp "repos/$1/issues/$2/comments?per_page=100") || + read_error "GET repos/$1/issues/$2/comments failed" + flat="0" fi - "$GH_BIN" api --paginate --slurp "repos/$1/issues/$2/comments?per_page=100" | - python3 -c 'import json,sys -out=[] -for page in json.load(sys.stdin): out.extend(page) -json.dump(out, sys.stdout)' + printf '%s' "$raw" | python3 -c 'import json,sys +flat = sys.argv[1] == "1" +try: + data = json.load(sys.stdin) +except ValueError as e: + sys.exit("response is not JSON: %s" % e) +if not isinstance(data, list): + sys.exit("expected a JSON list, got %s" % type(data).__name__) +pages = [data] if flat else data +out = [] +for page in pages: + if not isinstance(page, list): + sys.exit("expected a list of comment pages, got a %s page" % type(page).__name__) + out.extend(page) +for c in out: + if not isinstance(c, dict): + sys.exit("comment is a %s, not an object" % type(c).__name__) + if not isinstance(c.get("user") or {}, dict) or not isinstance(c.get("body") or "", str): + sys.exit("comment %r has a malformed user or body" % c.get("id")) +json.dump(out, sys.stdout)' "$flat" || read_error "comments for $1#$2 could not be parsed" } cmd="${1:-}"; repo="${2:-}"; number="${3:-}" case "$cmd" in has) section="${4:?section key required}" - comments "$repo" "$number" | python3 -c 'import json,re,sys + list=$(comments "$repo" "$number") + printf '%s' "$list" | python3 -c 'import json,re,sys want=sys.argv[1] section_re=re.compile(r"") def matches(key): @@ -64,7 +102,8 @@ sys.exit(1)' "$section" ;; upsert) marker="${4:?marker required}"; body_file="${5:?body file required}" - id=$(comments "$repo" "$number" | python3 -c 'import json,sys + list=$(comments "$repo" "$number") + id=$(printf '%s' "$list" | python3 -c 'import json,sys marker, author = sys.argv[1], sys.argv[2] for c in json.load(sys.stdin): if (c.get("user") or {}).get("login") != author: diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index 51bee2de8a..0c160eebe9 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 = '1a35ca4f9e5d1c8b7c50e8cc32efe996df5deeb0'; +const TRUSTED_SCRIPTS_TREE = 'b3108c5a9ebe25702b15654d9f37a7236f081830'; 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/test-hive-status-card.sh b/.github/scripts/test-hive-status-card.sh new file mode 100755 index 0000000000..b4425c0dd7 --- /dev/null +++ b/.github/scripts/test-hive-status-card.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# test-hive-status-card.sh — exercises .github/scripts/hive-status-card.sh with +# a gh stub so no network calls are made (#16363). +# +# Pins: exact section matching, ordinary behaviour when no card exists, that +# an API or parse failure is reported as an error (exit 3) and never as +# absence, and that `upsert` edits only the posting identity's marker comment. +set -u -o pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HELPER="${HERE}/hive-status-card.sh" +TMP_ROOT="${HERE}/../.test-tmp" +mkdir -p "$TMP_ROOT" +TMP="$(mktemp -d "$TMP_ROOT/hive-status-card.XXXXXX")" +trap 'rm -rf "$TMP"; rmdir "$TMP_ROOT" 2>/dev/null || true' EXIT + +fail=0 +pass() { echo " ok: $*"; } +bad() { echo " FAIL: $*"; fail=1; } + +CALL_LOG="$TMP/gh-calls.log" +: > "$CALL_LOG" + +GH_STUB="$TMP/gh" +cat > "$GH_STUB" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +method=GET +path="" +prev="" +for arg in "$@"; do + if [ "$prev" = "-X" ]; then method="$arg"; prev=""; continue; fi + if [ "$prev" = "-f" ] || [ "$prev" = "-F" ]; then prev=""; continue; fi + case "$arg" in + -X|-f|-F) prev="$arg" ;; + repos/*) path="$arg" ;; + esac +done +printf '%s %s\n' "$method" "$path" >> "$CALL_LOG" +if [ "$method" != "GET" ]; then + printf '{"id":1}\n' + exit 0 +fi +card='{"id":%s,"user":{"login":"hivecommons-hive[bot]","type":"Bot"},"body":"\\n**Hive status**\\n\\n\\nnote\\n"}' +case "$path" in + repos/o/r/issues/1/comments*) + printf "[[$card]]\n" 101 issue-close ;; + repos/o/r/issues/2/comments*) + printf "[[$card]]\n" 201 issue-partial:1638 ;; + repos/o/r/issues/3/comments*) + printf '[[{"id":301,"user":{"login":"someone","type":"User"},"body":"plain comment"}],[]]\n' ;; + repos/o/r/issues/4/comments*) + printf '[[{"id":401,"user":{"login":"someone","type":"User"},"body":"quoting:\\n\\n"}]]\n' ;; + repos/o/r/issues/5/comments*) + echo "HTTP 502: Bad Gateway" >&2 + exit 1 ;; + repos/o/r/issues/6/comments*) + printf 'rate limited\n' ;; + repos/o/r/issues/7/comments*) + printf '{"message":"Not Found"}\n' ;; + repos/o/r/issues/8/comments*) + printf '[[{"id":801,"user":"not-an-object","body":"x"}]]\n' ;; + repos/o/r/issues/9/comments*) + printf '[[{"id":901,"user":{"login":"someone","type":"User"},"body":"I saw quoted"}],[{"id":902,"user":{"login":"github-actions[bot]","type":"Bot"},"body":"\\nold"}]]\n' ;; + repos/o/r/issues/10/comments*) + printf '[[{"id":1001,"user":{"login":"someone","type":"User"},"body":"I saw quoted"}]]\n' ;; + *) + echo "unexpected gh api path: $path" >&2 + exit 99 ;; +esac +STUB +chmod +x "$GH_STUB" + +# run_has ISSUE SECTION -> sets rc and err +run_has() { + : > "$CALL_LOG" + err=$(CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" bash "$HELPER" has o/r "$1" "$2" 2>&1 >/dev/null) + rc=$? +} + +run_has 1 issue-close +if [ "$rc" -eq 0 ]; then pass "has: card carrying issue-close reports present"; else bad "has issue-close on #1: expected 0, got ${rc} (${err})"; fi + +run_has 1 issue-closed +if [ "$rc" -eq 1 ]; then pass "has: section keys match exactly, not by prefix"; else bad "has issue-closed on #1: expected 1, got ${rc}"; fi + +run_has 2 issue-partial:163 +if [ "$rc" -eq 1 ]; then pass "has: issue-partial:163 does not match issue-partial:1638"; else bad "has issue-partial:163 on #2: expected 1, got ${rc}"; fi + +run_has 2 issue-partial: +if [ "$rc" -eq 0 ]; then pass "has: a trailing colon is an explicit prefix match"; else bad "has issue-partial: on #2: expected 0, got ${rc}"; fi + +run_has 3 issue-close +if [ "$rc" -eq 1 ] && [ -z "$err" ]; then pass "has: no card is ordinary absence (exit 1, no error)"; else bad "has on #3 (no card): expected 1 and no stderr, got ${rc} (${err})"; fi + +run_has 4 issue-close +if [ "$rc" -eq 1 ]; then pass "has: a human quoting the card's markers is not the card"; else bad "has on #4 (human quote): expected 1, got ${rc}"; fi + +for case in "5:API failure" "6:non-JSON response" "7:JSON that is not a comment list" "8:malformed comment object"; do + n="${case%%:*}"; what="${case#*:}" + run_has "$n" issue-close + if [ "$rc" -eq 3 ] && printf '%s' "$err" | grep -q '^hive-status-card: error:'; then + pass "has: ${what} exits 3 with an error, not absence" + else + bad "has on #${n} (${what}): expected exit 3 and an error line, got ${rc} (${err})" + fi +done + +: > "$CALL_LOG" +printf 'not json' > "$TMP/bad-comments.json" +CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" HIVE_COMMENTS_FILE="$TMP/bad-comments.json" bash "$HELPER" has o/r 1 issue-close >/dev/null 2>&1 +rc=$? +if [ "$rc" -eq 3 ] && [ ! -s "$CALL_LOG" ]; then pass "has: an unparseable HIVE_COMMENTS_FILE is an error and issues no GET"; else bad "bad HIVE_COMMENTS_FILE: expected 3 and no gh call, got ${rc}"; fi + +: > "$CALL_LOG" +CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" HIVE_COMMENTS_FILE="$TMP/missing.json" bash "$HELPER" has o/r 1 issue-close >/dev/null 2>&1 +rc=$? +if [ "$rc" -eq 3 ]; then pass "has: a missing HIVE_COMMENTS_FILE is an error"; else bad "missing HIVE_COMMENTS_FILE: expected 3, got ${rc}"; fi + +BODY="$TMP/body.md" +printf '\nnew\n' > "$BODY" + +run_upsert() { + : > "$CALL_LOG" + CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" bash "$HELPER" upsert o/r "$1" '' "$BODY" >/dev/null 2>&1 + rc=$? +} + +run_upsert 9 +if [ "$rc" -eq 0 ] && grep -q '^PATCH repos/o/r/issues/comments/902$' "$CALL_LOG" \ + && ! grep -q '901' "$CALL_LOG" && ! grep -q '^POST' "$CALL_LOG"; then + pass "upsert: edits the posting identity's own marker comment (found on a later page)" +else + bad "upsert #9: expected one PATCH of 902 (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +run_upsert 10 +if [ "$rc" -eq 0 ] && grep -q '^POST repos/o/r/issues/10/comments$' "$CALL_LOG" && ! grep -q '^PATCH' "$CALL_LOG"; then + pass "upsert: never edits another author's comment carrying the marker; creates its own" +else + bad "upsert #10: expected a POST and no PATCH (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +run_upsert 3 +if [ "$rc" -eq 0 ] && grep -q '^POST repos/o/r/issues/3/comments$' "$CALL_LOG"; then + pass "upsert: creates the comment when no marker comment exists" +else + bad "upsert #3: expected a POST (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +for n in 5 6; do + run_upsert "$n" + if [ "$rc" -eq 3 ] && ! grep -q -E '^(POST|PATCH)' "$CALL_LOG"; then + pass "upsert: a read failure on #${n} exits 3 without posting a duplicate" + else + bad "upsert #${n}: expected exit 3 and no write (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" + fi +done + +if [ "$fail" -ne 0 ]; then + echo "test-hive-status-card FAILED" + exit 1 +fi +echo "test-hive-status-card OK" diff --git a/.github/workflows/dashboard-mobile-shots.yml b/.github/workflows/dashboard-mobile-shots.yml index f55eb1242c..e6c5b37a84 100644 --- a/.github/workflows/dashboard-mobile-shots.yml +++ b/.github/workflows/dashboard-mobile-shots.yml @@ -9,6 +9,7 @@ on: - 'src/pkg/dashboard/**' - 'src/scripts/dashboard-mobile-shots.mjs' - 'src/scripts/fixtures/dashboard-preparation-rail.mjs' + - 'src/scripts/fixtures/dashboard-activity-density.mjs' - '.github/workflows/dashboard-mobile-shots.yml' concurrency: diff --git a/.github/workflows/fossa.yml b/.github/workflows/fossa.yml index 9d28007235..c74f85f83e 100644 --- a/.github/workflows/fossa.yml +++ b/.github/workflows/fossa.yml @@ -20,7 +20,7 @@ jobs: fossa: name: FOSSA license scan runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 env: FOSSA_API_KEY: ${{ secrets.FOSSA_API_KEY }} steps: @@ -33,10 +33,51 @@ jobs: if: env.FOSSA_API_KEY == '' run: echo "FOSSA_API_KEY secret not set; skipping FOSSA scan." >> "$GITHUB_STEP_SUMMARY" + # The key must be a push-only token from the *CNCF* FOSSA organization so + # the project lands in the CNCF instance (cncf/sandbox#545). `team` takes + # the team NAME, not the numeric id, and is honored only on the very first + # upload that creates the project (fossa-cli docs/references/files/fossa-yml.md). + # With `run-tests: true` the action runs ONLY `fossa test` (no analyze) + # and forwards `team`/`branch` to it, which `fossa test` rejects. So: + # always analyze (upload), then on PRs run the policy test separately. - name: Run FOSSA scan if: env.FOSSA_API_KEY != '' uses: fossas/fossa-action@29693cc50323968e039056be419b32989fc5880c # v2.0.0 with: api-key: ${{ secrets.FOSSA_API_KEY }} - run-tests: ${{ github.event_name == 'pull_request' }} + project: hivecommons/hive + team: Hive Commons + branch: ${{ github.head_ref || github.ref_name }} + + # A recent base-branch push may still be queued or analyzing in FOSSA. + # Upload the exact diff baseline here so the PR test does not race it. + # Check it out after the PR scan to keep it out of that scan's discovery. + - name: Checkout FOSSA diff baseline + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .fossa-base + persist-credentials: false + + - name: Analyze FOSSA diff baseline + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + working-directory: .fossa-base + env: + FOSSA_BASE_SHA: ${{ github.event.pull_request.base.sha }} + FOSSA_BASE_BRANCH: ${{ github.event.pull_request.base.ref }} + # Reuse the CLI installed by Run FOSSA scan; the action has no revision input. + run: | + fossa analyze --project hivecommons/hive \ + --revision "$FOSSA_BASE_SHA" \ + --branch "$FOSSA_BASE_BRANCH" \ + --team "Hive Commons" + + - name: Run FOSSA policy test + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + uses: fossas/fossa-action@29693cc50323968e039056be419b32989fc5880c # v2.0.0 + with: + api-key: ${{ secrets.FOSSA_API_KEY }} + project: hivecommons/hive + run-tests: true test-diff-revision: ${{ github.event.pull_request.base.sha }} diff --git a/.github/workflows/native-queue-policy.yml b/.github/workflows/native-queue-policy.yml index ee55939a06..08420d8e43 100644 --- a/.github/workflows/native-queue-policy.yml +++ b/.github/workflows/native-queue-policy.yml @@ -33,12 +33,12 @@ jobs: ref: ${{ github.event.merge_group.base_sha || format('refs/heads/{0}', github.event.pull_request.base.ref) }} persist-credentials: false - name: Test policy behavior - run: node --test .github/scripts/native-queue-policy.test.cjs + run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/diagnose-dco-provider.test.cjs - name: Validate exact-head evidence (bounded wait for PR providers) uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | - const { evaluate, PendingEvidence } = require('./.github/scripts/native-queue-policy.cjs'); + const { evaluate, PendingEvidence, ProviderUnavailable } = require('./.github/scripts/native-queue-policy.cjs'); const attempts = 90; const intervalMs = 15000; for (let attempt = 0; attempt < attempts; attempt++) { @@ -46,6 +46,14 @@ jobs: core.info(await evaluate({github, context})); return; } catch (error) { + if (error instanceof ProviderUnavailable) { + await core.summary + .addHeading('Admission blocked: DCO provider unavailable') + .addRaw(error.message) + .write(); + core.setFailed(error.message); + return; + } if (!(error instanceof PendingEvidence) || attempt === attempts - 1) throw error; core.info(error.message); await new Promise(resolve => setTimeout(resolve, intervalMs)); diff --git a/.github/workflows/pr-auto-update-test.yml b/.github/workflows/pr-auto-update-test.yml index acf6e3c6ab..011d3c6c78 100644 --- a/.github/workflows/pr-auto-update-test.yml +++ b/.github/workflows/pr-auto-update-test.yml @@ -7,6 +7,7 @@ on: - '.github/scripts/test_pr-auto-update.sh' - '.github/workflows/pr-auto-update*.yml' - '.github/scripts/native-queue-*.cjs' + - '.github/scripts/diagnose-dco-provider*.cjs' - 'src/pkg/dashboard/static-src/js/config-helpers.js' - 'src/pkg/dashboard/static-src/js/config-features.js' - 'src/pkg/dashboard/static-src/js/tracker-native-queue.js' @@ -23,6 +24,7 @@ on: - '.github/scripts/test_pr-auto-update.sh' - '.github/workflows/pr-auto-update*.yml' - '.github/scripts/native-queue-*.cjs' + - '.github/scripts/diagnose-dco-provider*.cjs' - 'src/pkg/dashboard/static-src/js/config-helpers.js' - 'src/pkg/dashboard/static-src/js/config-features.js' - 'src/pkg/dashboard/static-src/js/tracker-native-queue.js' @@ -52,7 +54,7 @@ jobs: with: node-version: '22' - name: Exercise native queue policy with mocked APIs - run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/native-queue-settings.test.cjs .github/scripts/native-queue-tracker.test.cjs + run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/native-queue-settings.test.cjs .github/scripts/native-queue-tracker.test.cjs .github/scripts/diagnose-dco-provider.test.cjs - name: Ensure YAML parser for workflow contracts run: | python3 -c 'import yaml' 2>/dev/null && exit 0 diff --git a/README.md b/README.md index 47beaaf13e..dc1b28f306 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@

Watch the hive live on Twitch + FOSSA license scan status

--- diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 978707c748..06fc9a475a 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -5811,6 +5811,10 @@ const PROMPT_SUBMIT_DELAYED_RENDER_POLLS = 2; // `send-keys -l` bursts. Keep other backends on their long-tested literal path // until their panes show the same transport failure. const TASK_PROMPT_BRACKETED_PASTE_BACKENDS = new Set(['codex']); +// #16423: tmux rejects a single command above a few KB ("command too long"), +// and `send-keys -l ''` is one command. Donated standby prompts carry +// the lane role prompt (~55 KB), so any backend pastes above this size. +const TASK_PROMPT_PASTE_BUFFER_THRESHOLD_BYTES = 8192; const STRICT_PROMPT_CONFIRM_BACKENDS = new Set(['codex']); let tmuxPromptBufferSeq = 0; @@ -5838,7 +5842,8 @@ function tmuxPasteTaskPrompt(text) { } function tmuxDeliverTaskPrompt(text) { - if (TASK_PROMPT_BRACKETED_PASTE_BACKENDS.has(BACKEND)) { + if (TASK_PROMPT_BRACKETED_PASTE_BACKENDS.has(BACKEND) || + Buffer.byteLength(text, 'utf8') > TASK_PROMPT_PASTE_BUFFER_THRESHOLD_BYTES) { tmuxPasteTaskPrompt(text); } else { execSync(`tmux send-keys -t ${TMUX_SESSION} -l ${shellQuote(text)}`, { timeout: 30000 }); @@ -6111,6 +6116,8 @@ function tmuxSendKeys(text) { } if (!sent) { console.error('All tmux prompt paste attempts failed — task prompt lost'); + // #16423: tell the hub, or the item sits as an accepted task that never started. + failCurrentTask('All tmux prompt paste attempts failed — task prompt lost', { kind: 'environment' }); return; } // #6717/#9078: settle before submitting. sleepMs() is a no-op under diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index a460ecf874..e7a543edde 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -13427,6 +13427,30 @@ test('#9078 short task prompts use the same bracketed-paste path', () => { } finally { teardown(relay); } }); +test('#16423 oversized task prompts are pasted via load-buffer on every backend', () => { + const relay = loadRelay({ backend: 'claude', paneText: CODEX_WORKING_PANE }); + try { + relay.setCliReady(true); + const prompt = 'lane role prompt. ' + 'padding '.repeat(7000); + relay.tmuxSendKeys(prompt); + const loads = tmuxCalls(relay, 'load-buffer'); + assert.strictEqual(loads.length, 1); + assert.strictEqual(loads[0].opts && loads[0].opts.input, prompt); + assert.strictEqual(tmuxCalls(relay, 'paste-buffer').length, 1); + assert.deepStrictEqual(relay.__tmuxSends().filter(c => / -l lane role prompt/.test(c)), [], + 'an oversized prompt must not be sent as one send-keys argument'); + } finally { teardown(relay); } +}); + +test('#16423 small task prompts on claude keep the send-keys path', () => { + const relay = loadRelay({ backend: 'claude', paneText: CODEX_WORKING_PANE }); + try { + relay.setCliReady(true); + relay.tmuxSendKeys('short task prompt'); + assert.strictEqual(tmuxCalls(relay, 'load-buffer').length, 0); + } finally { teardown(relay); } +}); + // #9082: tmux capture-pane -p pads to the pane height. A codex turn that is // in flight renders "esc to interrupt" near the top of a tall pane, so a raw // slice(-15) window is blank padding and the busy marker is never seen. diff --git a/changelog.d/added-16475-code-activity-reader.md b/changelog.d/added-16475-code-activity-reader.md new file mode 100644 index 0000000000..bd965eb20d --- /dev/null +++ b/changelog.d/added-16475-code-activity-reader.md @@ -0,0 +1 @@ +- Add an opt-in code activity reader at `?kiosk=1&view=reader`. It shows pushed changes from `/api/matrix/lines` as readable, wrapping paragraph cards with green `+` additions and red `−` removals, with the repository, PR link, file, stage and observed time. It supports pause with P, Space or the button, pauses while you scroll, uses a static layout for reduced motion and stops in hidden tabs. The Matrix view is unchanged (#16475). diff --git a/changelog.d/added-16476-published-checkpoints.md b/changelog.d/added-16476-published-checkpoints.md new file mode 100644 index 0000000000..d3e17c0e17 --- /dev/null +++ b/changelog.d/added-16476-published-checkpoints.md @@ -0,0 +1 @@ +- Feed the Code activity reader whole pushed PR diff regions, including removals, through the existing authorized sentinel observer, with whole-region secret filtering, bounded memory-only history, policy reset, visible freshness, buffered-snapshot labels and explicit replay; stop restoring or writing the legacy Matrix code-history file. diff --git a/changelog.d/added-16530-matrix-lines-more.md b/changelog.d/added-16530-matrix-lines-more.md new file mode 100644 index 0000000000..5a95281519 --- /dev/null +++ b/changelog.d/added-16530-matrix-lines-more.md @@ -0,0 +1 @@ +- `/api/matrix/lines` now returns `more`, true only while another line the caller may see remains past the page, so clients paging a filtered backlog can stop without an empty follow-up request ([#16530](https://github.com/hivecommons/hive/issues/16530)). diff --git a/changelog.d/added-16582-hive-auto-reauthor.md b/changelog.d/added-16582-hive-auto-reauthor.md new file mode 100644 index 0000000000..d4d739f27e --- /dev/null +++ b/changelog.d/added-16582-hive-auto-reauthor.md @@ -0,0 +1 @@ +- The hive re-authors its own fixer-exhausted PRs by itself instead of parking them for a person ([#16582](https://github.com/hivecommons/hive/issues/16582)): the exhausted hive PR is closed as superseded with a note, the issue is labelled `hive/re-authored` and requeued so the next kick opens a fresh PR from the current base (the kick asks for `Supersedes #`). One automatic re-author per issue; a second exhaustion parks at 085 with Give direction / Hand it to a person / Close as not planned. The Activity Monitor words the issue `Re-authoring · superseding #N` (remediation evidence `kick`) and the fresh PR's chip `re-authored from #N`. `decide:re-author` is gone from the decision vocabulary: a person's rewrite of a contributor PR (unsigned DCO, exhausted) is `decide:adopt` — "Adopt as hive PR"; historical `re-author` ledger entries still read. diff --git a/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md new file mode 100644 index 0000000000..8282daf6aa --- /dev/null +++ b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md @@ -0,0 +1 @@ +- Activity Monitor chevrons follow the canonical spec ([#16599](https://github.com/hivecommons/hive/issues/16599)): a row always has 1–2 **active** chevrons (amber fill + counted caption) — the item's stage column, plus a CI/Review track only while it genuinely runs on the current head; every other chevron is an **icon only** (neutral not-yet-run, red failed/changes requested, green passed/approved) with its counts and the backend sentence in the tooltip. CI and Review icons are a tiny ring segmented into `checks_total` / `perspectives_total` steps that fills clockwise (pass green, fail red, newest step pulsing while running). When nothing moves the blocker column is filled in a still stalled style, e.g. `CI 1/11 · waiting on workflow approval` for heads whose workflow runs are `action_required` on GitHub (new `PRCIActivity.WorkflowApproval`, blocker `workflow-approval-required:N`). Review-pending rows never read `Review unknown` / a default `5/5`: with no verdict bundle on the head they are `Review N/5 · in progress` (N = verdicts actually posted) or `· adjudicating`. diff --git a/changelog.d/changed-16477-code-activity-cutover.md b/changelog.d/changed-16477-code-activity-cutover.md new file mode 100644 index 0000000000..cd752c68e5 --- /dev/null +++ b/changelog.d/changed-16477-code-activity-cutover.md @@ -0,0 +1 @@ +- Code activity supersedes the Matrix code view: the Activity Monitor topbar has one **Code activity** entry (still `#oc-matrix-tab`) that opens the published-checkpoint reader at `?kiosk=1&view=reader` in a new tab. The decorative rain/cascade/ghost/terminal renderers and their `mx.*` settings are retired. Saved `?kiosk=1&view=matrix` URLs are a deprecated alias for the reader, and the internal `/api/matrix/lines` and `dashboard.matrix.*` names are deprecated but still supported. Capture and broadcasting stay off by default. diff --git a/changelog.d/changed-16571-repo-qualification.md b/changelog.d/changed-16571-repo-qualification.md new file mode 100644 index 0000000000..fea495872e --- /dev/null +++ b/changelog.d/changed-16571-repo-qualification.md @@ -0,0 +1 @@ +- Fixer queue keys and deferred-fix reconciliation now use the same repository qualification as the review queue, including whitespace trimming and empty-repository handling ([#16571](https://github.com/hivecommons/hive/pull/16571)). diff --git a/changelog.d/changed-16574.md b/changelog.d/changed-16574.md new file mode 100644 index 0000000000..61b4edcbee --- /dev/null +++ b/changelog.d/changed-16574.md @@ -0,0 +1 @@ +- Document why dashboard matrix authentication failures also receive `Cache-Control: no-store`. diff --git a/changelog.d/changed-activity-chevron-verdict-icons.md b/changelog.d/changed-activity-chevron-verdict-icons.md new file mode 100644 index 0000000000..e0f6990128 --- /dev/null +++ b/changelog.d/changed-activity-chevron-verdict-icons.md @@ -0,0 +1 @@ +- Activity monitor: once a CI or Review chevron reaches a settled verdict (all checks reported / review approved or changes requested) the chevron shows only its icon in green (pass) or red (fail); the former words ("CI 11/11 passed", "Review 5/5 · 1 changes requested", failing check names) move into the chevron tooltip and `aria-label`. In-progress and awaiting-human states keep their text; chevron geometry is unchanged. diff --git a/changelog.d/changed-hive-hosted-matrix-reader-view.md b/changelog.d/changed-hive-hosted-matrix-reader-view.md new file mode 100644 index 0000000000..b60b43eab4 --- /dev/null +++ b/changelog.d/changed-hive-hosted-matrix-reader-view.md @@ -0,0 +1 @@ +- hive-hosted-matrix stream overlay opens the dashboard with `view=reader` instead of the deprecated `view=matrix` alias (#16612). diff --git a/changelog.d/changed-issue-side-comment-churn.md b/changelog.d/changed-issue-side-comment-churn.md new file mode 100644 index 0000000000..cf98be5a10 --- /dev/null +++ b/changelog.d/changed-issue-side-comment-churn.md @@ -0,0 +1 @@ +- Issue-side comment churn is cut by editing in place instead of re-posting ([#16433](https://github.com/hivecommons/hive/issues/16433)): `hive:claim` / `hive:release` transitions now maintain one per-issue claim-ledger comment (``, current state plus the last 8 transitions; `github.notifications.claim_ledger`, default on, `false` restores one comment per transition) that every existing claim reader still parses; a PR re-entering a needs-decision stage has its entry comment rewritten with an `Updated ` line; a new push rewrites the hive's existing `hive-sentinel` comment for the new head; and in quiet mode a reviewer-lane review that narrates "no findings" with an approving, finding-free verdict is recorded and folded into the `hive:status` comment instead of being submitted as a review. diff --git a/changelog.d/changed-logscrub-v5-categories.md b/changelog.d/changed-logscrub-v5-categories.md new file mode 100644 index 0000000000..8dfc0d45ec --- /dev/null +++ b/changelog.d/changed-logscrub-v5-categories.md @@ -0,0 +1 @@ +- logscrub: `ScrubString` and the contributor relay now mask the same api-key, Slack/Discord webhook, Slack token and Basic-auth shapes on v5 as on v6 ([#16470](https://github.com/hivecommons/hive/pull/16470)). diff --git a/changelog.d/changed-progressive-dashboard-loading.md b/changelog.d/changed-progressive-dashboard-loading.md new file mode 100644 index 0000000000..f9bfd7866d --- /dev/null +++ b/changelog.d/changed-progressive-dashboard-loading.md @@ -0,0 +1 @@ +- Show the dashboard shell before downloading its cacheable application script, prioritize the selected and visible panels, limit background refresh concurrency, and progressively render the latest live data without waiting for every panel before restoring navigation. diff --git a/changelog.d/changed-reviewer-question-autodecide.md b/changelog.d/changed-reviewer-question-autodecide.md new file mode 100644 index 0000000000..57d332b6c5 --- /dev/null +++ b/changelog.d/changed-reviewer-question-autodecide.md @@ -0,0 +1 @@ +- A reviewer's scope / follow-up question on a hive-authored PR with CI green and no unresolved finding no longer parks the PR at 085 "Needs human decision": the dashboard classifies the ask and runs the existing *Let hive decide* pipeline itself (approve → merge queue plus a `follow-up:` issue; direction → fixer; owner-only → park with the recommendation), once per head, while policy sign-off asks (workflow edits from forks, OWNERS / secrets / permissions, auto-merge config, sentinel) stay a person's. Off switch `governor.review.auto_decide_questions`; counter `review_questions_autodecided_1h` on `/api/status`. diff --git a/changelog.d/fixed-16363-status-card-errors.md b/changelog.d/fixed-16363-status-card-errors.md new file mode 100644 index 0000000000..c2427e9a9f --- /dev/null +++ b/changelog.d/fixed-16363-status-card-errors.md @@ -0,0 +1 @@ +- The post-merge refs sweep no longer treats an unreadable `hive:status` card as "no card": when the comments API call fails or returns something other than a JSON list of comments, `.github/scripts/hive-status-card.sh` now reports an error (exit 3) instead of absence, `upsert` writes nothing, and the sweep skips that issue with an `::error::` annotation and a non-zero exit rather than posting a possible duplicate note ([#16363](https://github.com/hivecommons/hive/issues/16363)). diff --git a/changelog.d/fixed-16423.md b/changelog.d/fixed-16423.md new file mode 100644 index 0000000000..3d645ac33b --- /dev/null +++ b/changelog.d/fixed-16423.md @@ -0,0 +1 @@ +- Large task prompts (such as ~55 KB donated standby prompts) are no longer lost on claude relays: prompts over 8192 bytes are pasted through a tmux buffer, and a prompt that still cannot be delivered is reported to the hub as `task_failed` (#16423). diff --git a/changelog.d/fixed-16438-gate-regression-guard.md b/changelog.d/fixed-16438-gate-regression-guard.md new file mode 100644 index 0000000000..af5e8d0d02 --- /dev/null +++ b/changelog.d/fixed-16438-gate-regression-guard.md @@ -0,0 +1 @@ +- A spoke that boots from the ConfigMap seed (runtime overlay moved aside or missing) no longer drops `review.require_labels`, `project.paused_repos`, `writeback.per_repo` or `project.issue_filter.require_labels` in silence: each gate a previous overlay on the PVC carried that the effective config lacks or loosens is logged as `WARN safety gate dropped` with its previous value, listed in `/api/status` as `config.gate_regressions`, and shown as a Settings banner; `config.refuse_gate_regression: true` refuses to start instead. diff --git a/changelog.d/fixed-16459-manual-provisioning-label-keys.md b/changelog.d/fixed-16459-manual-provisioning-label-keys.md new file mode 100644 index 0000000000..91811627c6 --- /dev/null +++ b/changelog.d/fixed-16459-manual-provisioning-label-keys.md @@ -0,0 +1 @@ +- Fixed `manual-provisioning.md` to name the `hive.hivecommons.dev/*` namespace identity labels and annotation the hub actually stamps, instead of the legacy `hive.kubestellar.io/*` keys (#16459). diff --git a/changelog.d/fixed-16472-tracker-ci-review-icons.md b/changelog.d/fixed-16472-tracker-ci-review-icons.md new file mode 100644 index 0000000000..e68a5d7d5b --- /dev/null +++ b/changelog.d/fixed-16472-tracker-ci-review-icons.md @@ -0,0 +1 @@ +- The Activity Monitor tracker strip now shows a flask glyph for the CI track and keeps the eye for the Review track, so the two adjacent chevrons are no longer identical ([#16472](https://github.com/hivecommons/hive/issues/16472)). diff --git a/changelog.d/fixed-16479-ci-track-captions.md b/changelog.d/fixed-16479-ci-track-captions.md new file mode 100644 index 0000000000..09fdd46858 --- /dev/null +++ b/changelog.d/fixed-16479-ci-track-captions.md @@ -0,0 +1 @@ +- Activity Monitor CI track captions now explain themselves in plain language — `CI waiting · required check "test" hasn't reported for this head yet`, `CI running · 3/5 checks done`, `CI failing · "lint" red`, `CI green · all 3 required checks passed` — and each carries a longer explanation in the chevron tooltip via a new `detail` field; the fix-task CI-wait and CI-retry captions were reworded the same way ([#16479](https://github.com/hivecommons/hive/issues/16479)). diff --git a/changelog.d/fixed-16481-tracking-parent-word.md b/changelog.d/fixed-16481-tracking-parent-word.md new file mode 100644 index 0000000000..6da612447c --- /dev/null +++ b/changelog.d/fixed-16481-tracking-parent-word.md @@ -0,0 +1 @@ +- The activity monitor no longer shows a decomposed parent issue that is waiting on open child issues as a stuck *Actionable* row "waiting for the scanner to pick it up": the lit step reads `Tracking · 3/4` (or `Tracking · N open children`), the caption and actor name the open children, and the item carries `open_children` ([#16481](https://github.com/hivecommons/hive/issues/16481)). diff --git a/changelog.d/fixed-16485-tracker-row-density.md b/changelog.d/fixed-16485-tracker-row-density.md new file mode 100644 index 0000000000..03f2c69ac9 --- /dev/null +++ b/changelog.d/fixed-16485-tracker-row-density.md @@ -0,0 +1 @@ +- Activity monitor tracker rows are compact again: the stage chevrons sit directly under the title line as a one-line (~20px) strip, the issue title stays inline after its chips instead of dropping to its own line, the row toolbar pills share that first line, and row padding is tightened — roughly 60px per simple row as before the two-line chevron budget ([#16485](https://github.com/hivecommons/hive/issues/16485)). diff --git a/changelog.d/fixed-16490.md b/changelog.d/fixed-16490.md new file mode 100644 index 0000000000..de5ec142ce --- /dev/null +++ b/changelog.d/fixed-16490.md @@ -0,0 +1 @@ +- The inference translator's "unidentified caller refused" warning now records why the caller was unidentified (no UID map, unresolved socket, or unmapped UID), the socket owner UID, and whether an `x-api-key` was sent; the refusal itself is unchanged ([#16474](https://github.com/hivecommons/hive/issues/16474)). diff --git a/changelog.d/fixed-16493-tracker-chevron-counts.md b/changelog.d/fixed-16493-tracker-chevron-counts.md new file mode 100644 index 0000000000..499e963bbd --- /dev/null +++ b/changelog.d/fixed-16493-tracker-chevron-counts.md @@ -0,0 +1 @@ +- The Activity Monitor's CI and Review chevrons now show counts instead of a bare glyph or a muted tint: `CI 12/14 passed`, `CI 11/14 · 1 failing (lint)`, `CI 0/14 · queued`, `Review 3/5 perspectives`, `Review 5/5 approved`, `Review 0/5 · re-review pending (new head)`. A track in progress on the current head wears the full active fill (both may be lit at once — the counts disambiguate, and the tooltip says which one the hive is waiting on), a finished track wears the done style, a red check or changes-requested verdict wears the error colour, and only a not-yet-started track is a glyph alone. The server now reports `checks_passed/total/failed/failing` and `perspectives_done/total` on every CI/Review activity ([#16493](https://github.com/hivecommons/hive/issues/16493)). diff --git a/changelog.d/fixed-16496-assignment-close-race.md b/changelog.d/fixed-16496-assignment-close-race.md new file mode 100644 index 0000000000..06214e5383 --- /dev/null +++ b/changelog.d/fixed-16496-assignment-close-race.md @@ -0,0 +1 @@ +- Contributor assignments that race with an already-sent WebSocket close frame still release their undelivered claim, but now log at INFO instead of triggering repeated-error self-reports. diff --git a/changelog.d/fixed-16501-cluster-health-budget.md b/changelog.d/fixed-16501-cluster-health-budget.md new file mode 100644 index 0000000000..f5276b7902 --- /dev/null +++ b/changelog.d/fixed-16501-cluster-health-budget.md @@ -0,0 +1 @@ +- Bound spoke cluster-health collection with a shared deadline so slow Kubernetes APIs return partial health reports without exhausting the hub heartbeat collection budget ([#16501](https://github.com/hivecommons/hive/issues/16501)). diff --git a/changelog.d/fixed-16504-heartbeat-collect.md b/changelog.d/fixed-16504-heartbeat-collect.md new file mode 100644 index 0000000000..72240674c6 --- /dev/null +++ b/changelog.d/fixed-16504-heartbeat-collect.md @@ -0,0 +1 @@ +- Heartbeat loops no longer accumulate blocked full or fresh-stats collectors after repeated collection timeouts; fallback liveness beats continue, and timeout self-reports include the slowest collector sections. diff --git a/changelog.d/fixed-16507-heartbeat-cached-fallback.md b/changelog.d/fixed-16507-heartbeat-cached-fallback.md new file mode 100644 index 0000000000..6cd7992bb9 --- /dev/null +++ b/changelog.d/fixed-16507-heartbeat-cached-fallback.md @@ -0,0 +1 @@ +- Stop filing duplicate unclassified self-reports for the hub heartbeat's last-good cached stats fallback; retain local warnings and fleet reporting of collector timeouts, slow collectors, and heartbeat failures ([#16507](https://github.com/hivecommons/hive/issues/16507)). diff --git a/changelog.d/fixed-16522-covered-issue-release-while-fixing.md b/changelog.d/fixed-16522-covered-issue-release-while-fixing.md new file mode 100644 index 0000000000..84dd8ca332 --- /dev/null +++ b/changelog.d/fixed-16522-covered-issue-release-while-fixing.md @@ -0,0 +1 @@ +- The claim-release valve no longer drops a covered issue to `stage/010-actionable` while the hive is still repairing its red covering PR ([#16522](https://github.com/hivecommons/hive/issues/16522)). A red+stale PR releases its issue only once the fix loop has given up on that head: escalated to a human, re-engagement budget spent, or red for the whole re-engagement window (`escalation.ClaimReleaseAfter`) with no owner reachable. Until then the issue stays `stage/040-covered-by-pr` narrating the PR's `070-fixing`, and the scanner is not offered work a live PR already owns. diff --git a/changelog.d/fixed-16536-fixer-fallback.md b/changelog.d/fixed-16536-fixer-fallback.md new file mode 100644 index 0000000000..0a6982f9bc --- /dev/null +++ b/changelog.d/fixed-16536-fixer-fallback.md @@ -0,0 +1 @@ +- Add opt-in ordered fixer fallback agents, configurable in Settings, so review fixes and stale red-PR repairs can bypass an undeliverable primary without interrupting its turn ([#16536](https://github.com/hivecommons/hive/issues/16536)). diff --git a/changelog.d/fixed-16537-fixer-queue.md b/changelog.d/fixed-16537-fixer-queue.md new file mode 100644 index 0000000000..8f7843a7ce --- /dev/null +++ b/changelog.d/fixed-16537-fixer-queue.md @@ -0,0 +1 @@ +- Deferred PR fix kicks now retain their queue position until delivery or closure; the governor API exposes the queue and the dashboard review queue shows “fixer queued, N ahead” ([#16537](https://github.com/hivecommons/hive/issues/16537)). diff --git a/changelog.d/fixed-16550-reader-context-lines.md b/changelog.d/fixed-16550-reader-context-lines.md new file mode 100644 index 0000000000..09744f34cf --- /dev/null +++ b/changelog.d/fixed-16550-reader-context-lines.md @@ -0,0 +1 @@ +- The code activity reader now accepts unchanged diff context lines (`op: ' '`) from a regions source and renders them in a neutral color with their space prefix, instead of dropping the whole region; the current published-checkpoint source still emits only `+`/`-` lines ([#16550](https://github.com/hivecommons/hive/issues/16550)). diff --git a/changelog.d/fixed-16551-chevron-height.md b/changelog.d/fixed-16551-chevron-height.md new file mode 100644 index 0000000000..549f916cd9 --- /dev/null +++ b/changelog.d/fixed-16551-chevron-height.md @@ -0,0 +1 @@ +- Activity Monitor stage chevrons are a one-line band again on phones and touch tablets; the chevron's info wrapper no longer inherits the 40px tap-target floor (and ring) that made every chevron a 44px box ([#16551](https://github.com/hivecommons/hive/issues/16551)). diff --git a/changelog.d/fixed-16552-pushed-head-ci-track.md b/changelog.d/fixed-16552-pushed-head-ci-track.md new file mode 100644 index 0000000000..e5825b5ef8 --- /dev/null +++ b/changelog.d/fixed-16552-pushed-head-ci-track.md @@ -0,0 +1 @@ +- The Activity Monitor keeps the CI track lit on a 071/072 row whose pushed or checking head has checks running, instead of muting it as waiting on the contributor ([#16552](https://github.com/hivecommons/hive/issues/16552)). diff --git a/changelog.d/fixed-16579.md b/changelog.d/fixed-16579.md new file mode 100644 index 0000000000..05a0773154 --- /dev/null +++ b/changelog.d/fixed-16579.md @@ -0,0 +1 @@ +- Stage controller: an issue a maintainer already decided (`approved-direction`) whose remaining work is human-only (`needs-human`) is no longer re-parked on `stage/045-needs-decision` with the ack stripped; it keeps `approved-direction` and is held out of the pipeline, ending the decide → re-park bounce loop; a newer, different `/hive decision` still lets an agent's park through and clears the stale ack ([#16579](https://github.com/hivecommons/hive/issues/16579)). diff --git a/changelog.d/fixed-16580-viewer-signoff-match.md b/changelog.d/fixed-16580-viewer-signoff-match.md new file mode 100644 index 0000000000..45e8c01758 --- /dev/null +++ b/changelog.d/fixed-16580-viewer-signoff-match.md @@ -0,0 +1 @@ +- Activity Monitor: a sign-off question naming `@clubanderson-bot` or `@clubandersonx` no longer reads "needs your sign-off" to the viewer `clubanderson`; the viewer's handle is matched on a word boundary. diff --git a/changelog.d/fixed-16586.md b/changelog.d/fixed-16586.md new file mode 100644 index 0000000000..d2254b76eb --- /dev/null +++ b/changelog.d/fixed-16586.md @@ -0,0 +1 @@ +- The automerge sweep reuses the stored re-author target on retry passes instead of fetching the exhausted PR's closing issue from GitHub each pass ([#16586](https://github.com/hivecommons/hive/issues/16586)). diff --git a/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md b/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md new file mode 100644 index 0000000000..e232f220cb --- /dev/null +++ b/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md @@ -0,0 +1 @@ +- Stop-polling nudges no longer leave a `ci_poll_nudge` fleet report marked unrecovered: the next kick after a nudge now closes it as self-recovered, so the report stops accusing a healthy agent of being stuck ([#16588](https://github.com/hivecommons/hive/issues/16588)). diff --git a/changelog.d/fixed-16591.md b/changelog.d/fixed-16591.md new file mode 100644 index 0000000000..b54e4c37f5 --- /dev/null +++ b/changelog.d/fixed-16591.md @@ -0,0 +1 @@ +- The un-park sweep no longer posts the "What to reply" notice or the `/hive approve` hint on an issue held after a human decision (`needs-human` + `approved-direction`, no stage/045), while still answering `/hive decision`, `/hive help` and `/fixed` on it ([#16591](https://github.com/hivecommons/hive/issues/16591)). diff --git a/changelog.d/fixed-16606.md b/changelog.d/fixed-16606.md new file mode 100644 index 0000000000..e0637fa390 --- /dev/null +++ b/changelog.d/fixed-16606.md @@ -0,0 +1 @@ +- fix(github): log expected author self-approval verdict refusals at INFO instead of WARN so they no longer surface in repeated-error self-reports (#16605) diff --git a/changelog.d/fixed-16625.md b/changelog.d/fixed-16625.md new file mode 100644 index 0000000000..3523513fc6 --- /dev/null +++ b/changelog.d/fixed-16625.md @@ -0,0 +1 @@ +- Keep a not-yet-run current-phase CI/Review chevron visibly filled (#16625) diff --git a/changelog.d/fixed-activity-chevron-height.md b/changelog.d/fixed-activity-chevron-height.md new file mode 100644 index 0000000000..f1c4ac7b35 --- /dev/null +++ b/changelog.d/fixed-activity-chevron-height.md @@ -0,0 +1 @@ +- Activity monitor: stage chevrons are again only as tall as their caption (one line of text → a one-line chevron, two lines → two, never more) with the caption centred instead of flush-left in a fixed two-line box, and the CI / Review lanes are notched chevrons like the other stages (state shown by fill and text colour) rather than bordered boxes. diff --git a/changelog.d/fixed-activity-header-spans.md b/changelog.d/fixed-activity-header-spans.md new file mode 100644 index 0000000000..f2bd6f427d --- /dev/null +++ b/changelog.d/fixed-activity-header-spans.md @@ -0,0 +1 @@ +- Restore activity issue/PR header spans and far-right action controls; keep truthful current-phase highlights across parallel CI/Review, wrap all chevrons within two lines with complete hover/keyboard details, show unknown track states as icons rather than verbose panels, and label observed PR remediation “Remediating” without renaming native states or implying work during waits. diff --git a/changelog.d/fixed-activity-needs-human-hive-note.md b/changelog.d/fixed-activity-needs-human-hive-note.md new file mode 100644 index 0000000000..c372795996 --- /dev/null +++ b/changelog.d/fixed-activity-needs-human-hive-note.md @@ -0,0 +1 @@ +- Activity monitor: "Needs human: …", "Current blocker", "Next move", "Claimed by" and optional-delegation lines under an item are hive notes again — they open, tuck left into the ⬡ icon after the same 30 s as other hive notes, re-open on click, and a re-render never re-opens a line the tab already showed. The row's Let hive decide / Sentinel alert controls still carry the decision state. #16011 had drawn these as static rows that never left. diff --git a/changelog.d/fixed-adopt-now-takes-over-any-author.md b/changelog.d/fixed-adopt-now-takes-over-any-author.md new file mode 100644 index 0000000000..23b629de55 --- /dev/null +++ b/changelog.d/fixed-adopt-now-takes-over-any-author.md @@ -0,0 +1 @@ +- An operator's Adopt now takes over any PR, a hive owner's or maintainer's included: the stage engine honours the forced adoption instead of refusing it as person-authored on every sweep, which left the row at "adopting… (queued)" forever. The hive still never adopts a person's own PR on its own initiative; the audit names the author taken over from. diff --git a/changelog.d/fixed-advisory-digest-foreign-anchor.md b/changelog.d/fixed-advisory-digest-foreign-anchor.md new file mode 100644 index 0000000000..2b61c14bc8 --- /dev/null +++ b/changelog.d/fixed-advisory-digest-foreign-anchor.md @@ -0,0 +1 @@ +- Advisory digest: when the newest digest comment on the advisory issue is not App-authored, re-pin to the App's own digest comment (or create one) and persist that anchor; log the foreign-comment warning once per issue per process (Debug thereafter) with the action taken, and skip the edit when the digest's material content is unchanged for the anchor. diff --git a/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md b/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md new file mode 100644 index 0000000000..84771a421a --- /dev/null +++ b/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md @@ -0,0 +1 @@ +- The fleet selfreport feed no longer files the automerge sweep lanes' (queued, trusted-author, contributor) `base-refresh:merge-guard` skip ("destination merge already in progress") as an `unclassified_error_repeated` issue; it is an expected, self-limiting outcome and stays in local logs (#16520). diff --git a/changelog.d/fixed-awaiting-rerun-lane.md b/changelog.d/fixed-awaiting-rerun-lane.md new file mode 100644 index 0000000000..c5c62ca884 --- /dev/null +++ b/changelog.d/fixed-awaiting-rerun-lane.md @@ -0,0 +1 @@ +- Activity Monitor: a PR parked on a person who must act on the PR itself (rerun CI, approve workflow runs, resolve a GitHub permission, answer open review findings) now lights the PR in progress chevron — "Waiting for @who · rerun shared ci on GitHub" — and leaves the Merge queue column empty; only rows actually queued / merging, or a merge-ready PR parked on a merge decision, sit in Merge queue. diff --git a/changelog.d/fixed-ci-failure-kick-retry.md b/changelog.d/fixed-ci-failure-kick-retry.md new file mode 100644 index 0000000000..bd33424018 --- /dev/null +++ b/changelog.d/fixed-ci-failure-kick-retry.md @@ -0,0 +1 @@ +- Retry CI-failure webhook kicks with bounded backoff when the owning agent is busy, then drain a bounded per-PR/check pending queue on governor evaluations; discard resolved signals when checks pass or PRs close. diff --git a/changelog.d/fixed-heartbeat-timeout-outcome-notices.md b/changelog.d/fixed-heartbeat-timeout-outcome-notices.md new file mode 100644 index 0000000000..9205d7f580 --- /dev/null +++ b/changelog.d/fixed-heartbeat-timeout-outcome-notices.md @@ -0,0 +1 @@ +- Stop filing duplicate unclassified self-reports for the hub heartbeat collect-timeout outcome notices (minimal liveness beat, skipped beat before identity is known, and stale stats without fresh agent overlay); retain local warnings and fleet reporting of collector timeouts, slow collectors, panics, and heartbeat failures ([#16516](https://github.com/hivecommons/hive/issues/16516)). diff --git a/changelog.d/fixed-kubejob-cleanup-ctx.md b/changelog.d/fixed-kubejob-cleanup-ctx.md new file mode 100644 index 0000000000..aa2fb91a14 --- /dev/null +++ b/changelog.d/fixed-kubejob-cleanup-ctx.md @@ -0,0 +1 @@ +- Completed Kubernetes Jobs are now immediately deleted even if the caller's context expires during pod log collection, preventing them from lingering for the full TTL ([#16547](https://github.com/hivecommons/hive/issues/16547)). diff --git a/changelog.d/fixed-lead-delegate-inline.md b/changelog.d/fixed-lead-delegate-inline.md new file mode 100644 index 0000000000..194036b8e1 --- /dev/null +++ b/changelog.d/fixed-lead-delegate-inline.md @@ -0,0 +1 @@ +- Activity Monitor: a row parked on a human decision now shows "Let hive decide" inline beside the server's lead (e.g. "Re-author") instead of hiding it under ⋯ → Decide…, and inline action pills are filled buttons with a ▸ glyph and a consequence tooltip so they no longer pass for record pills like "adopted from #N". diff --git a/changelog.d/fixed-matrix-ingest-freshness.md b/changelog.d/fixed-matrix-ingest-freshness.md index fdb1d8b350..639a4a819c 100644 --- a/changelog.d/fixed-matrix-ingest-freshness.md +++ b/changelog.d/fixed-matrix-ingest-freshness.md @@ -1 +1 @@ -- Matrix kiosk no longer goes stale for the length of a governor tick: an incremental sentinel pass now reads only new PR heads in the allowlisted repos every two minutes, independently of the full 15-minute sweep, and `/api/matrix/lines` reports `last_ingest_at` / `next_ingest_in_s` so the footer can tell "nothing pushed" from "nothing ingested". The matrix backlog (last 500 lines) and the set of already-evaluated PR heads now persist under `/data/matrix-lines.json` and `/data/sentinel-heads.json` and are restored at boot with the sequence counter continuing, so a hub-triggered restart no longer blanks the kiosk or re-diffs every open PR; the first ingest also runs at boot instead of waiting for the reconcile timer ([#16276](https://github.com/hivecommons/hive/issues/16276)). +- Matrix kiosk no longer goes stale for the length of a governor tick: an incremental sentinel pass now reads only new PR heads in the allowlisted repos every two minutes, independently of the full 15-minute sweep, and `/api/matrix/lines` reports `last_ingest_at` / `next_ingest_in_s` so the footer can tell "nothing pushed" from "nothing ingested". The set of already-evaluated PR heads now persists under `/data/sentinel-heads.json` and is restored at boot, so a hub-triggered restart no longer re-diffs every open PR; the first ingest also runs at boot instead of waiting for the reconcile timer ([#16276](https://github.com/hivecommons/hive/issues/16276)). diff --git a/changelog.d/fixed-matrix-terminal-hud-cta.md b/changelog.d/fixed-matrix-terminal-hud-cta.md new file mode 100644 index 0000000000..4a7b8bc85b --- /dev/null +++ b/changelog.d/fixed-matrix-terminal-hud-cta.md @@ -0,0 +1 @@ +- Matrix kiosk: the freshness HUD and get-started CTA now stay pinned above the canvas in every effect, including `mx.effect=terminal`, and typed rows stop above the HUD band. diff --git a/changelog.d/fixed-merge-queue-ci-rerun-flip.md b/changelog.d/fixed-merge-queue-ci-rerun-flip.md new file mode 100644 index 0000000000..fe52e153d8 --- /dev/null +++ b/changelog.d/fixed-merge-queue-ci-rerun-flip.md @@ -0,0 +1 @@ +- A human-gated (085) PR that is approved on its current head now stays in the Merge queue column while CI on that head is queued or re-running, instead of flipping to PR in progress and back as checks cycle; failing CI or an unapproved review still moves it out ([#16595](https://github.com/hivecommons/hive/issues/16595)). diff --git a/changelog.d/fixed-mobile-overview-kpi-overflow.md b/changelog.d/fixed-mobile-overview-kpi-overflow.md new file mode 100644 index 0000000000..78c853e26d --- /dev/null +++ b/changelog.d/fixed-mobile-overview-kpi-overflow.md @@ -0,0 +1 @@ +- Overview KPI tiles no longer overflow the phone viewport right after a restart: the "refreshing after restart" pill wraps inside the card instead of widening the headline grid, tile sublines and sparklines stay within the tile, and the `--fs-2xs`/`--fs-2xl`/`--fs-3xl` type tokens are now defined at `:root` so they no longer fall back to the 16px body size (hivecommons/hive#16601). diff --git a/changelog.d/fixed-needs-human-reason-on-row.md b/changelog.d/fixed-needs-human-reason-on-row.md new file mode 100644 index 0000000000..c111bdc0fa --- /dev/null +++ b/changelog.d/fixed-needs-human-reason-on-row.md @@ -0,0 +1 @@ +- Activity Monitor rows parked on a person now state why on the row itself: the hive-note line reads `#N — Needs human: — · requested by … · lead: ▸ · @author is pushing it in #PR`, the issue's decision column keeps `Blocked · App lacks workflows permission 👤` while a covering PR drives the strip, the `needs human` pill carries the full reason and reveals the line on click, the 085 chevron reads `Needs human · ` (e.g. "edits CI workflows"), an issue blocked only by its PR's pending decision reads `decision on #PR`, the first enabled blocker option leads when the server disables "Let hive decide" (shown muted with its reason), and the "owed — blocked: …" caption double space is gone ([#16623](https://github.com/hivecommons/hive/issues/16623)). diff --git a/changelog.d/fixed-rebase-exhaustion-selfreport.md b/changelog.d/fixed-rebase-exhaustion-selfreport.md new file mode 100644 index 0000000000..c78b920241 --- /dev/null +++ b/changelog.d/fixed-rebase-exhaustion-selfreport.md @@ -0,0 +1 @@ +- Stop filing fleet runtime self-reports for the expected handoff after rebase attempts are exhausted, while retaining the local warning and diagnostics ([#16510](https://github.com/hivecommons/hive/issues/16510)). diff --git a/changelog.d/fixed-remediating-chevron-evidence.md b/changelog.d/fixed-remediating-chevron-evidence.md new file mode 100644 index 0000000000..bd767effb6 --- /dev/null +++ b/changelog.d/fixed-remediating-chevron-evidence.md @@ -0,0 +1 @@ +- Activity Monitor: the PR in progress chevron on a red PR now reads the evidence-based remediation state — `Changes requested · unassigned · next: scanner` while nobody has picked it up, `Remediating · · 4m` only on a running fix kick, a clanker claim or a working agent on the PR, and a done-style `Fix pushed abc1234 · re-review pending` once a head lands after the red signal; a push that predates the changes-requested review no longer reads as a fix. The item carries `remediation: {actor, kind, since, source}` and the tooltip names the evidence (hivecommons/hive#16525). diff --git a/changelog.d/fixed-review-chevron-amber.md b/changelog.d/fixed-review-chevron-amber.md new file mode 100644 index 0000000000..75c4d93c0c --- /dev/null +++ b/changelog.d/fixed-review-chevron-amber.md @@ -0,0 +1 @@ +- Activity Monitor: the Review and CI chevrons wear the amber in-progress fill only while perspectives or checks are actually running; a finished verdict is done-style (approved, changes requested, or a muted "awaiting human decision"). Back in PR in progress with the hive on the repair, a human-decision verdict reads "changes requested" instead of "awaiting human decision" (#16531). diff --git a/changelog.d/fixed-signoff-lead.md b/changelog.d/fixed-signoff-lead.md new file mode 100644 index 0000000000..96970343a2 --- /dev/null +++ b/changelog.d/fixed-signoff-lead.md @@ -0,0 +1 @@ +- Activity Monitor: a row parked on a policy sign-off ask (e.g. a fork's workflow change) now says "Review 5/5 · needs your sign-off" / "needs owner sign-off" instead of "awaiting human decision", leads with an inline "Approve ▸" when CI is green (then "Let hive decide ▸"), and no longer captions "Recommendation recorded" when hive kept the park without recording a recommendation. diff --git a/changelog.d/fixed-single-hive-note-line.md b/changelog.d/fixed-single-hive-note-line.md new file mode 100644 index 0000000000..b0978c77ac --- /dev/null +++ b/changelog.d/fixed-single-hive-note-line.md @@ -0,0 +1 @@ +- Activity Monitor: a tracker row (issue row or PR sub-row) now renders at most one hive note line. The needs-human / decision ask outranks the blocker, next-move and stage-transition notes; a lower note's facts ride the winning line as a trailing clause only when they say something the row does not already (a "moved to Needs human decision" note under a strip already lit at Needs human decision is dropped). The single line keeps its ⬡ icon, View link and one relative age ([#16627](https://github.com/hivecommons/hive/issues/16627)). diff --git a/changelog.d/fixed-stream-buffering-watchdog.md b/changelog.d/fixed-stream-buffering-watchdog.md new file mode 100644 index 0000000000..088a273e2a --- /dev/null +++ b/changelog.d/fixed-stream-buffering-watchdog.md @@ -0,0 +1 @@ +- The Twitch matrix streamer no longer drops frames on every encoder hiccup: `VIDEO_QUEUE_FRAMES` defaults to 256, the audio queue is configurable (`AUDIO_QUEUE`), x11grab uses wallclock timestamps with `aresample=async=1` so audio/video PTS cannot drift, and a stall watchdog restarts ffmpeg when frames stop for 30 s or `speed` stays below 0.90x for 60 s, publishing its samples to `/run/stream/health.json`; the README gains a "Why does the player buffer?" diagnosis recipe. diff --git a/changelog.d/fixed-tracker-mobile-chevron-height.md b/changelog.d/fixed-tracker-mobile-chevron-height.md new file mode 100644 index 0000000000..7aa1273c89 --- /dev/null +++ b/changelog.d/fixed-tracker-mobile-chevron-height.md @@ -0,0 +1 @@ +- Keep Activity tracker chevrons compact on mobile while preserving their caption and icon alignment. diff --git a/changelog.d/fixed-two-lit-chevrons.md b/changelog.d/fixed-two-lit-chevrons.md new file mode 100644 index 0000000000..55aa7aa9bf --- /dev/null +++ b/changelog.d/fixed-two-lit-chevrons.md @@ -0,0 +1 @@ +- Activity Monitor: a row never lights more than two chevrons, and a filled chevron now always means "this is where the item is / what is in motion". CI and Review are filled (amber) only while a check-run or a review perspective is actually running on the current head; passed / approved, findings, pending and decided verdicts are words in their colour on the muted field. Unreported checks and rows waiting on a person render as pending words, never amber. When both tracks run, the stage chevron is settled-current. A queued review swarm reads "Review 0/5 · swarm requested" instead of 5/5 (#16540). diff --git a/changelog.d/fixed-webhook-ci-counts.md b/changelog.d/fixed-webhook-ci-counts.md new file mode 100644 index 0000000000..5070ebf3dc --- /dev/null +++ b/changelog.d/fixed-webhook-ci-counts.md @@ -0,0 +1 @@ +- Activity Monitor CI chevron counts (`CI 7/11`) are now driven by `check_run`/`workflow_job`/`status` webhook deliveries applied straight into a per-head check set — no PR re-read per check fan-out — with one coalesced check-run listing only when the head has none yet, so rows no longer sit at `CI ?/?` after a push or for sidelined PRs until the next eval cycle; `/api/status.webhooks` gains `last_ci_event_at`, `ci_events_1h`, `ci_events_applied_1h`, `ci_refetches_1h` and the hub relays `workflow_run`/`workflow_job` (hivecommons/hive#16521) diff --git a/changelog.d/security-npm-transitives-proxy-discord.md b/changelog.d/security-npm-transitives-proxy-discord.md new file mode 100644 index 0000000000..e4d6e7a2bd --- /dev/null +++ b/changelog.d/security-npm-transitives-proxy-discord.md @@ -0,0 +1 @@ +- Bumped transitive `body-parser` to 2.4.0 and `qs` to 6.17.1 in `src/proxy/package-lock.json` (GHSA-27r3-jxmh-p828, GHSA-6pq8-jhm2-2vcw), matching what `dashboard/` already pins, and `undici` to 6.29.1 in `discord/package-lock.json` (GHSA-2m5v-pch6-74hx TLS option drop and four DoS advisories). `/discord` now has its own Dependabot npm entry so the directory gets the same weekly coverage as `/src/proxy` and `/dashboard`. diff --git a/changelog.d/security-pin-only-upstream-reachability.md b/changelog.d/security-pin-only-upstream-reachability.md new file mode 100644 index 0000000000..4d4147a699 --- /dev/null +++ b/changelog.d/security-pin-only-upstream-reachability.md @@ -0,0 +1 @@ +- The opt-in `auto_merge.human_merge_pin_only` exception now admits an `action-sha` pin only when the new SHA is anchored in its upstream action repository: with a `# vX[.Y[.Z]]` comment the upstream `tags/vX…` ref (annotated tags dereferenced) must point at exactly that SHA, otherwise the SHA must be an ancestor of the upstream default branch ([#16399](https://github.com/hivecommons/hive/issues/16399)). GitHub resolves a `uses:` SHA across the whole fork network, so a pin-shaped line could otherwise point at a commit pushed to any fork. Any 404, mismatch, rate limit or API error keeps the human-merge-path hold; repos without the key are unaffected. The pin-only commit check now uses the shared PR commit lister ([#16401](https://github.com/hivecommons/hive/issues/16401)). diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index d511a40ae0..bbfb4b88be 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -838,9 +838,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.22.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", + "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/src/Dockerfile b/src/Dockerfile index d40b7836d2..05b645c17b 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -326,7 +326,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.317 +ARG CLAUDE_CODE_VERSION=2.1.318 # --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 diff --git a/src/Dockerfile.contributor b/src/Dockerfile.contributor index f5498739cc..cbf0c3d628 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.317 +ARG CLAUDE_CODE_VERSION=2.1.318 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 diff --git a/src/cmd/hive/boot.go b/src/cmd/hive/boot.go index d1b81f85fb..513a723fa6 100644 --- a/src/cmd/hive/boot.go +++ b/src/cmd/hive/boot.go @@ -124,6 +124,7 @@ type boot struct { ghAuth githubAuth ghClient *github.Client appAuth *github.AppAuth + ciFailureKicker *ciFailureKicker gov *governor.Governor sched *scheduler.Scheduler notifier *notify.Notifier diff --git a/src/cmd/hive/boot_config_deps.go b/src/cmd/hive/boot_config_deps.go index f341e8fce5..14b8dcb834 100644 --- a/src/cmd/hive/boot_config_deps.go +++ b/src/cmd/hive/boot_config_deps.go @@ -65,6 +65,9 @@ type bootConfigDeps struct { runHub func(logger *slog.Logger, configPath string) // loadConfig is config.LoadWithDashboardOverlay. loadConfig func(path string) (*config.Config, error) + // gateRegressions compares the loaded config against the previous + // runtime overlays on the PVC (#16438); nil-returning in tests. + gateRegressions func(cfg *config.Config) []config.GateRegression // fileLogger builds the rolling-file logger from the loaded config. fileLogger func(cfg *config.Config) *slog.Logger // hiveID loads or generates the persistent hive identity. @@ -109,6 +112,9 @@ func defaultBootConfigDeps() bootConfigDeps { clearUpgradeMarker: func() error { return os.Remove(upgradeMarkerPath) }, runHub: runHub, loadConfig: config.LoadWithDashboardOverlay, + gateRegressions: func(cfg *config.Config) []config.GateRegression { + return config.DetectPriorOverlayGateRegressions(cfg, config.PriorOverlayPaths()) + }, fileLogger: func(cfg *config.Config) *slog.Logger { l := cfg.Governor.Logging return setupLogger(l.Dir, l.MaxSizeMB, l.MaxAgeDays, l.MaxBackups, l.Compress, l.Level) diff --git a/src/cmd/hive/boot_config_deps_test.go b/src/cmd/hive/boot_config_deps_test.go index f0a4dfaa85..fb80c1a7f6 100644 --- a/src/cmd/hive/boot_config_deps_test.go +++ b/src/cmd/hive/boot_config_deps_test.go @@ -82,6 +82,7 @@ func newBootConfigFake(t *testing.T) *bootConfigFake { cfg.Debug.PprofAddr = config.PprofAddrOff return cfg, nil }, + gateRegressions: func(*config.Config) []config.GateRegression { return nil }, // Every logger the phase installs is captured, including the stdout // bootstrap logger's replacement, so assertions see the whole boot. fileLogger: func(*config.Config) *slog.Logger { @@ -514,3 +515,63 @@ func TestBootConfigWith_HubModeNotGatedByProxyInjectGuard(t *testing.T) { t.Fatalf("returned=%v ok=%v code=%d hubRun=%v, want the hub started", returned, ok, code, f.hubRun) } } + +// #16438: a safety gate a previous runtime overlay carried that the effective +// config lacks is logged once per gate at WARN and kept on the config for +// /api/status; with config.refuse_gate_regression it is fatal, with its own +// exit code and the gates named in the log. +func TestBootConfigWith_GateRegressionWarnsOrRefuses(t *testing.T) { + regs := []config.GateRegression{ + {Gate: config.GateReviewRequireLabels, Previous: "[hive-review]", Effective: "none", Source: "/data/hive.yaml.runtime.bak"}, + {Gate: config.GatePausedRepos + "[acme/widgets]", Previous: "paused", Effective: "not paused", Source: "/data/hive.yaml.dashboard"}, + } + t.Run("warns and boots by default", func(t *testing.T) { + f := newBootConfigFake(t) + f.deps.gateRegressions = func(*config.Config) []config.GateRegression { return regs } + b := &boot{} + if returned, ok, code := runBootConfig(t, b, f.deps); !returned || !ok { + t.Fatalf("returned=%v ok=%v code=%d, want a normal boot", returned, ok, code) + } + log := f.log.String() + if n := strings.Count(log, "safety gate dropped"); n != len(regs) { + t.Fatalf("want %d 'safety gate dropped' lines, got %d:\n%s", len(regs), n, log) + } + for _, want := range []string{"review.require_labels", "[hive-review]", "acme/widgets", "level=WARN"} { + if !strings.Contains(log, want) { + t.Fatalf("gate warning lacks %q:\n%s", want, log) + } + } + if len(b.cfg.GateRegressions) != len(regs) { + t.Fatalf("cfg.GateRegressions = %v, want the detector's list", b.cfg.GateRegressions) + } + }) + t.Run("refuses when config.refuse_gate_regression is on", func(t *testing.T) { + f := newBootConfigFake(t) + load := f.deps.loadConfig + f.deps.loadConfig = func(p string) (*config.Config, error) { + cfg, err := load(p) + cfg.ConfigGuard.RefuseGateRegression = true + return cfg, err + } + f.deps.gateRegressions = func(*config.Config) []config.GateRegression { return regs } + returned, _, code := runBootConfig(t, &boot{}, f.deps) + if returned || code != gateRegressionExitCode { + t.Fatalf("returned=%v code=%d, want exit(%d)", returned, code, gateRegressionExitCode) + } + log := f.log.String() + for _, want := range []string{"refusing to start", "refuse_gate_regression", "review.require_labels", "acme/widgets"} { + if !strings.Contains(log, want) { + t.Fatalf("refusal log lacks %q:\n%s", want, log) + } + } + }) + t.Run("quiet when nothing regressed", func(t *testing.T) { + f := newBootConfigFake(t) + if returned, ok, code := runBootConfig(t, &boot{}, f.deps); !returned || !ok { + t.Fatalf("returned=%v ok=%v code=%d, want a normal boot", returned, ok, code) + } + if strings.Contains(f.log.String(), "safety gate dropped") { + t.Fatal("gate warning logged with no regressions") + } + }) +} diff --git a/src/cmd/hive/ci_failure_kick.go b/src/cmd/hive/ci_failure_kick.go index 1830316665..b98e168eba 100644 --- a/src/cmd/hive/ci_failure_kick.go +++ b/src/cmd/hive/ci_failure_kick.go @@ -5,6 +5,7 @@ import ( "errors" "log/slog" "strings" + "sync" "time" "github.com/hivecommons/hive/pkg/config" @@ -33,7 +34,7 @@ var errNoAgentRuntime = errors.New("agent runtime not available") // off the webhook goroutine so GitHub gets its 200 at once. type ciFailureKicker struct { cfg func() *config.Config - gov *governor.Governor + gov func() *governor.Governor isPaused func(agent string) bool message func(agent string, sig github.CIFailureSignal) string attribute func(repo string, number int) string @@ -42,12 +43,17 @@ type ciFailureKicker struct { ctx context.Context // spawn runs the kick delivery; tests swap in a synchronous runner. spawn func(func()) + + mu sync.Mutex + pending map[ciFailurePendingKey]*ciFailurePending + now func() time.Time + wait func(context.Context, time.Duration) bool } func (b *boot) newCIFailureKicker() *ciFailureKicker { k := &ciFailureKicker{ cfg: func() *config.Config { return b.cfg }, - gov: b.gov, + gov: func() *governor.Governor { return b.gov }, attribute: github.AuthorAgentForPR, logger: b.logger, ctx: b.ctx, @@ -73,8 +79,8 @@ func (b *boot) newCIFailureKicker() *ciFailureKicker { // ciFailureKickFunc is the dashboard.Dependencies.CIFailureKick hook. func (b *boot) ciFailureKickFunc() func(sig github.CIFailureSignal) dashboard.CIFailureKickOutcome { - k := b.newCIFailureKicker() - return k.React + b.ciFailureKicker = b.newCIFailureKicker() + return b.ciFailureKicker.React } // React decides and, when every gate passes, dispatches the kick. @@ -82,10 +88,6 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK if k == nil { return dashboard.CIFailureKickOutcome{Reason: "no kicker"} } - logger := k.logger - if logger == nil { - logger = slog.Default() - } cfg := k.cfg() if cfg == nil { return dashboard.CIFailureKickOutcome{Reason: "no config"} @@ -101,25 +103,8 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK agent = ciFailureKickDefaultAgent } out := dashboard.CIFailureKickOutcome{Agent: agent} - ac, ok := cfg.Agents[agent] - if !ok { - out.Reason = "unknown agent" - return out - } - if !ac.Enabled || ac.Paused { - out.Reason = "agent paused" - return out - } - if k.isPaused != nil && k.isPaused(agent) { - out.Reason = "agent paused" - return out - } - if cfg.IsRepoPaused(sig.Repo) { - out.Reason = "repo paused" - return out - } - if k.gov != nil && !k.gov.AgentEligibleForCELKick(agent) { - out.Reason = "governor gated" + if reason := k.gate(sig, agent); reason != "" { + out.Reason = reason return out } // Attribute before rendering so the fix-before-new builder lists the @@ -134,34 +119,54 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK out.Reason = "nothing to repair" return out } - if !github.CIFailureSignals().AllowKick(sig.Repo, sig.Number, sig.HeadSHA, cfg.CIFailureKickCooldown()) { - out.Reason = "cooldown" - return out - } if k.send == nil { out.Reason = "no kick sender" return out } + p, reason := k.reserve(sig, message) + if reason != "" { + out.Reason = reason + return out + } + if !github.CIFailureSignals().AllowKick(sig.Repo, sig.Number, sig.HeadSHA, cfg.CIFailureKickCooldown()) { + k.remove(p) + out.Reason = "cooldown" + return out + } out.Kicked = true - spawn := k.spawn - if spawn == nil { - spawn = func(fn func()) { go fn() } - } - spawn(func() { - parent := k.ctx - if parent == nil { - parent = context.Background() - } - ctx, cancel := context.WithTimeout(parent, ciFailureKickSendTimeout) - defer cancel() - if err := k.send(ctx, agent, message); err != nil { - logger.Warn("ci failure webhook kick failed", "agent", agent, "repo", sig.Repo, "number", sig.Number, "check", sig.Check, "error", err) - return - } - if k.gov != nil { - k.gov.RecordKickForRepo(agent, sig.Repo) - } - logger.Info("ci failure webhook kick delivered", "agent", agent, "repo", sig.Repo, "number", sig.Number, "check", sig.Check) - }) + k.dispatch(p, ciFailureKickImmediateAttempts) return out } + +// gate is rechecked before deferred delivery, so a queued kick never bypasses +// a pause, config change or governor budget gate that landed during backoff. +func (k *ciFailureKicker) gate(sig github.CIFailureSignal, agent string) string { + cfg := k.cfg() + if cfg == nil { + return "no config" + } + if !cfg.CIFailureWebhookKick() { + return "disabled" + } + ac, ok := cfg.Agents[agent] + if !ok { + return "unknown agent" + } + if !ac.Enabled || ac.Paused || (k.isPaused != nil && k.isPaused(agent)) { + return "agent paused" + } + if cfg.IsRepoPaused(sig.Repo) { + return "repo paused" + } + if gov := k.governor(); gov != nil && !gov.AgentEligibleForCELKick(agent) { + return "governor gated" + } + return "" +} + +func (k *ciFailureKicker) governor() *governor.Governor { + if k.gov != nil { + return k.gov() + } + return nil +} diff --git a/src/cmd/hive/ci_failure_kick_test.go b/src/cmd/hive/ci_failure_kick_test.go index 01106228f0..e687654921 100644 --- a/src/cmd/hive/ci_failure_kick_test.go +++ b/src/cmd/hive/ci_failure_kick_test.go @@ -21,9 +21,10 @@ func newCIFailureKickerForTest(t *testing.T, cfg *config.Config) (*ciFailureKick t.Helper() var sent []ciKickRecord logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + gov := governor.New(cfg.Governor, cfg.EnabledAgents(), logger) k := &ciFailureKicker{ cfg: func() *config.Config { return cfg }, - gov: governor.New(cfg.Governor, cfg.EnabledAgents(), logger), + gov: func() *governor.Governor { return gov }, attribute: func(repo string, number int) string { return "quality" }, message: func(agent string, sig github.CIFailureSignal) string { return "CI failed on " + sig.Repo + " for " + agent diff --git a/src/cmd/hive/ci_failure_pending.go b/src/cmd/hive/ci_failure_pending.go new file mode 100644 index 0000000000..b240d9f800 --- /dev/null +++ b/src/cmd/hive/ci_failure_pending.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "strings" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" +) + +const ( + ciFailureKickImmediateAttempts = 3 + ciFailureKickMaxAttempts = 6 + ciFailureKickMaxPending = 128 +) + +type ciFailurePendingKey struct { + repo, check string + number int +} + +type ciFailurePending struct { + key ciFailurePendingKey + sig github.CIFailureSignal + message string + attempts int + next time.Time + inFlight bool +} + +func (k *ciFailureKicker) reserve(sig github.CIFailureSignal, message string) (*ciFailurePending, string) { + key := ciFailurePendingKey{strings.ToLower(strings.TrimSpace(sig.Repo)), strings.TrimSpace(sig.Check), sig.Number} + k.mu.Lock() + defer k.mu.Unlock() + if k.pending == nil { + k.pending = make(map[ciFailurePendingKey]*ciFailurePending) + } + if prev := k.pending[key]; prev != nil && strings.EqualFold(prev.sig.HeadSHA, sig.HeadSHA) { + return nil, "pending" + } + if k.pending[key] == nil && len(k.pending) >= ciFailureKickMaxPending { + return nil, "pending queue full" + } + // A newer head replaces the old pending signal without growing the queue. + // The old worker checks pointer identity before attempting another send. + p := &ciFailurePending{key: key, sig: sig, message: message, inFlight: true} + k.pending[key] = p + return p, "" +} + +func (k *ciFailureKicker) remove(p *ciFailurePending) { + k.mu.Lock() + defer k.mu.Unlock() + if k.pending[p.key] == p { + delete(k.pending, p.key) + } +} + +func (k *ciFailureKicker) clock() time.Time { + if k.now != nil { + return k.now() + } + return time.Now() +} + +// Drain retries pending kicks once at the governor's next evaluation. It does +// no delivery IO on the evaluation goroutine and never runs a second worker +// for an entry already being delivered. Retries bypass the webhook cooldown: +// that cooldown was consumed by the original dispatch, not by a delivery. +func (k *ciFailureKicker) Drain() { + if k == nil { + return + } + now := k.clock() + k.mu.Lock() + var due []*ciFailurePending + for key, p := range k.pending { + if !ciFailureStillPending(p.sig) { + delete(k.pending, key) + continue + } + if !p.inFlight && !now.Before(p.next) { + p.inFlight = true + due = append(due, p) + } + } + k.mu.Unlock() + for _, p := range due { + k.dispatch(p, 1) + } +} + +func ciFailureStillPending(sig github.CIFailureSignal) bool { + for _, current := range github.CIFailureSignals().ForPR(sig.Repo, sig.Number) { + if strings.EqualFold(current.HeadSHA, sig.HeadSHA) && strings.TrimSpace(current.Check) == strings.TrimSpace(sig.Check) { + return true + } + } + return false +} + +func ciFailureKickBackoff(attempts int) time.Duration { + return time.Second << (attempts - 1) +} + +func (k *ciFailureKicker) dispatch(p *ciFailurePending, limit int) { + spawn := k.spawn + if spawn == nil { + spawn = func(fn func()) { go fn() } + } + spawn(func() { k.deliver(p, limit) }) +} + +func (k *ciFailureKicker) deliver(p *ciFailurePending, limit int) { + parent := k.ctx + if parent == nil { + parent = context.Background() + } + logger := k.logger + if logger == nil { + logger = slog.Default() + } + for i := 0; i < limit; i++ { + k.mu.Lock() + current := k.pending[p.key] == p + k.mu.Unlock() + if !current { + return + } + if parent.Err() != nil || (p.attempts > 0 && !ciFailureStillPending(p.sig)) { + k.remove(p) + return + } + if k.gate(p.sig, p.sig.Agent) != "" { + break + } + message := p.message + if p.attempts > 0 { + message = k.message(p.sig.Agent, p.sig) + } + if strings.TrimSpace(message) == "" { + k.remove(p) + return + } + p.attempts++ + // Bound each send separately: a busy runtime may spend the full + // prompt timeout before returning ErrAgentBusy. That must still + // leave room for retries unless the process context was cancelled. + ctx, cancel := context.WithTimeout(parent, ciFailureKickSendTimeout) + err := k.send(ctx, p.sig.Agent, message) + cancel() + if err == nil { + k.remove(p) + if gov := k.governor(); gov != nil { + gov.RecordKickForRepo(p.sig.Agent, p.sig.Repo) + } + logger.Info("ci failure webhook kick delivered", "agent", p.sig.Agent, "repo", p.sig.Repo, "number", p.sig.Number, "check", p.sig.Check, "attempts", p.attempts) + return + } + if parent.Err() != nil { + k.remove(p) + return + } + if !errors.Is(err, crux.ErrAgentBusy) || p.attempts >= ciFailureKickMaxAttempts { + k.remove(p) + logger.Warn("ci failure webhook kick failed", "agent", p.sig.Agent, "repo", p.sig.Repo, "number", p.sig.Number, "check", p.sig.Check, "attempts", p.attempts, "error", err) + return + } + if i+1 < limit && !k.waitBackoff(parent, ciFailureKickBackoff(p.attempts)) { + k.remove(p) + return + } + } + k.mu.Lock() + p.inFlight = false + p.next = k.clock().Add(ciFailureKickBackoff(max(1, p.attempts))) + k.mu.Unlock() +} + +func (k *ciFailureKicker) waitBackoff(ctx context.Context, delay time.Duration) bool { + if k.wait != nil { + return k.wait(ctx, delay) + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/src/cmd/hive/ci_failure_pending_test.go b/src/cmd/hive/ci_failure_pending_test.go new file mode 100644 index 0000000000..d23d9592c7 --- /dev/null +++ b/src/cmd/hive/ci_failure_pending_test.go @@ -0,0 +1,218 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" +) + +func pendingCIFailureTest(t *testing.T) (*ciFailureKicker, github.CIFailureSignal, *time.Time, *[]time.Duration) { + t.Helper() + now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetCIFailureSignalsForTest(func() time.Time { return now })) + k, _ := newCIFailureKickerForTest(t, ciKickTestConfig()) + k.now = func() time.Time { return now } + var delays []time.Duration + k.wait = func(_ context.Context, delay time.Duration) bool { + delays = append(delays, delay) + now = now.Add(delay) + return true + } + sig := github.CIFailureSignal{Repo: "acme/widgets", Number: 7, HeadSHA: "abc", Check: "build"} + github.CIFailureSignals().Record(sig) + return k, sig, &now, &delays +} + +func TestCIFailureKicker_BusyRetryAndPendingDedupe(t *testing.T) { + k, sig, now, delays := pendingCIFailureTest(t) + var logs bytes.Buffer + k.logger = slog.New(slog.NewTextHandler(&logs, nil)) + attempts, delivered := 0, 0 + busy := true + k.send = func(context.Context, string, string) error { + attempts++ + if busy { + return fmt.Errorf("prompt not reached: %w", crux.ErrAgentBusy) + } + delivered++ + return nil + } + if out := k.React(sig); !out.Kicked { + t.Fatalf("first dispatch: %+v", out) + } + if attempts != 3 || len(k.pending) != 1 || len(*delays) != 2 || (*delays)[0] != time.Second || (*delays)[1] != 2*time.Second { + t.Fatalf("attempts=%d pending=%d delays=%v", attempts, len(k.pending), *delays) + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" { + t.Fatalf("duplicate signal: %+v", out) + } + k.Drain() // backoff has not elapsed + if attempts != 3 { + t.Fatal("drain ignored backoff") + } + busy = false + *now = now.Add(4 * time.Second) + k.Drain() // same head is still inside the webhook's cooldown + k.Drain() + if attempts != 4 || delivered != 1 || len(k.pending) != 0 { + t.Fatalf("attempts=%d delivered=%d pending=%d", attempts, delivered, len(k.pending)) + } + if strings.Contains(logs.String(), "level=WARN") { + t.Fatalf("recoverable busy kick warned: %s", logs.String()) + } +} + +func TestCIFailureKicker_BusyFirstAttemptRecoversWithBackoff(t *testing.T) { + k, sig, _, delays := pendingCIFailureTest(t) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + if attempts == 1 { + return crux.ErrAgentBusy + } + return nil + } + k.React(sig) + if attempts != 2 || len(*delays) != 1 || (*delays)[0] != time.Second || len(k.pending) != 0 { + t.Fatalf("attempts=%d delays=%v pending=%d", attempts, *delays, len(k.pending)) + } +} + +func TestCIFailureKicker_PendingKeysIncludeRepoPRAndCheck(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + k.send = func(context.Context, string, string) error { return crux.ErrAgentBusy } + k.React(sig) + *now = now.Add(k.cfg().CIFailureKickCooldown() + time.Second) + otherCheck, otherPR, otherRepo := sig, sig, sig + otherCheck.Check = "lint" + otherPR.Number, otherPR.HeadSHA = 8, "def" + otherRepo.Repo = "acme/other" + for _, other := range []github.CIFailureSignal{otherCheck, otherPR, otherRepo} { + github.CIFailureSignals().Record(other) + if out := k.React(other); !out.Kicked { + t.Fatalf("distinct signal: %+v", out) + } + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" || len(k.pending) != 4 { + t.Fatalf("duplicate after cooldown: %+v pending=%d", out, len(k.pending)) + } + *now = now.Add(3 * time.Hour) + k.Drain() + if len(k.pending) != 0 { + t.Fatalf("expired signals retained: %d", len(k.pending)) + } +} + +func TestCIFailureKicker_ExhaustionWarnsOnce(t *testing.T) { + for _, busy := range []bool{false, true} { + t.Run(fmt.Sprintf("busy=%t", busy), func(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + var logs bytes.Buffer + k.logger = slog.New(slog.NewTextHandler(&logs, nil)) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + if busy { + return crux.ErrAgentBusy + } + return errors.New("pane gone") + } + k.React(sig) + for range ciFailureKickMaxAttempts + 2 { + *now = now.Add(time.Minute) + k.Drain() + } + want := 1 + if busy { + want = ciFailureKickMaxAttempts + } + if attempts != want || len(k.pending) != 0 || strings.Count(logs.String(), "level=WARN") != 1 || !strings.Contains(logs.String(), fmt.Sprintf("attempts=%d", want)) { + t.Fatalf("attempts=%d pending=%d logs=%s", attempts, len(k.pending), logs.String()) + } + }) + } +} + +func TestCIFailureKicker_DeferredGatesAndResolution(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + return crux.ErrAgentBusy + } + k.React(sig) + *now = now.Add(time.Minute) + k.isPaused = func(string) bool { return true } + k.Drain() + if attempts != 3 || len(k.pending) != 1 { + t.Fatalf("paused retry: attempts=%d pending=%d", attempts, len(k.pending)) + } + // The GitHub webhook/enrichment path forgets green and closed PRs. + github.CIFailureSignals().Forget(sig.Repo, sig.Number) + k.Drain() + if attempts != 3 || len(k.pending) != 0 { + t.Fatalf("resolved PR: attempts=%d pending=%d", attempts, len(k.pending)) + } +} + +func TestCIFailureKicker_PendingBoundAndInFlightDedupe(t *testing.T) { + k, sig, _, _ := pendingCIFailureTest(t) + var workers []func() + k.spawn = func(fn func()) { workers = append(workers, fn) } + for number := 1; number <= ciFailureKickMaxPending; number++ { + sig.Number = number + sig.HeadSHA = fmt.Sprintf("head-%d", number) + github.CIFailureSignals().Record(sig) + if out := k.React(sig); !out.Kicked { + t.Fatalf("entry %d: %+v", number, out) + } + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" { + t.Fatalf("in-flight duplicate: %+v", out) + } + sig.Number++ + if out := k.React(sig); out.Kicked || out.Reason != "pending queue full" { + t.Fatalf("overflow: %+v", out) + } + k.Drain() + if len(workers) != ciFailureKickMaxPending || len(k.pending) > ciFailureKickMaxPending { + t.Fatalf("workers=%d pending=%d", len(workers), len(k.pending)) + } + for _, worker := range workers { + worker() + } + if len(k.pending) != 0 { + t.Fatalf("pending after success=%d", len(k.pending)) + } +} + +func TestCIFailureKicker_CancelDuringBackoff(t *testing.T) { + k, sig, _, _ := pendingCIFailureTest(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + k.ctx = ctx + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + return crux.ErrAgentBusy + } + // Use the production timer helper after cancelling, without a real sleep. + k.wait = func(ctx context.Context, delay time.Duration) bool { + cancel() + k.wait = nil + return k.waitBackoff(ctx, delay) + } + k.React(sig) + k.Drain() + if attempts != 1 || len(k.pending) != 0 { + t.Fatalf("cancelled: attempts=%d pending=%d", attempts, len(k.pending)) + } +} diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index b77b28e51c..140d7bd587 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -246,6 +246,9 @@ func githubClaimHooksOn(queue *claimEffectQueue, ctx context.Context, cfg *confi } comment := cfg.Governor.Claims.CommentEnabled() label := cfg.Governor.Claims.LabelEnabled() + // The ledger folds every transition into one edited comment per issue + // (hivecommons/hive#16433); off, each transition is its own comment. + ledgerMode := cfg.GitHub.Notifications.ClaimLedgerEnabled() attempt := func(fn func(ctx context.Context, gh *github.Client) error, gh *github.Client) error { cctx, cancel := context.WithTimeout(ctx, claimsGitHubTimeout) defer cancel() @@ -270,13 +273,44 @@ func githubClaimHooksOn(queue *claimEffectQueue, ctx context.Context, cfg *confi logger.Warn("issue-claims: GitHub side effect failed", "what", what, "issue", c.Key(), "attempts", 1, "error", err) } } + // ledger edits the issue's claim ledger comment for event, posting the + // one notifying comment a human owed one gets. The edit is retried: a + // PATCH that lands twice is the same body, unlike a POST. + ledger := func(what string, event claims.LedgerEvent, notice func(previous string) string) { + run(what, event.Claim, func(ctx context.Context, gh *github.Client) error { + res, err := gh.EditIssueMarkerComment(ctx, event.Claim.Repo, event.Claim.Issue, claims.LedgerMarker, func(previous string) string { + return claims.LedgerComment(previous, event) + }) + if err != nil { + return err + } + if notice == nil || !res.Found { + // A freshly created ledger already notified: it carries the + // same @-mention the standalone comment did. + return nil + } + if body := notice(res.Previous); body != "" { + return gh.CreateIssueCommentBudgeted(ctx, event.Claim.Repo, event.Claim.Issue, body) + } + return nil + }) + } return claims.Hooks{ OnClaimed: func(c claims.Claim, outcome claims.Outcome) { queue.run(c.Key(), func() { if comment && outcome == claims.OutcomeClaimed { - runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) - }) + if ledgerMode { + ledger("claim ledger", claims.LedgerEvent{Claim: c, At: c.ClaimedAt}, func(previous string) string { + if claims.LedgerNotifiesHuman(previous, c) { + return claims.LedgerNoticeComment(c) + } + return "" + }) + } else { + runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) + }) + } } if label { // The stage is a fact for the engine (ADR-0025): a live @@ -301,9 +335,17 @@ func githubClaimHooksOn(queue *claimEffectQueue, ctx context.Context, cfg *confi OnTakenOver: func(now, previous claims.Claim) { queue.run(now.Key(), func() { if comment { - runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) - }) + if ledgerMode { + ledger("takeover ledger", claims.LedgerEvent{Claim: now, Previous: previous, At: now.ClaimedAt}, func(string) string { + // The displaced person must hear it; an edit + // tells them nothing. + return claims.LedgerDisplacedNotice(now, previous) + }) + } else { + runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) + }) + } } if label { run("claimed stage", now, func(ctx context.Context, gh *github.Client) error { @@ -350,8 +392,9 @@ func githubClaimHooksOn(queue *claimEffectQueue, ctx context.Context, cfg *confi }) } // Every early release needs a marker: the 🔒 comment is - // never edited, and issueclaim.Latest otherwise reads the - // hold as live until until=. This includes relay disconnect, + // never edited (the ledger rewrites it to carry the release + // marker instead), and issueclaim.Latest otherwise reads + // the hold as live until until=. This includes relay disconnect, // revoke and lease-expiry releases: omitting them starved // hive agents while relays flapped (hivecommons/hive#13579). // TTL expiry needs no marker: until= has already lapsed. @@ -361,9 +404,13 @@ func githubClaimHooksOn(queue *claimEffectQueue, ctx context.Context, cfg *confi // SetIssueClaimLedgerHive still prevents this hive from // believing its own stale hold. if comment && reason != claims.ReasonExpired { - runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) - }) + if ledgerMode { + ledger("release ledger", claims.LedgerEvent{Claim: c, Released: true, Reason: reason, At: time.Now()}, nil) + } else { + runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) + }) + } } }) }, diff --git a/src/cmd/hive/claimswire_budget_test.go b/src/cmd/hive/claimswire_budget_test.go index 5ea53c8100..9330810ad8 100644 --- a/src/cmd/hive/claimswire_budget_test.go +++ b/src/cmd/hive/claimswire_budget_test.go @@ -27,6 +27,11 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Run(name, func(t *testing.T) { posted := make(chan string, 1) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widgets/issues/7/comments" { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } if r.Method != http.MethodPost || r.URL.Path != "/repos/acme/widgets/issues/7/comments" { t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) http.NotFound(w, r) @@ -77,7 +82,7 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Fatalf("missing lease release marker: %s", body) } case message := <-failed: - if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release comment") { + if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release ledger") { t.Fatalf("unexpected hook failure: %s", message) } case <-time.After(5 * time.Second): diff --git a/src/cmd/hive/claimswire_relaunch_test.go b/src/cmd/hive/claimswire_relaunch_test.go index 253ac6e3fb..033c92ac7e 100644 --- a/src/cmd/hive/claimswire_relaunch_test.go +++ b/src/cmd/hive/claimswire_relaunch_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "io" "log/slog" "net/http" @@ -89,6 +90,11 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { _, _ = w.Write([]byte(`{"number":7,"labels":[{"name":"stage/020-claimed"},{"name":"hive/claimed-by-scanner"}]}`)) }) mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } body, _ := io.ReadAll(r.Body) mu.Lock() comments = append(comments, string(body)) @@ -125,3 +131,101 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { t.Fatalf("release comment:\n%s", got[0]) } } + +// With the claim ledger on (the default), an issue's claim, release and +// re-claim are one comment: the first claim creates it, every later +// transition PATCHes it, and the body always carries exactly one machine +// marker — the current state — above the history (hivecommons/hive#16433). +// With the ledger off, each transition is its own comment as before. +func TestClaimHooks_ClaimLedgerEditsOneCommentPerIssue(t *testing.T) { + for _, ledgerOn := range []bool{true, false} { + name := "ledger" + if !ledgerOn { + name = "legacy" + } + t.Run(name, func(t *testing.T) { + var mu sync.Mutex + var posted, edited []string + var existing []byte + mux := http.NewServeMux() + mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.Method == http.MethodGet { + if existing == nil { + _, _ = w.Write([]byte(`[]`)) + return + } + _, _ = w.Write([]byte(`[{"id":41,"body":` + string(existing) + `,"user":{"login":"hive[bot]"}}]`)) + return + } + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + posted = append(posted, body.Body) + existing, _ = json.Marshal(body.Body) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/repos/acme/widgets/issues/comments/41", func(w http.ResponseWriter, r *http.Request) { + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + edited = append(edited, body.Body) + existing, _ = json.Marshal(body.Body) + mu.Unlock() + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`[]`)) }) + srv := httptest.NewServer(mux) + defer srv.Close() + gh := github.NewClientForTest(srv.URL, "acme", []string{"widgets"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + gh.SetAppBotLogin("hive[bot]") + cfg := &config.Config{} + cfg.Governor.Claims.Label = boolPtr(false) + cfg.Governor.Claims.Comment = boolPtr(true) + cfg.GitHub.Notifications.ClaimLedger = boolPtr(ledgerOn) + hooks := githubClaimHooks(context.Background(), cfg, func() *github.Client { return gh }, nil) + at := time.Date(2026, 11, 3, 9, 0, 0, 0, time.UTC) + claim := claims.Claim{Repo: "acme/widgets", Issue: 7, Holder: "scanner", HolderID: "scanner", Kind: claims.KindAgent, ClaimedAt: at, ExpiresAt: at.Add(time.Hour)} + + hooks.OnClaimed(claim, claims.OutcomeClaimed) + hooks.OnReleased(claim, claims.ReasonHolderRelaunched) + claim.ClaimedAt = at.Add(2 * time.Minute) + hooks.OnClaimed(claim, claims.OutcomeClaimed) + wantPosted, wantEdited := 1, 2 + if !ledgerOn { + wantPosted, wantEdited = 3, 0 + } + testutil.Eventually(t, 5*time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return len(posted) == wantPosted && len(edited) == wantEdited + }, "claim transitions never settled") + mu.Lock() + defer mu.Unlock() + if len(posted) != wantPosted || len(edited) != wantEdited { + t.Fatalf("posted=%d edited=%d, want %d/%d", len(posted), len(edited), wantPosted, wantEdited) + } + if !ledgerOn { + return + } + if !strings.HasPrefix(posted[0], claims.LedgerMarker) || !strings.Contains(posted[0], "` comment. | Next un-park sweep. | Removes `stage/017-possible-existing`, appends a **Scope vs existing** section with `` to the issue body, records the un-park so the issue re-derives `stage/010-actionable` ([#13575](https://github.com/hivecommons/hive/issues/13575)). | | `/hive decision exists` | Agrees the request already exists. | Same as above. | Same as above. | Next un-park sweep. | Adds `already-exists`, closes the issue `not_planned`, replies with a pointer at the quoted findings. Reopen the issue to continue; the gate does not ask again. | diff --git a/src/docs/manual-provisioning.md b/src/docs/manual-provisioning.md index 63adec0f8e..fbf2ffb391 100644 --- a/src/docs/manual-provisioning.md +++ b/src/docs/manual-provisioning.md @@ -1832,17 +1832,17 @@ never changes: | Key | Kind | Holds | |---|---|---| -| `hive.kubestellar.io/hive-name` | label | The hive's display name (`ProjectName`), **sanitized** to a valid RFC-1123 label value. | -| `hive.kubestellar.io/org` | label | The hive's forge org, sanitized the same way. | -| `hive.kubestellar.io/hive-id` | label | The hive's internal `hive_id`, sanitized the same way. | -| `hive.kubestellar.io/display-name` | annotation | The **exact, unsanitized** hive name — the recoverable source of truth when the sanitized label value has been lossily transformed. | +| `hive.hivecommons.dev/hive-name` | label | The hive's display name (`ProjectName`), **sanitized** to a valid RFC-1123 label value. | +| `hive.hivecommons.dev/org` | label | The hive's forge org, sanitized the same way. | +| `hive.hivecommons.dev/hive-id` | label | The hive's internal `hive_id`, sanitized the same way. | +| `hive.hivecommons.dev/display-name` | annotation | The **exact, unsanitized** hive name — the recoverable source of truth when the sanitized label value has been lossily transformed. | **Sanitization**: label values are lower-cased, restricted to `[a-z0-9.-]` (everything else — spaces, underscores, unicode, punctuation — is dropped outright rather than transliterated), trimmed of leading/trailing separators, and capped at 63 characters (the RFC-1123 label-value limit). So a hive named `"TradingAsBuddies"` gets the label value `tradingasbuddies`, while the -`hive.kubestellar.io/display-name` annotation preserves the original +`hive.hivecommons.dev/display-name` annotation preserves the original `TradingAsBuddies` exactly. A field that sanitizes to empty (or wasn't set yet — e.g. a fresh placeholder with no real name/org) is **omitted** from the labels rather than written as an empty/invalid label. @@ -1851,14 +1851,14 @@ Given a hive name, find its namespace: ```bash kubectl --context get ns \ - -l hive.kubestellar.io/hive-name=tradingasbuddies + -l hive.hivecommons.dev/hive-name=tradingasbuddies ``` Given a namespace, find the hive that owns it: ```bash kubectl --context get ns hive-hosted-hosted-available--01-placeholder-bb95 \ - -o jsonpath='{.metadata.annotations.hive\.kubestellar\.io/display-name}' + -o jsonpath='{.metadata.annotations.hive\.hivecommons\.dev/display-name}' # -> TradingAsBuddies ``` @@ -1868,7 +1868,7 @@ known or changes, so the namespace never goes stale: 1. **Automatic provisioning** (`provisionHive`, Path A above) — stamps whatever is known at namespace-creation time. For a freshly-created pool - placeholder this is often just `hive.kubestellar.io/hive-id`, since + placeholder this is often just `hive.hivecommons.dev/hive-id`, since `org`/`name` are still placeholder values at this point. 2. **Claim** (`handleApproveProvision`) — the real name/org become known here for the first time, so the labels/annotation are (re)written. diff --git a/src/docs/notifications.md b/src/docs/notifications.md index ff798f4d64..38459f2b2a 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -581,6 +581,7 @@ without a class. Review submissions and review requests are always counted as | `github.(*Client).PostNoteOrFold` | `status` | passthrough wrapper; attributed to its caller | | `github.(*Client).SweepLegacyFleetReportIssues` | `status` | | | `github.(*Client).UpsertIssueMarkerComment` | `status` | passthrough wrapper; attributed to its caller | +| `github.(*Client).EditIssueMarkerComment` | `status` | passthrough wrapper; attributed to its caller | | `automerge.(*engineStatusForge).CreateComment` | `status` | passthrough wrapper shared by normal-mode stage notes and the quiet-mode status-comment forge under `prstatus.Write`; attributed to its caller | | `github.(*clientStatusForge).CreateComment` | `status` | passthrough wrapper (status-comment forge under `prstatus.Write`); attributed to its caller | | `github.(*Client).PostIssueNote` | `status` | passthrough wrapper (issue status card, `attention_pilot`); attributed to its caller | @@ -796,6 +797,15 @@ paths apply only where a card exists; with `github.notifications.attention_pilot` off there is no issue card, and the workflows behave as before. +A failure to read the card is not treated as "no card": when the comments +API call fails or its response is not a JSON list of comment objects, +`hive-status-card.sh` writes a `hive-status-card: error:` line and exits 3 +(`has` otherwise exits 0 for present, 1 for absent), and `upsert` writes +nothing. The refs sweep then skips that issue with an `::error::` annotation +and exits non-zero instead of posting a possible duplicate. +`.github/scripts/test-hive-status-card.sh` and +`src/scripts/test-comment-merged-refs.sh` pin this behaviour. + **Outside Hive's control.** Comments from external bots, such as Prow, tide and kubestellar-prow, are posted by their own services and cannot be edited, folded or skipped from this repository. Hive does not try to suppress them; diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 0b41f91933..2b57f739d5 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -123,6 +123,8 @@ The reference is organized into the sections below. Existing links to this page - [Knowledge: Context7 content caps](operator-reference/runtime-and-quota.md#knowledge-context7-content-caps) - [Inference endpoint fallbacks](operator-reference/runtime-and-quota.md#inference-endpoint-fallbacks) + +- [DCO provider unavailable on large forward merges](operator-reference/dco-provider-unavailable.md) - [v6 operator controls](operator-reference/v6-controls.md) @@ -135,5 +137,3 @@ The reference is organized into the sections below. Existing links to this page - [Red-main circuit breaker](operator-reference/v6-controls.md#red-main-circuit-breaker-red_main_threshold) - [Open held PR cap](operator-reference/v6-controls.md#open-held-pr-cap-max_open_held_prs) - -- [DCO provider unavailable on large forward merges](operator-reference/dco-provider-unavailable.md) diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index cf4378e32d..c8eec88283 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -266,9 +266,10 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `project.label_driven_trust_org_members` | `true` | Whether a public member of the repo's owning org who applies an approval label is trusted (Prow's own rule). Dashboard: Settings → Repos → "trust public org members". | | `project.label_driven_trusted_bots` | `["kubestellar-prow[bot]"]` | Bot logins whose label additions count as a trusted triager (Prow command bots relaying `/triage accepted`). `github-actions[bot]` is not in the default because it is the shared identity of every workflow in the repo, including ones triggered by untrusted events; operators whose Prow emulation runs as `github-actions[bot]` must add it explicitly per deployment. Dashboard: Settings → Repos → "Trusted bots". | | `project.label_driven_supersede_park_actors` | `[]` (off) | Automation logins (for example a lifecycle bot running as `github-actions[bot]`) whose park labels a later trusted acceptance supersedes on label-driven repos: Hive removes the label, says so in the release comment, and releases the issue ([#13605](https://github.com/hivecommons/hive/issues/13605)). Park labels added by people, by unlisted bots, or by a listed bot after the acceptance still block; `hold` is never superseded. Per-repo override: `project.repo_policies[].label_driven_supersede_park_actors`. | +| `config.refuse_gate_regression` | `false` | Safety-gate regression guard ([#16438](https://github.com/hivecommons/hive/issues/16438)). At boot the hive compares the effective config against any previous runtime overlay still on the PVC (`/data/hive.yaml.runtime`, an operator's `hive.yaml.runtime.bak`, `/data/hive.yaml.dashboard`) for `review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos` and `writeback.per_repo` modes. A gate the overlay carried that the effective config lacks or loosens — typically a boot from the ConfigMap seed after the overlay was moved aside — is logged once per gate as `WARN safety gate dropped: (was ) — effective config has `, listed in `/api/status` under `config.gate_regressions`, and shown as a banner at the top of Settings. `true` makes it fatal: the hive exits (code 21) with the gates named instead of running with weaker gates. Set it in the overlay itself; the ConfigMap seed is the file the regression usually comes from. Legacy `/data/hive.yaml.bak` is not consulted — it is frozen at the rename and would warn forever about gates removed on purpose. | | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | -| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, and whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature; it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | +| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | | `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge. Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. Details in the sweep key table below. | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | Title prefixes (after trimming) that mark a PR as a breaking change a person must merge. Every auto-merge lane and the merge train skip the PR; the tracker parks it at 090 *Ready for human merge · human merge*. Set to `[]` to disable. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive) that mark a PR a person must merge; same effect as the title prefixes. Set to `[]` to disable. | @@ -300,7 +301,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `dashboard.public_url` | Empty means OAuth redirect URIs (Linear agent install, OpenRouter funding) fall back to `hub.dashboard_url`, then the request's forwarded/`Host` origin. | Set to this dashboard's externally reachable origin (`https://hive.example.com`, no path/query) on a standalone hive whose callback is published on a different hostname or whose ingress rewrites `Host`. Must be an absolute `http(s)://` origin; a trailing slash is trimmed and anything else fails config load. See [linear-agent.md](../linear-agent.md#setup). | | `dashboard.experiment_lab` | Off by default. | Hides the Experiment Lab (formerly Strategy Lab) while that surface is being reworked. Set `dashboard.experiment_lab: true` to show the Experiment Lab section, sidebar nav entry, and Nous status controls. | | `dashboard.strategy_lab` | Off by default. **Deprecated** alias of `dashboard.experiment_lab`, kept for one release (#11695). | `true` still enables the Experiment Lab and logs a one-line deprecation at config load; the value is folded into `dashboard.experiment_lab` so the next config save writes the documented key. | -| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Opt-in Activity Monitor Matrix display block (#15862). When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≤1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | +| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Code activity source; see [Code activity reader](../dashboard.md#code-activity-reader) for presentation, compatibility, capture and access policies. When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≤1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | | `hub.contribute_announcement` | Empty/off by default. | Operator notice for contributors. Set from Governor → Hub or `/contribute` Management (owner/read-write): `text` is server-sanitised plain text capped at 500 characters and rendered only through text-safe sinks (empty clears), `level` is `info`/`warning`, `expires_at` is optional RFC3339, and the server rotates `id` whenever text changes so dismissed Operations/Profile banners reappear. Active notices show on `/contribute` Operations/Profile, above the Onboarding command block, and in connected relay terminals. | | `hub.contribute_repo_filters` | Empty map means repos inherit the hive-wide contributor title, author, and label filters exactly as before. | Optional full `owner/repo` keys that narrow one repository's `/contribute` queue without widening the hive. Hive-wide skip labels and hive-wide filters always run first; a repo filter can only add deny matches or require an allow-mode title/author/label match for that repo. Edit from `/contribute` → Management → Repos for Contribute → Filters or Governor → Hub. Operations lists configured overrides and withheld diagnostics name repo matches, e.g. `Repo filter label "2-discussing" denied for projectbluefin/common`. | | `hub.contribute_wall_enabled` | Off by default. | Opts the hive into the public contributor wall on `/contribute` Operations. The Management tab and Governor Hub settings mirror this switch. When off, the panel is hidden and write endpoints refuse posts. | @@ -568,7 +569,7 @@ auto_merge: | Repository key | Case-insensitive `owner/repo`; configure each consumer separately. | | `enabled` | Absent/false preserves the existing human-merge-path gate. | | `paths` | Explicit allowed paths within the protected path matches, not a replacement for `human_merge_paths`. Required when enabled. | -| `kinds` | Explicit subset of `action-sha`, `image-digest`, `version-pin`; unknown kinds rejected. Required when enabled. | +| `kinds` | Explicit subset of `action-sha`, `image-digest`, `version-pin`; unknown kinds rejected. Required when enabled. An `action-sha` pin is admitted only when the upstream repo's `tags/` (annotated tags dereferenced) points at the new SHA, or, without a comment, the SHA is an ancestor of the upstream default branch; any lookup failure holds. | | `trusted_authors` | Explicit author allowlist; required when enabled. Matched against the PR author login and against the author login of every commit behind the head; each commit must also be committed by GitHub (`web-flow`) or by a trusted login and carry a GitHub-verified signature, since GitHub verifies the committer, not the author (web-flow-committed bot commits qualify; human authors must commit and sign as themselves). Not permission to trust arbitrary bot-looking logins. | Edit the controller's active `hive.yaml` seed, not the consumer image repo. diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index 5097718c4f..e677e1b2e5 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -148,7 +148,9 @@ manage are ignored. webhook with the same secret works too). Subscribe the App to these events: `pull_request`, `pull_request_review`, `pull_request_review_comment`, `issue_comment`, `issues`, `check_suite`, `check_run`, `status`, `push`, - and, with `governor.work_source.type: github_projects`, `projects_v2_item` + optionally `workflow_job` (Actions: read; lets the CI counts on the + activity monitor move from the job payload for Apps that do not surface + check runs), and, with `governor.work_source.type: github_projects`, `projects_v2_item` (organization-scoped; see [Work sources](../work-sources.md#type-github_projects--github-projects-projects-v2)). 3. **Hub relay.** The hub verifies the HMAC and relays the body byte-for-byte, with the original signature and `X-GitHub-Delivery`, to the spoke whose @@ -171,8 +173,8 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. #### What a delivery does - `pull_request`, `pull_request_review`, `pull_request_review_comment`, - `check_suite`, `check_run`, `status`, `issue_comment` (on PRs only) and - `push` invalidate the cached PR detail and the GraphQL batch + `check_suite`, `check_run`, `workflow_job`, `status`, `issue_comment` (on + PRs only) and `push` invalidate the cached PR detail and the GraphQL batch check-run/review entries for the affected PR and mark it dirty. Check and status events are matched by PR number and head SHA (fork PRs arrive without a PR list); `push` invalidates every open PR whose base or head @@ -288,8 +290,7 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. `issues` — any action) also drops the `/api/stage-tracker` cache at once and queues a **targeted re-read of just that item**: one `GET` of the PR or issue, debounced by `dashboard.stage_tracker.webhook_refresh_debounce_ms` - (default `2000`) and coalesced per item, so a check fan-out of twenty - `check_run` deliveries costs one request. The re-read patches that row of + (default `2000`) and coalesced per item. The re-read patches that row of the status snapshot in place — labels, title, draft flag, last activity; a closed or merged item leaves — then drops the tracker cache again and sends the `stage-tracker` SSE nudge. The same re-read is handed to the @@ -318,6 +319,24 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. also lists each repo's items closed since its last look every `dashboard.stage_tracker.closed_sweep_interval_s` (default `300`; one list call per repo; negative disables) and evicts any still shown. +- **CI counts on the activity monitor move from the check payload.** A + `check_run`, `workflow_job` or `status` delivery is applied directly into + the per-head check set the tracker's CI chevron counts (`CI 7/11`): the + named check is upserted by run id (or check name and producing App), a + newer run replaces an older one, and the row is pushed over the + `stage-tracker` SSE nudge without any GitHub request — a fan-out of + twenty `check_run` deliveries costs zero requests. The payload-only + `check_run`/`status` delivery no longer queues the PR re-read above. + When no check-run listing exists yet for that head (first delivery after + a push, or a sidelined PR the eval cycle never enriched) one coalesced + listing of the head's check runs is scheduled instead (debounced by the + same `webhook_refresh_debounce_ms`), so the required-check set and the + `pass/total` denominator are right from the first row. The polling + path's `EnrichCIStatus` still refreshes every actionable PR each cycle + and is the backstop for spokes without webhooks. + `/api/status.webhooks.last_ci_event_at`, `ci_events_1h`, + `ci_events_applied_1h` and `ci_refetches_1h` show whether check + deliveries actually arrive and how many were served from the payload. #### Polling cadence vs webhook patch vs reconcile diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 430dfc3570..0091c4acf7 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -398,6 +398,7 @@ between. Two mechanisms close that gap |---|---|---| | `scanner.skip_issues_with_open_pr` | `true` (unset) | Set `false` to turn off both the pre-dispatch guard and the duplicate-fix sweep; the claim ledger alone then decides, as before. | | `governor.auto_close_superseded` | `true` (unset) | At ACMM L6, a **hive-authored** PR whose closing targets are all closed, one of them by a different merged PR, and whose head conflicts with the base (or whose files are a subset of that PR's) is closed by the hive itself as superseded — `hive/superseded`, one notice naming the superseding PR — in the self-authored auto-merge lane (before any review cycle), the supersession sweep, and close-on-merge of the superseding PR. Human-authored PRs are never auto-closed. Set `false` to report the refusal once and leave the PR for a person, as before ([#14965](https://github.com/hivecommons/hive/pull/14965)). See [labels-and-control-signals.md § Supersession](../labels-and-control-signals/stage-labels.md#supersession-closed-issue-another-merged-pr). | +| `governor.review.auto_decide_questions` | `true` (unset) | A review perspective that ends with a **question** rather than a finding used to park the PR at 085 "Needs human decision" on its wording alone. The dashboard now classifies the ask. **Policy sign-off** stays a person's: the PR edits `.github/workflows/*` or `.github/actions/*` from a fork; touches OWNERS / CODEOWNERS / SECURITY / rulesets / secrets / key material; adds or removes `auto_merge`, `human_merge_paths` or `self_authored_decision_policy` config; or the ask names an owner-only guard (sentinel, GitHub/App permissions, unauthorized, tokens / secrets / credentials, branch protection). **Scope / follow-up question** — "should we also…", "merge ahead of…", "apply X from the PR body", "confirm Y is acceptable" — on a hive-authored (or hive-adopted) PR with CI green and no unresolved finding on the head runs the existing *Let hive decide* pipeline with the hive as requester: an approve verdict admits the PR to the merge queue and files the question as a `follow-up: …` issue linked to the PR; a direction verdict routes the fixer (070); an owner-only or recommend-only verdict keeps the 085 park with the hive's recommendation on the row ("needs your sign-off"). At most one auto-decide per head (a new push asks again), one INFO line `reviewer question auto-decided` per run, and `review_questions_autodecided_1h` on `/api/status`. Set `false` to park every reviewer question for a person, as before. | ## What hive writes to GitHub, and when @@ -545,12 +546,19 @@ not what it records: The comment is created the first time a note is due and PATCHed for every later note; only the creation sends email. - **No "no findings" reviews.** A reviewer whose whole body is the clean - acknowledgement has its verdict recorded through the relay and the - evidence bundle, and no GitHub review is submitted (the reviewer prompts - also stop asking for the line, whatever `review.acknowledge_no_findings` - says). Only perspectives with findings post, and a head carries at most - one hive review: a later perspective's findings for the same head are - folded into the status comment instead of becoming a second review. + acknowledgement — or whose body says it has no findings while its verdict + report approves with an empty findings list, as the plain `reviewer` + lanes narrate ("Read the tree at … Looks correct to me. No findings.") — + has its verdict recorded through the relay and the evidence bundle, and + no GitHub review is submitted (the reviewer prompts also stop asking for + the line, whatever `review.acknowledge_no_findings` says). The verdict + and the reviewer's notes land in the status comment as a + `review-findings:` section instead. A body that asks for a + decision, carries a hive marker, or rides a non-approving verdict is a + real review and still posts. Only perspectives with findings post, and a + head carries at most one hive review: a later perspective's findings for + the same head are folded into the status comment instead of becoming a + second review. - **@-mentions once per cause.** The 071 note mentions the author the first time a cause class appears (conflict, red CI, changes requested) and is silent for further heads with the same cause; a new cause mentions again. @@ -592,6 +600,59 @@ already present), so the effect of the mode can be charted from the logs. `normal` restores the previous behaviour: every note is its own comment, every perspective's verdict its own review, every new head its own mention. +Three issue-side comments are edited in place in either mode, because a +re-post never carried information the previous comment lacked: + +- **Needs-decision entry** (`` and the + other stage entry markers): a PR that re-enters the stage after a decision + cycle has its existing entry comment rewritten, with an `Updated ` + line, instead of receiving a new one. Only the hive's own comment is + reused; a stranger's comment carrying the marker is ignored. +- **Sentinel alert** (` `): a new push rewrites + the hive's existing sentinel comment for the new head rather than + stamping the PR again. The label is what blocks; one explanation per PR + is enough. A hive that cannot verify its own account (no App login and + no resolvable identity) still posts a fresh comment rather than edit a + comment the PR author may have forged. +- **Claim ledger** (`github.notifications.claim_ledger`, default `true`): + see below. + +### Claim ledger (`github.notifications.claim_ledger`) + +**Why:** every `hive:claim` and `hive:release` the fleet posted was a new +comment, and a relaunch or lease revocation appends a release+claim pair +each time. Over 48 hours that was 334 comments — a quarter of everything +the hive wrote — on issues whose holder, as far as a reader cared, had not +changed. + +```yaml +github: + notifications: + claim_ledger: true # default; false restores one comment per claim/release +``` + +With the ledger on, an issue carries **one** claim comment marked +`` that is PATCHed on every transition. It +shows the current state — the same `hive:claim` / `hive:release` / +`hive:preempt` machine marker and text the separate comments carried — and +a collapsed `Claim history` list of the last 8 transitions (timestamp, +agent, kind, release reason). The first claim on an issue creates the +comment; later claims, takeovers and releases edit it, and only the +creation sends email. + +The ledger is written so that every reader of the old comments keeps +working without change: it carries exactly one machine marker, for the +current state, so `issueclaim.Latest` (claim recovery after a restart, the +`claimed-by` label sweep, the contributor lane's "is it free" check and the +dashboard's claims view) reads the ledger the way it read the newest +separate comment. A legacy claim comment on the same issue is superseded +by the ledger's later `at=` the same way a later comment superseded it. + +A human is still told, in a fresh comment, the two things only a new +comment can tell them: that an agent took over an issue they held, and +that they displaced an agent (so they know to drop the `claimed-by` label +when done). Everything else goes into the ledger. + `github.notifications.shadow: true` (default off) adds would-notify instrumentation without changing any write: every new comment, review, review request and @-mention is classified by producer and class, repeats of diff --git a/src/docs/review-swarm.md b/src/docs/review-swarm.md index aeab5f1299..685060cdab 100644 --- a/src/docs/review-swarm.md +++ b/src/docs/review-swarm.md @@ -182,6 +182,8 @@ review: max_parallel_reviews: 5 reviewer_agents: [reviewer-a, reviewer-b] # optional; otherwise agents with review role/keywords are selected fixer_agent: scanner # optional; defaults to the PR lane, then scanner + fixer_fallback_agents: [] # opt-in ordered fallback lanes, e.g. [fixer, scanner-2] + fixer_fallback_after_undeliverable: 3 # 0 defaults to 3 only when fallbacks are configured confidence_score: true # optional; append the 0–5 mergeability line to review comments self_authored_decision_policy: resolve # resolve (default) non-risk-class Hive-authored decision questions, or escalate all of them # all_authors: true # deprecated no-op; every open PR is reviewed regardless of author @@ -576,7 +578,13 @@ Expiry also covers a head whose aggregate is `incomplete`: the delivered perspec The PR review queue (`GET /api/review/queue`) shows this state on unreviewed items: `pending_since` (first dispatch for the current head still pending) and `redispatch_count`, plus a reason such as `review dispatched 32m ago, no verdict yet (re-dispatched 2x after expiry)` or `review dispatch exhausted: …; waiting on a human` after the generic `not reviewed at this head` line. -When an aggregate verdict is `changes_requested`, Hive builds a review-fix kick containing the aggregate findings and sends it to `review.fixer_agent`, the classified PR lane, or `scanner`. Fix dispatches are capped by `escalation.MaxReEngagements`; once exhausted, dispatch state records a `requires_human` hold for the PR head so the automated loop stops. +When an aggregate verdict is `changes_requested`, Hive builds a review-fix kick containing the aggregate findings and sends it to `review.fixer_agent`, the classified PR lane, or `scanner`. + +Set `review.fixer_fallback_agents` to an ordered list of enabled, kick-capable repair agents to route around an undeliverable fixer. An empty or unset list preserves existing behavior; setting `review.fixer_fallback_after_undeliverable` alone has no effect. With the list set, a candidate yields after that many consecutive undeliverable kicks (default 3), or after at least one refusal when its last known transcript activity is older than its agent-level `busy_no_activity_threshold` (default 30m). Missing transcript activity is unknown, and an idle agent with no outstanding refusals does not yield merely because its transcript is old. + +Both review-fix kicks and stale CI-red PR re-engagements retain their existing owner/fixer selection order, then try the configured fallback list in order. Paused, disabled, on-demand, non-kick, cadence-paused, provider-backed-off or already refusing fallback agents are skipped. Routing is logged, and the next repair returns to the primary once its refusal count clears. No turn is interrupted or restarted, and a fix already delivered to a fallback remains pending under the usual `pending_fix_ttl` rather than being dispatched twice. + +Fix dispatches are capped by `escalation.MaxReEngagements`; once exhausted, dispatch state records a `requires_human` hold for the PR head so the automated loop stops. Once that cap is hit the hive is no longer fixing the PR, and the stage must say so ([#15744](https://github.com/hivecommons/hive/issues/15744)): diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 1f07ab9dc2..89557b364d 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`src/pkg/github/client.go:5277-5285`, where `RankActionableIssues` sorts by descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5314-5324`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index 41272618ab..c7dd5a8cde 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -95,7 +95,7 @@ apply the overlay — the steps below are all yours to run. ### Call-to-action overlay -Every kiosk view — this stream's Activity Monitor, the [Matrix](#matrix-mode-separate-channel) +Every kiosk view — this stream's Activity Monitor, [Code activity](#code-activity-separate-channel) and the hub's [public fleet page](#the-hivecommonsfleet-broadcast) — carries a small pill bottom-right: "🐝 Want this for your repos?", the URL `hive.hivecommons.dev/get-started` in 24px amber, and a 110px QR code of it, so @@ -107,8 +107,8 @@ spoke the destination and the copy are `dashboard.kiosk_cta_url` and are `HIVE_HUB_KIOSK_CTA_URL` and `HIVE_HUB_KIOSK_CTA_TEXT`. The QR code is rendered server-side (`src/pkg/webassets/kioskcta`) as an inline `data:` PNG, so nothing external is loaded and the pages' Content-Security-Policy is unchanged. -In Matrix mode the pill sits above the canvas at 85 % opacity so it does not -fight the effect. +In Code activity the pill sits above the reader at 85 % opacity so it does not +obscure the code. ### Channel title, category, tags @@ -291,51 +291,22 @@ with the same ↑/↓ delta cue), enlarged in kiosk, pop-out, display and full-s views so it reads at 1920×1080. Do not point the streamer at a hive tracking private repositories without reviewing what the tracker would show. -The main `twitch.tv/hivecommons` stream never shows Matrix; it remains the +The main `twitch.tv/hivecommons` stream never shows Code activity; it remains the full-screen Activity Monitor. -## Matrix mode (separate channel) - -When `dashboard.matrix.enabled` is set, the Activity Monitor header also shows a **Matrix** tab that opens `?kiosk=1&view=matrix` in the same window. - -Matrix is an experimental, default-off code display for a separate channel, -[`twitch.tv/hivecommonsmatrix`](https://www.twitch.tv/hivecommonsmatrix). -It depends on the Matrix display renderer (`/?kiosk=1&view=matrix`, -[#15936](https://github.com/hivecommons/hive/issues/15936)); without that -renderer the dashboard ignores `view=matrix` and the kiosk serves the ordinary -Activity Monitor. When active it shows pushed added lines only, from positively -identified hive identities, on public repositories explicitly allowlisted in -`dashboard.matrix.repos`. -Private patches, unverified authors and excluded paths are never shown. Lines -touched by scrubbing are dropped entirely rather than displayed with redactions; -the built-in secret/path filters and `dashboard.matrix.exclude_paths` apply. -Dashboard authentication alone does not make a code stream safe for public -Twitch broadcasting: the public allowlist, author restriction and scrub/drop -rules are required. - -The display's look is chosen with `mx.*` URL parameters; each value is also -remembered in the browser (`hive.matrix.*` in local storage) for later visits. -Every effect renders only lines already delivered by `/api/matrix/lines`. - -| `mx.effect` | Display | -|---|---| -| `rain` (default) | Falling columns built from the characters of the latest lines. Unknown values fall back to `rain`. | -| `cascade` | Whole lines drift down the screen, each with its `repo#PR · path` caption. | -| `ghost` | Ghost coder: a fake editor with one tab per PR (`repo#PR`), titled with the file path; at most six tabs, the oldest closes first. Lines are typed character by character behind a blinking cursor, with light keyword/string/comment/number colouring by file extension. | -| `terminal` | An endless `git log -p`-style scroll: each line printed as a green `+ `, with a `repo#PR · path` header whenever the PR or file changes. | - -`mx.speed` (0.1–5, default 1) and `mx.fps` (1–60, default 30) set the -animation and typing speed, `mx.palette` is `green` (default), `amber` or -`gold`, and `mx.captions=off` hides the `repo#PR · path` captions and headers -on the canvas. `p` or Space pauses; a hidden tab pauses too. With the -operating system's *reduce motion* setting on, every effect is replaced by -static pages of the latest lines with their captions. +## Code activity (separate channel) + +The separate Code activity channel uses the +[Code activity reader](dashboard.md#code-activity-reader); see that section for +its display, source restrictions, compatibility and access policy. +Dashboard authentication alone does not authorize broadcasting. [`overlays/hive-hosted-matrix/`](../deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml) reuses the streamer image and base as a separate instance. It renders Deployment, ConfigMap and NetworkPolicy `matrix-hive-stream` in namespace `hive-stream-matrix`, with separate pod selectors and secret references scoped to that namespace. -It opens `/?kiosk=1&view=matrix&sound=off` and sets `STREAM_AUDIO=silent`. +It opens `/?kiosk=1&view=matrix&sound=off` (the deprecated alias, which now +shows Code activity) and sets `STREAM_AUDIO=silent`. Its independent process and deployment isolate restarts and failures from the existing stream. The `hive-hosted` overlay and `twitch.tv/hivecommons` are unaffected. @@ -344,11 +315,11 @@ unaffected. channel.** The overlay has `replicas: 0`; applying it starts no streamer. Channel availability alone does not authorize activation. The owner must: -1. Confirm the deployed dashboard build serves the Matrix display for - `view=matrix` (#15936). A build without it broadcasts the ordinary kiosk - Activity Monitor on the Matrix channel, not code lines. +1. Confirm the deployed dashboard build serves Code activity for + `view=matrix` (the alias the overlay opens) and `view=reader`. A build without it broadcasts the ordinary kiosk + Activity Monitor on the separate channel, not code changes. 2. Enable `dashboard.matrix` with an explicit, reviewed public repo allowlist - and verify the Matrix display and its author restriction and scrub/drop rules + and verify Code activity and its author restriction and scrub/drop rules before any broadcast. An empty allowlist captures nothing. 3. Provision `hivecommonsmatrix` independently, create namespace `hive-stream-matrix`, and create the out-of-band diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 655aae1f58..3cee013b92 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -1005,6 +1005,11 @@ governor: # # perspective; shared review boilerplate is sent once instead of once # # per perspective. Verdicts stay per-perspective. Default false. # fixer_agent: "" # optional override; defaults to the PR lane, then scanner +# fixer_fallback_agents: [] # opt-in ordered repair lanes, e.g. [fixer, scanner-2] +# fixer_fallback_after_undeliverable: 3 # consecutive refusals before rerouting; +# # 0 defaults to 3 only when the fallback list is non-empty. +# # A busy fixer silent past its busy_no_activity_threshold +# # (default 30m) also yields. No turn is interrupted. # pending_ttl: 45m # re-dispatch a review whose kick posted no verdict after this long # # (Go duration; default 45m; negative disables expiry) # pending_fix_ttl: 2h # dispatch the next bounded fix attempt when a fixer turn has diff --git a/src/pkg/claims/ledger_comment.go b/src/pkg/claims/ledger_comment.go new file mode 100644 index 0000000000..daf45567db --- /dev/null +++ b/src/pkg/claims/ledger_comment.go @@ -0,0 +1,233 @@ +package claims + +import ( + "fmt" + "regexp" + "strings" + "time" +) + +// The claim ledger is the one comment per issue that records who holds it. +// Before it existed every claim, takeover and release was its own comment, +// and a relaunch/revoke cycle appended a fresh release+claim pair each time +// (334 comments in 48h, a quarter of the hive's output). The ledger is +// edited in place instead: editing notifies nobody, while the facts stay on +// the issue. +// +// Compatibility with marker readers (pkg/issueclaim.Latest, the dashboard's +// contribute claims view, the contributor lane) rests on two rules: +// +// - the ledger body carries EXACTLY ONE machine-readable marker for the +// current state — a `hive:claim` marker while held, a `hive:release` +// marker once released — so a reader that scans comment bodies sees the +// same thing it saw when each transition was its own comment; +// - the history lines never contain a marker prefix, and LedgerMarker +// itself does not start with `" + // LedgerHistoryLimit is how many transitions the ledger keeps. + LedgerHistoryLimit = 8 + + ledgerHistoryOpen = "
Claim history" + ledgerHistoryClose = "
" + ledgerLinePrefix = "- " +) + +// LedgerEvent is one transition the ledger records. +type LedgerEvent struct { + // Claim is the claim the event concerns: the new holder for a claim or + // takeover, the released holder for a release. + Claim Claim + // Previous is the displaced holder on a takeover; zero otherwise. + Previous Claim + // Released is set for a release; Reason is its reason. + Released bool + Reason string + // At is when the transition happened. + At time.Time +} + +// LedgerComment renders the ledger body after event, given the body of the +// existing ledger comment (empty when the issue has none yet). The current +// state is rendered exactly as the standalone claim / takeover / release +// comment used to be, so the marker a reader finds is unchanged; the history +// below it keeps the last LedgerHistoryLimit transitions, oldest first. +func LedgerComment(previous string, event LedgerEvent) string { + if event.At.IsZero() { + event.At = time.Now() + } + history := ParseLedgerHistory(previous) + history = append(history, ledgerHistoryLine(event)) + if len(history) > LedgerHistoryLimit { + history = history[len(history)-LedgerHistoryLimit:] + } + var b strings.Builder + b.WriteString(LedgerMarker) + b.WriteString("\n") + switch { + case event.Released: + // The release prose quotes the reason verbatim; a reason that smuggles + // a marker opener in would hand the ledger a second machine marker. + b.WriteString(releaseCommentAt(event.Claim, strings.ReplaceAll(event.Reason, "", At: t0.Add(time.Minute)}) + if n := strings.Count(body, issueclaim.MarkerPrefix); n != 0 { + t.Fatalf("history must not carry a claim marker prefix: %q", body) + } + now := ledgerTestClaim("alice", KindHuman, t0.Add(2*time.Minute)) + body = LedgerComment(body, LedgerEvent{Claim: now, Previous: prev, At: now.ClaimedAt}) + if !strings.Contains(body, "`) that every claim, takeover and + // release edits in place, instead of posting a fresh `hive:claim` / + // `hive:release` comment per transition (hivecommons/hive#16433). A + // human holder the ledger has not named before still gets one notifying + // comment. Default on; `claim_ledger: false` restores a comment per + // transition. + ClaimLedger *bool `yaml:"claim_ledger,omitempty" json:"claim_ledger,omitempty"` +} + +// ClaimLedgerEnabled resolves ClaimLedger with its default (on). +func (c GitHubNotificationsConfig) ClaimLedgerEnabled() bool { + return c.ClaimLedger == nil || *c.ClaimLedger } // Quiet reports whether the hive should fold its PR notes into one edited diff --git a/src/pkg/config/governor_config.go b/src/pkg/config/governor_config.go index 5fea007eca..0fe5fa61ec 100644 --- a/src/pkg/config/governor_config.go +++ b/src/pkg/config/governor_config.go @@ -142,6 +142,10 @@ type GovernorConfig struct { // different merged PR. A person's PR still needs their decision. AutoCloseSuperseded *bool `yaml:"auto_close_superseded,omitempty" json:"auto_close_superseded,omitempty"` + // Review tunes what the governor does with the review swarm's verdicts + // on the hive's own PRs. See GovernorReviewConfig. + Review GovernorReviewConfig `yaml:"review,omitempty" json:"review,omitempty"` + // Hotspot* tune the merge-hotspot advisor. Zero values use the defaults; // disabling issues keeps reporting enabled without filing on GitHub. HotspotEnabled *bool `yaml:"hotspot_enabled,omitempty" json:"hotspot_enabled,omitempty"` @@ -1038,3 +1042,24 @@ func (c StageAdoptionConfig) EffectiveCloseSuperseded() string { } return DefaultAdoptionCloseSuperseded } + +// GovernorReviewConfig is governor.review: how the governor treats the +// review swarm's verdicts on hive-authored PRs. +type GovernorReviewConfig struct { + // AutoDecideQuestions lets the hive answer a reviewer's scope or + // follow-up QUESTION on its own green, finding-free PR through the + // delegated-decision path instead of parking the PR at stage/085 for a + // person (hivecommons/docs#618: "this is auto-merge material, not + // needs-human"). Policy sign-off asks — workflow edits from a fork, + // secrets / permissions / OWNERS / security paths, auto_merge or + // human_merge_paths changes, an explicit owner-only guard in the ask — + // still park. At most one auto-decision per head; a new push re-asks. + // Default on. See review.ClassifyDecisionQuestion for the two classes. + AutoDecideQuestions *bool `yaml:"auto_decide_questions,omitempty" json:"auto_decide_questions,omitempty"` +} + +// AutoDecideQuestionsEnabled resolves GovernorReviewConfig.AutoDecideQuestions +// with its default (on). +func (r GovernorReviewConfig) AutoDecideQuestionsEnabled() bool { + return r.AutoDecideQuestions == nil || *r.AutoDecideQuestions +} diff --git a/src/pkg/config/review_config.go b/src/pkg/config/review_config.go index 3ee07bd180..82966f2f9a 100644 --- a/src/pkg/config/review_config.go +++ b/src/pkg/config/review_config.go @@ -108,6 +108,12 @@ type ReviewConfig struct { MaxParallelReviews int `yaml:"max_parallel_reviews,omitempty" json:"max_parallel_reviews,omitempty"` ReviewerAgents []string `yaml:"reviewer_agents,omitempty" json:"reviewer_agents,omitempty"` FixerAgent string `yaml:"fixer_agent,omitempty" json:"fixer_agent,omitempty"` + // FixerFallbackAgents opts into routing repairs around an undeliverable + // fixer, in list order. Empty preserves the historical delivery behavior. + FixerFallbackAgents []string `yaml:"fixer_fallback_agents,omitempty" json:"fixer_fallback_agents,omitempty"` + // FixerFallbackAfterUndeliverable is the consecutive refusal threshold; + // zero uses 3, only when FixerFallbackAgents is non-empty. + FixerFallbackAfterUndeliverable int `yaml:"fixer_fallback_after_undeliverable,omitempty" json:"fixer_fallback_after_undeliverable,omitempty"` // Severity controls which review findings block vs. comment/backlog. Severity ReviewSeverityConfig `yaml:"severity,omitempty" json:"severity,omitempty"` // Backlog controls where non-blocking review findings are filed. diff --git a/src/pkg/config/review_dispatch.go b/src/pkg/config/review_dispatch.go index f793e81967..08a3373cfa 100644 --- a/src/pkg/config/review_dispatch.go +++ b/src/pkg/config/review_dispatch.go @@ -237,3 +237,27 @@ func (r ReviewConfig) ValidateDeltaMaxAge() error { } return nil } + +// EffectiveFixerFallbackAfterUndeliverable is zero while fallback routing is +// disabled, so setting a threshold alone cannot change existing behavior. +func (r ReviewConfig) EffectiveFixerFallbackAfterUndeliverable() int { + if len(r.EffectiveFixerFallbackAgents()) == 0 { + return 0 + } + if r.FixerFallbackAfterUndeliverable > 0 { + return r.FixerFallbackAfterUndeliverable + } + return 3 +} + +// EffectiveFixerFallbackAgents returns the ordered, non-empty agent names. +func (r ReviewConfig) EffectiveFixerFallbackAgents() []string { + return trimmedNonEmpty(r.FixerFallbackAgents) +} + +func (r ReviewConfig) ValidateFixerFallback() error { + if r.FixerFallbackAfterUndeliverable < 0 { + return fmt.Errorf("review: fixer_fallback_after_undeliverable must be >= 0") + } + return nil +} diff --git a/src/pkg/config/review_dispatch_test.go b/src/pkg/config/review_dispatch_test.go index a1e9f0e841..f35c88e7f6 100644 --- a/src/pkg/config/review_dispatch_test.go +++ b/src/pkg/config/review_dispatch_test.go @@ -205,3 +205,25 @@ func TestReviewDeltaRereviewConfig(t *testing.T) { t.Fatalf("ValidateDeltaMaxAge rejected unset: %v", err) } } + +func TestReviewFixerFallbackConfig(t *testing.T) { + r := ReviewConfig{FixerFallbackAfterUndeliverable: 2} + if r.EffectiveFixerFallbackAfterUndeliverable() != 0 { + t.Fatal("threshold alone enabled fallback routing") + } + r.FixerFallbackAgents = []string{" ", " fixer "} + if got := r.EffectiveFixerFallbackAgents(); len(got) != 1 || got[0] != "fixer" { + t.Fatalf("fallback names = %v", got) + } + if r.EffectiveFixerFallbackAfterUndeliverable() != 2 { + t.Fatal("explicit threshold was not used") + } + r.FixerFallbackAfterUndeliverable = 0 + if r.EffectiveFixerFallbackAfterUndeliverable() != 3 { + t.Fatal("opted-in default must be three refusals") + } + r.FixerFallbackAfterUndeliverable = -1 + if r.ValidateFixerFallback() == nil { + t.Fatal("negative threshold accepted") + } +} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 9c2b6a6b76..0055318195 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -400,6 +400,7 @@ "queue_health": {} }, "auto_close_superseded": true, + "review": {}, "project_observability": {}, "work_source": { "type": "", @@ -825,5 +826,6 @@ "classification": { "review_bots": {} }, - "task_mcp": {} + "task_mcp": {}, + "config": {} } diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index e931f8ff51..47abec30f8 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -206,6 +206,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.Hub.ValidateNPS(); err != nil { return err } + if err := c.Review.ValidateFixerFallback(); err != nil { + return err + } if err := c.Review.ValidateReviewEventDispatch(); err != nil { return err } diff --git a/src/pkg/dashboard/api_checkpoint.go b/src/pkg/dashboard/api_checkpoint.go new file mode 100644 index 0000000000..8c4a0aa65b --- /dev/null +++ b/src/pkg/dashboard/api_checkpoint.go @@ -0,0 +1,35 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strconv" +) + +// handleCheckpointRegions runs behind handleMatrixLines' existing read gate. +// Initializing the memory-only projection here gives an enabled cold source a +// truthful empty 200, without waiting for or initiating a sentinel pass. +func (s *Server) handleCheckpointRegions(w http.ResponseWriter, r *http.Request) { + s.MatrixObserver(s.currentMatrixConfig()) + src, cfg := s.matrixActiveSource() + if src == nil || cfg == nil { + jsonError(w, "matrix mode disabled", http.StatusNotFound) + return + } + since, _ := strconv.ParseUint(r.URL.Query().Get("since"), 10, 64) + limit := matrixDefaultSinceMax + if r.URL.Query().Has("max") { + n, err := strconv.Atoi(r.URL.Query().Get("max")) + if err != nil || n < matrixMinSinceMax { + n = matrixMinSinceMax + } + limit = min(n, matrixMaxSinceMax) + } + resp := src.checkpoints.since(since, limit) + if last, next := src.ingestStatus(src.now()); !last.IsZero() { + resp.LastIngestAt = &last + resp.NextIngestInS = next + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} diff --git a/src/pkg/dashboard/api_config_review.go b/src/pkg/dashboard/api_config_review.go index 84f4c32de8..d5dfc625c8 100644 --- a/src/pkg/dashboard/api_config_review.go +++ b/src/pkg/dashboard/api_config_review.go @@ -100,16 +100,18 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { return } var body struct { - RequireApproval *bool `json:"require_approval"` - Shadow *bool `json:"shadow"` // hive.yaml review.shadow - FanOut *bool `json:"fan_out"` - MaxParallelReviews *int `json:"max_parallel_reviews"` - MaxPerspectives *int `json:"max_perspectives_per_pr"` - ReviewerAgents *[]string `json:"reviewer_agents"` - FixerAgent *string `json:"fixer_agent"` - AllAuthors *bool `json:"all_authors"` - FixHumanPRs *bool `json:"fix_human_prs"` - ContributorPRs *struct { + RequireApproval *bool `json:"require_approval"` + Shadow *bool `json:"shadow"` // hive.yaml review.shadow + FanOut *bool `json:"fan_out"` + MaxParallelReviews *int `json:"max_parallel_reviews"` + MaxPerspectives *int `json:"max_perspectives_per_pr"` + ReviewerAgents *[]string `json:"reviewer_agents"` + FixerAgent *string `json:"fixer_agent"` + FixerFallbackAgents *[]string `json:"fixer_fallback_agents"` + FixerFallbackAfterUndeliverable *int `json:"fixer_fallback_after_undeliverable"` + AllAuthors *bool `json:"all_authors"` + FixHumanPRs *bool `json:"fix_human_prs"` + ContributorPRs *struct { BaseSync *bool `json:"base_sync"` } `json:"contributor_prs"` AcknowledgeNoFind *bool `json:"acknowledge_no_findings"` @@ -216,6 +218,7 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { name string }{ {body.MaxRedispatch, "max_redispatch"}, + {body.FixerFallbackAfterUndeliverable, "fixer_fallback_after_undeliverable"}, {body.HeadMaxRetries, "head_max_retries"}, {body.MaxOutOfScopeBacklogIssues, "max_out_of_scope_backlog_issues"}, } { @@ -472,6 +475,12 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { if body.FixerAgent != nil { cfg.Review.FixerAgent = strings.TrimSpace(*body.FixerAgent) } + if body.FixerFallbackAgents != nil { + cfg.Review.FixerFallbackAgents = (config.ReviewConfig{FixerFallbackAgents: *body.FixerFallbackAgents}).EffectiveFixerFallbackAgents() + } + if body.FixerFallbackAfterUndeliverable != nil { + cfg.Review.FixerFallbackAfterUndeliverable = *body.FixerFallbackAfterUndeliverable + } if body.AllAuthors != nil { cfg.Review.AllAuthors = *body.AllAuthors } diff --git a/src/pkg/dashboard/api_github_webhook.go b/src/pkg/dashboard/api_github_webhook.go index f6ab79c8b1..b8ad183a36 100644 --- a/src/pkg/dashboard/api_github_webhook.go +++ b/src/pkg/dashboard/api_github_webhook.go @@ -136,6 +136,9 @@ func (s *Server) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) { if reactions := s.reactToCIFailure(res); len(reactions) > 0 { resp["ci_failure"] = reactions } + if res.CIEvidence != nil { + resp["ci_evidence"] = res.CIEvidence + } if n, ok := sentinelPREventTarget(event, body); ok && s.deps.SentinelPREvent != nil { s.deps.SentinelPREvent(res.ConfiguredRepo, n) resp["sentinel"] = n diff --git a/src/pkg/dashboard/api_governor_pr_models.go b/src/pkg/dashboard/api_governor_pr_models.go index 9b18959c08..4bbb0c9955 100644 --- a/src/pkg/dashboard/api_governor_pr_models.go +++ b/src/pkg/dashboard/api_governor_pr_models.go @@ -8,6 +8,7 @@ import ( "time" ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" "github.com/hivecommons/hive/pkg/modelfamily" ) @@ -21,12 +22,13 @@ const ( ) type governorPRModelsResponse struct { - Window string `json:"window"` - MinMergedPRs int `json:"min_merged_prs"` - Total int `json:"total"` - Buckets []governorPRModelBucket `json:"buckets"` - Unknown int `json:"unknown"` - MostReworked []governorPRMostReworkedItem `json:"most_reworked,omitempty"` + Window string `json:"window"` + MinMergedPRs int `json:"min_merged_prs"` + Total int `json:"total"` + Buckets []governorPRModelBucket `json:"buckets"` + Unknown int `json:"unknown"` + MostReworked []governorPRMostReworkedItem `json:"most_reworked,omitempty"` + FixerQueue map[string]governor.FixerQueueStatus `json:"fixer_queue,omitempty"` } // governorPRModelBucket is one canonical model (modelfamily.Canonical folds @@ -111,6 +113,7 @@ func (s *Server) handleGovernorPRModels(w http.ResponseWriter, r *http.Request) minMergedPRs := effectiveModelsMinMergedPRs() actionable := s.lastActionableForPRModels() resp := aggregateGovernorPRModels(actionable.PRs.Attributed, window, time.Now()) + resp.FixerQueue = s.governorFixerQueue() runs, _, _ := readEffectiveModelRuns(s.effectiveModelTaskRunLogPath(), governorPRModelsWindowDuration(window)) effective := aggregateEffectiveModelsFromPRAggregation(resp, aggregateEffectiveRunStats(runs, effectiveModelsFilterAll), effectiveModelsFilterAll, minMergedPRs) applyGovernorPRModelEffectiveness(&resp, effective, minMergedPRs) diff --git a/src/pkg/dashboard/api_matrix.go b/src/pkg/dashboard/api_matrix.go index 025c1234a6..971a262621 100644 --- a/src/pkg/dashboard/api_matrix.go +++ b/src/pkg/dashboard/api_matrix.go @@ -81,6 +81,8 @@ type matrixLinesResponse struct { Seq uint64 `json:"seq"` Source string `json:"source"` Lines []matrixLine `json:"lines"` + // More is true only when another line this caller may see remains. + More bool `json:"more"` // LastIngestAt is when the pass that feeds this source last finished // (RFC 3339), or null before the first; NextIngestInS is the whole // seconds until the next pass is due, 0 when unknown. Together they let @@ -97,6 +99,11 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { return } + if r.URL.Query().Get("format") == "regions" { + s.handleCheckpointRegions(w, r) + return + } + src, cfg := s.matrixActiveSource() if src == nil || cfg == nil || !cfg.Active() { jsonError(w, "matrix mode disabled", http.StatusNotFound) @@ -125,7 +132,7 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { } // Filter inside the scan so max counts only lines this caller may see. - lines, latest := src.SinceMatching(since, limit, func(l matrixLine) bool { + lines, latest, more := src.SinceMatching(since, limit, func(l matrixLine) bool { return cfg.RepoAllowed(l.Repo) }) @@ -134,6 +141,7 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { Seq: latest, Source: "pushed-lines", Lines: lines, + More: more, } if last, nextS := src.ingestStatus(src.now()); !last.IsZero() { resp.LastIngestAt = &last diff --git a/src/pkg/dashboard/api_matrix_test.go b/src/pkg/dashboard/api_matrix_test.go index 50940e8373..6996b87212 100644 --- a/src/pkg/dashboard/api_matrix_test.go +++ b/src/pkg/dashboard/api_matrix_test.go @@ -416,6 +416,46 @@ func getMatrixLines(t *testing.T, s *Server, target string) matrixLinesResponse return resp } +// More describes visible work, even when the page is full and newer ring +// entries are all filtered out (#16530). +func TestHandleMatrixLines_MoreCountsOnlyAllowedLines(t *testing.T) { + s := newTestServer() + s.MatrixObserver(config.DashboardMatrixConfig{Enabled: true, Repos: []string{"hivecommons/allowed"}}) + src := s.matrix + t.Cleanup(src.close) + helperAddMatrixLine(src, "hivecommons/denied", "hidden before") + helperAddMatrixLine(src, "hivecommons/allowed", "first") + helperAddMatrixLine(src, "hivecommons/denied", "hidden between") + helperAddMatrixLine(src, "hivecommons/allowed", "last") + helperAddMatrixLine(src, "hivecommons/denied", "hidden after") + + for _, tc := range []struct { + name string + query string + seqs []uint64 + more bool + }{ + {"truncated", "since=0&max=1", []uint64{2}, true}, + {"full final page", "since=2&max=1", []uint64{4}, false}, + {"short final page", "since=2&max=2", []uint64{4}, false}, + {"initial backlog", "since=0", []uint64{2, 4}, false}, + {"only hidden lines", "since=4&max=1", nil, false}, + {"caught up", "since=5&max=1", nil, false}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := getMatrixLines(t, s, "/api/matrix/lines?"+tc.query) + if resp.Seq != 5 || resp.More != tc.more || len(resp.Lines) != len(tc.seqs) { + t.Fatalf("response = %+v, want latest=5 more=%v seqs=%v", resp, tc.more, tc.seqs) + } + for i, seq := range tc.seqs { + if resp.Lines[i].Seq != seq { + t.Fatalf("line %d seq = %d, want %d", i, resp.Lines[i].Seq, seq) + } + } + }) + } +} + // /api/matrix/lines reports when the ingest pass last ran and when the next // is due (#16276), null/0 before the first pass, so the kiosk can tell "no // pushes" from "no ingest". diff --git a/src/pkg/dashboard/api_repo_item_decision_reroute.go b/src/pkg/dashboard/api_repo_item_decision_reroute.go index 8ad7bf7523..8d17a41a2f 100644 --- a/src/pkg/dashboard/api_repo_item_decision_reroute.go +++ b/src/pkg/dashboard/api_repo_item_decision_reroute.go @@ -117,7 +117,10 @@ func (s *Server) handleRepoItemAdoptNow(ctx context.Context, w http.ResponseWrit jsonError(w, "queuing forced adoption: "+err.Error(), http.StatusBadGateway) return } - s.audit.LogRecord(user, auditRepoItemDecisionAdoptNow, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "action", repoItemDecisionAdoptNowAction, "label", delegatedecision.LabelAdoptSupersede), "", repoFull, number) + // The audit names whose PR was taken over: an operator may force the + // adoption of anyone's PR, a hive owner's included, and that choice + // stays attributable. + s.audit.LogRecord(user, auditRepoItemDecisionAdoptNow, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "action", repoItemDecisionAdoptNowAction, "label", delegatedecision.LabelAdoptSupersede, "author", facts.Author, "author_owner", strconv.FormatBool(s.isAuthorizedUserLogin(facts.Author))), "", repoFull, number) superseding := s.nudgeSweepAndAwaitAdoption(ctx, store, key, repoFull, number) jsonResponse(w, repoItemAdoptNowResponse(repoFull, number, superseding)) } diff --git a/src/pkg/dashboard/api_repo_item_takeover_test.go b/src/pkg/dashboard/api_repo_item_takeover_test.go index 088ef448c9..614a11ca78 100644 --- a/src/pkg/dashboard/api_repo_item_takeover_test.go +++ b/src/pkg/dashboard/api_repo_item_takeover_test.go @@ -130,6 +130,33 @@ func TestRepoItemAdoptNowGuards(t *testing.T) { } } +// An operator may take over anyone's PR, a hive owner's included: Adopt now +// on an owner-authored PR records the forced mark and the audit names the +// author as an owner. +func TestRepoItemAdoptNowOnOwnerAuthoredPR(t *testing.T) { + srv, store := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) + srv.deps.Config.Dashboard.AuthorizedUsers = []string{"someone:owner"} + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("owner-authored: code=%d body=%s", w.Code, w.Body.String()) + } + if rec, _ := store.Get(stagelabels.Key("testorg/testrepo", 8)); !recForced(rec) { + t.Fatalf("forced mark not recorded for an owner's PR: %+v", rec) + } + found := false + for _, e := range srv.GetAudit().Recent(20) { + if e.Action == auditRepoItemDecisionAdoptNow { + found = true + if !strings.Contains(e.Detail, "author=someone") || !strings.Contains(e.Detail, "author_owner=true") { + t.Fatalf("audit detail %q lacks the owner attribution", e.Detail) + } + } + } + if !found { + t.Fatalf("audit = %v", decisionAuditActions(srv)) + } +} + func TestRepoItemRerouteNoneOnlineIsConflict(t *testing.T) { srv, _ := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"any","type":"pr"}`) diff --git a/src/pkg/dashboard/api_review_queue.go b/src/pkg/dashboard/api_review_queue.go index 909ce51804..1e5c5d56f6 100644 --- a/src/pkg/dashboard/api_review_queue.go +++ b/src/pkg/dashboard/api_review_queue.go @@ -10,6 +10,7 @@ import ( "time" ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -51,7 +52,19 @@ type reviewQueueResponse struct { // needs attention (hivecommons/hive#12534). HiveHeld int `json:"hive_held"` History []ReviewQueueHistoryEntry `json:"history"` - Items []ghpkg.ReviewQueueEntry `json:"items"` + Items []reviewQueueItem `json:"items"` +} + +type reviewQueueItem struct { + ghpkg.ReviewQueueEntry + governor.FixerQueueStatus +} + +func (s *Server) governorFixerQueue() map[string]governor.FixerQueueStatus { + if s == nil || s.deps == nil { + return nil + } + return s.deps.Governor.FixerQueue() } // handleReviewQueue serves GET /api/review/queue?limit=N&offset=M: every open @@ -110,7 +123,7 @@ func (s *Server) handleReviewQueue(w http.ResponseWriter, r *http.Request) { Limit: limit, Offset: offset, History: history, - Items: []ghpkg.ReviewQueueEntry{}, + Items: []reviewQueueItem{}, } for _, e := range queue { if e.Stage != nil && e.Stage.WaitingOnHive && e.Stage.PastDwell { @@ -122,7 +135,13 @@ func (s *Server) handleReviewQueue(w http.ResponseWriter, r *http.Request) { if end > len(queue) { end = len(queue) } - resp.Items = queue[offset:end] + fixers := s.governorFixerQueue() + for _, entry := range queue[offset:end] { + resp.Items = append(resp.Items, reviewQueueItem{ + ReviewQueueEntry: entry, + FixerQueueStatus: fixers[ghpkg.ReviewQueueKey(entry.Repo, entry.Number)], + }) + } } resp.HasMore = offset+len(resp.Items) < len(queue) jsonResponse(w, resp) diff --git a/src/pkg/dashboard/checkpoint_source.go b/src/pkg/dashboard/checkpoint_source.go new file mode 100644 index 0000000000..c19408cd67 --- /dev/null +++ b/src/pkg/dashboard/checkpoint_source.go @@ -0,0 +1,315 @@ +package dashboard + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "time" + "unicode" + "unicode/utf8" + + "github.com/hivecommons/hive/crux/logscrub" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +const ( + checkpointMaxLineRunes = 4096 + checkpointMaxRegionBytes = 16 << 10 + checkpointMaxBytes = 512 << 10 +) + +// Response contract shared by ingest and since(): the reader shows +// checkpointSourceLabel as the feed source and checkpointStage on every region. +const ( + checkpointSourceLabel = "Pushed PR" + checkpointStage = "pushed-checkpoint" +) + +type checkpointLine struct { + Op string `json:"op"` + Line string `json:"line"` +} + +type checkpointRegion struct { + Seq uint64 `json:"seq"` + Repo string `json:"repo"` + PR int `json:"pr"` + PRURL string `json:"pr_url"` + Head string `json:"head"` + Path string `json:"path"` + Stage string `json:"stage"` + At time.Time `json:"at"` + Lines []checkpointLine `json:"lines"` +} + +type checkpointHead struct { + at time.Time +} + +// checkpointSource is a memory-only projection of the existing sentinel +// observer. It never fetches patches, restores Matrix's persisted lines, logs +// content, or broadcasts code. A region is the indivisible unit everywhere. +type checkpointSource struct { + mu sync.Mutex + cfg config.DashboardMatrixConfig + epoch string + seq uint64 + regions []checkpointRegion + lines, bytes int + heads map[[sha256.Size]byte]checkpointHead + rateStart time.Time + rateCount int +} + +func newCheckpointSource(cfg config.DashboardMatrixConfig) *checkpointSource { + c := &checkpointSource{} + c.configure(cfg) + return c +} + +func (c *checkpointSource) configure(cfg config.DashboardMatrixConfig) { + c.mu.Lock() + defer c.mu.Unlock() + if c.epoch != "" && c.cfg.Enabled == cfg.Enabled && slices.Equal(c.cfg.Repos, cfg.Repos) && slices.Equal(c.cfg.ExcludePaths, cfg.ExcludePaths) { + return + } + cfg.Repos = append([]string(nil), cfg.Repos...) + cfg.ExcludePaths = append([]string(nil), cfg.ExcludePaths...) + c.cfg = cfg + var nonce [16]byte + _, _ = rand.Read(nonce[:]) // crypto/rand.Read cannot fail on supported Go versions. + c.epoch = hex.EncodeToString(nonce[:]) + c.regions = nil + c.lines, c.bytes, c.rateCount = 0, 0, 0 + c.rateStart = time.Time{} + c.heads = make(map[[sha256.Size]byte]checkpointHead) +} + +func (c *checkpointSource) policyEpoch() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.epoch +} + +func (c *checkpointSource) ingest(obs github.SentinelPatchObservation, epoch string, now time.Time) int { + c.mu.Lock() + defer c.mu.Unlock() + if epoch != c.epoch || !c.cfg.Active() || !c.cfg.RepoAllowed(obs.Repo) || obs.Private || !obs.HiveIdentified || obs.Number <= 0 || obs.HeadSHA == "" { + return 0 + } + // The sentinel proves public visibility (unknown is Private=true). Only its + // actual PR/head observations enter; observing the same head cannot replay it. + key := sha256.Sum256([]byte(strings.ToLower(obs.Repo) + "\x00" + strconv.Itoa(obs.Number) + "\x00" + obs.HeadSHA)) + for k, head := range c.heads { + if now.Sub(head.at) >= matrixDedupTTL { + delete(c.heads, k) + } + } + if _, seen := c.heads[key]; seen { + return 0 + } + if len(c.heads) >= matrixMaxTrackedPRs { + var oldest [sha256.Size]byte + var at time.Time + for k, head := range c.heads { + if at.IsZero() || head.at.Before(at) { + oldest, at = k, head.at + } + } + delete(c.heads, oldest) + } + c.heads[key] = checkpointHead{at: now} + if now.Sub(c.rateStart) >= matrixRateWindow || now.Before(c.rateStart) { + c.rateStart, c.rateCount = now, 0 + } + at := obs.At + if at.IsZero() { + at = now + } + count := 0 + for i, file := range obs.Files { + if i >= matrixMaxFilesPerObs { + break + } + if matrixPathDenied(file.Path, c.cfg.ExcludePaths) || len(file.Patch) > matrixMaxPatchBytes { + continue + } + for _, lines := range checkpointRegions(file.Patch) { + size := 0 + safe := len(lines) <= matrixMaxLinesPerHead + for _, line := range lines { + size += len(line.Line) + safe = safe && checkpointSafeLine(line.Line) + } + if !safe || size > checkpointMaxRegionBytes { + continue + } + if count+len(lines) > matrixMaxLinesPerHead || c.rateCount+len(lines) > matrixMaxLinesPerRate { + continue + } + c.seq++ + region := checkpointRegion{Seq: c.seq, Repo: obs.Repo, PR: obs.Number, PRURL: fmt.Sprintf("https://github.com/%s/pull/%d", obs.Repo, obs.Number), Head: obs.HeadSHA, Path: file.Path, Stage: checkpointStage, At: at, Lines: lines} + for len(c.regions) > 0 && (c.lines+len(lines) > matrixBacklogCap || c.bytes+size > checkpointMaxBytes) { + old := c.regions[0] + c.lines -= len(old.Lines) + for _, l := range old.Lines { + c.bytes -= len(l.Line) + } + c.regions[0] = checkpointRegion{} + c.regions = c.regions[1:] + } + c.regions = append(c.regions, region) + c.lines += len(lines) + c.bytes += size + count += len(lines) + c.rateCount += len(lines) + } + } + return count +} + +func checkpointSafeLine(line string) bool { + if !utf8.ValidString(line) || utf8.RuneCountInString(line) > checkpointMaxLineRunes { + return false + } + for _, r := range line { + if unicode.IsControl(r) && r != '\t' { + return false + } + } + return !matrixHasEntropyRun(line) && !matrixKeyValueSecret.MatchString(line) && + !strings.Contains(line, "-----BEGIN ") && !strings.Contains(line, "-----END ") && + !logscrub.ContainsRedactionMarker(line) && logscrub.ScrubString(line) == line && logscrub.RedactPaneTokens(line) == line +} + +var checkpointHunk = regexp.MustCompile(`^@@ -[0-9]+(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@(?:.*)$`) + +// Validate hunk counts before admitting any changed runs. Incomplete or +// malformed patches fail closed, so a truncated hunk never looks complete. +func checkpointRegions(patch string) [][]checkpointLine { + if patch == "" || strings.ContainsRune(patch, 0) { + return nil + } + rows := strings.Split(patch, "\n") + if rows[len(rows)-1] == "" { + rows = rows[:len(rows)-1] + } + var out [][]checkpointLine + var run []checkpointLine + oldLeft, newLeft := 0, 0 + inHunk := false + flush := func() { + if len(run) > 0 { + out = append(out, run) + run = nil + } + } + for _, row := range rows { + if strings.HasPrefix(row, "@@") { + if inHunk && (oldLeft != 0 || newLeft != 0) { + return nil + } + flush() + match := checkpointHunk.FindStringSubmatch(row) + if match == nil { + return nil + } + oldLeft, newLeft = 1, 1 + if match[1] != "" { + n, e := strconv.Atoi(match[1]) + if e != nil { + return nil + } + oldLeft = n + } + if match[2] != "" { + n, e := strconv.Atoi(match[2]) + if e != nil { + return nil + } + newLeft = n + } + inHunk = true + continue + } + if !inHunk { + continue + } + if row == `\ No newline at end of file` { + continue + } + if row == "" { + return nil + } + switch row[0] { + case '+': + newLeft-- + run = append(run, checkpointLine{Op: "+", Line: strings.Clone(row[1:])}) + case '-': + oldLeft-- + run = append(run, checkpointLine{Op: "-", Line: strings.Clone(row[1:])}) + case ' ': + oldLeft-- + newLeft-- + flush() + default: + return nil + } + if oldLeft < 0 || newLeft < 0 { + return nil + } + } + if !inHunk || oldLeft != 0 || newLeft != 0 { + return nil + } + flush() + return out +} + +type checkpointResponse struct { + Seq uint64 `json:"seq"` + Latest uint64 `json:"latest"` + Epoch string `json:"epoch"` + Source string `json:"source"` + Stage string `json:"stage"` + Regions []checkpointRegion `json:"regions"` + LastIngestAt *time.Time `json:"last_ingest_at"` + NextIngestInS int `json:"next_ingest_in_s"` +} + +// max counts changed lines, but the first eligible region is always returned +// whole even when larger than max. seq advances only through consumed regions. +func (c *checkpointSource) since(seq uint64, limit int) checkpointResponse { + c.mu.Lock() + defer c.mu.Unlock() + if limit <= 0 { + limit = matrixDefaultSinceMax + } + if seq > c.seq { + seq = 0 + } + out := checkpointResponse{Seq: seq, Latest: c.seq, Epoch: c.epoch, Source: checkpointSourceLabel, Stage: checkpointStage, Regions: []checkpointRegion{}} + count := 0 + for _, r := range c.regions { + if r.Seq <= seq { + continue + } + if count > 0 && count+len(r.Lines) > limit { + break + } + out.Regions = append(out.Regions, r) + count += len(r.Lines) + out.Seq = r.Seq + } + if len(out.Regions) == 0 { + out.Seq = c.seq + } + return out +} diff --git a/src/pkg/dashboard/checkpoint_source_test.go b/src/pkg/dashboard/checkpoint_source_test.go new file mode 100644 index 0000000000..b2d77090d5 --- /dev/null +++ b/src/pkg/dashboard/checkpoint_source_test.go @@ -0,0 +1,366 @@ +package dashboard + +import ( + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/sentinel" +) + +func checkpointPatch(lines ...string) string { + return fmt.Sprintf("@@ -0,0 +1,%d @@\n+%s\n", len(lines), strings.Join(lines, "\n+")) +} + +func TestCheckpointWholeRegionsAndContinuation(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + patch := "@@ -1,4 +1,7 @@\n-old\n+\tnew\n+\n+repeat\n+repeat\n context\n-again\n+again\n tail\n" + obs := matrixObs(3, "real-head", sentinel.File{Path: "a.go", Patch: patch}) + now := time.Now() + if n := c.ingest(obs, c.policyEpoch(), now); n != 7 { + t.Fatalf("admitted %d changed lines", n) + } + first := c.since(0, 1) + if len(first.Regions) != 1 || len(first.Regions[0].Lines) != 5 || first.Seq != 1 || first.Latest != 2 { + t.Fatalf("first page: %+v", first) + } + want := []checkpointLine{{"-", "old"}, {"+", "\tnew"}, {"+", ""}, {"+", "repeat"}, {"+", "repeat"}} + r := first.Regions[0] + if !reflect.DeepEqual(r.Lines, want) || r.Head != "real-head" || r.PRURL != "https://github.com/"+matrixTestRepo+"/pull/3" || r.Stage != checkpointStage || !r.At.Equal(now) { + t.Fatalf("region %+v", r) + } + next := c.since(first.Seq, 1) + if len(next.Regions) != 1 || len(next.Regions[0].Lines) != 2 || next.Seq != 2 || next.Latest != 2 { + t.Fatalf("next page %+v", next) + } + if n := c.ingest(obs, c.policyEpoch(), now); n != 0 { + t.Fatal("unchanged head replayed") + } + obs.HeadSHA = "next-head" + if n := c.ingest(obs, c.policyEpoch(), now); n != 7 { + t.Fatal("new actual head was suppressed") + } +} + +func TestCheckpointDropsUnsafeWholeRegions(t *testing.T) { + bad := []string{"password: hunter2", "token = \"short\"", "-----BEGIN PRIVATE KEY-----", "[REDACTED]", strings.Repeat("a", 33), "bad\x01text", string([]byte{0xff}), strings.Repeat("a ", checkpointMaxLineRunes)} + for _, op := range []string{"+", "-"} { + for i, line := range bad { + t.Run(fmt.Sprintf("%s/%d", op, i), func(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + // The secret and innocent line form one region. A separate safe region + // after context survives; no apparently complete fragment of the first does. + oldN, newN := 1, 3 + if op == "-" { + oldN, newN = 3, 1 + } + patch := fmt.Sprintf("@@ -1,%d +1,%d @@\n%ssafe peer\n%s%s\n context\n@@ -10,0 +10 @@\n+visible\n", oldN, newN, op, op, line) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: patch}) + c.ingest(obs, c.policyEpoch(), time.Now()) + got := c.since(0, 200) + if len(got.Regions) != 1 || !reflect.DeepEqual(got.Regions[0].Lines, []checkpointLine{{"+", "visible"}}) { + t.Fatalf("unsafe region leaked: %+v", got.Regions) + } + }) + } + } +} + +func TestCheckpointRejectsIncompleteDiff(t *testing.T) { + for _, patch := range []string{"+orphan", "@@ -0,0 +1,2 @@\n+only one\n", "@@ -1 +1 @@\n-old\n", "@@ malformed\n+x\n", "@@ -0,0 +1 @@\n+x\n+y\n", "@@ -0,0 +1 @@\n+x\n@@ -0,0 +2,2 @@\n+truncated\n", "@@ -0,0 +1 @@\n+binary\x00\n"} { + if r := checkpointRegions(patch); len(r) != 0 { + t.Fatalf("incomplete patch admitted: %+v", r) + } + } + r := checkpointRegions("@@ -1 +1 @@\n--- literal\n+++ literal\n\\ No newline at end of file\n") + if len(r) != 1 || len(r[0]) != 2 || r[0][1].Line != "++ literal" { + t.Fatalf("literal diff signs lost: %+v", r) + } +} + +func TestCheckpointObservationAndPolicyBoundaries(t *testing.T) { + for _, kind := range []string{"private-or-unknown", "unidentified", "unlisted", "no-head", "no-pr", "excluded", "secret-path"} { + t.Run(kind, func(t *testing.T) { + cfg := matrixTestConfig() + cfg.ExcludePaths = []string{"skip/**"} + c := newCheckpointSource(cfg) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + switch kind { + case "private-or-unknown": + obs.Private = true + case "unidentified": + obs.HiveIdentified = false + case "unlisted": + obs.Repo = "other/repo" + case "no-head": + obs.HeadSHA = "" + case "no-pr": + obs.Number = 0 + case "excluded": + obs.Files[0].Path = "skip/a.go" + case "secret-path": + obs.Files[0].Path = ".env" + } + if c.ingest(obs, c.policyEpoch(), time.Now()) != 0 || len(c.since(0, 200).Regions) != 0 { + t.Fatal("boundary admitted content") + } + }) + } + c := newCheckpointSource(matrixTestConfig()) + epoch := c.policyEpoch() + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + c.ingest(obs, epoch, time.Now()) + cfg := matrixTestConfig() + cfg.ExcludePaths = []string{"elsewhere/**"} + c.configure(cfg) + if c.policyEpoch() == epoch || len(c.since(0, 200).Regions) != 0 || c.since(0, 200).Seq != c.since(0, 200).Latest { + t.Fatal("policy change retained code or epoch") + } + if c.ingest(obs, epoch, time.Now()) != 0 { + t.Fatal("old queued observation crossed policy epoch") + } + epoch = c.policyEpoch() + c.configure(cfg) + if c.policyEpoch() != epoch { + t.Fatal("unchanged policy reset epoch") + } + c.ingest(obs, epoch, time.Now()) + cfg.Enabled = false + c.configure(cfg) + if len(c.since(0, 200).Regions) != 0 || c.ingest(obs, c.policyEpoch(), time.Now()) != 0 { + t.Fatal("disable retained or admitted code") + } +} + +func TestCheckpointPolicyClearsSharedQueue(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("queued code")})) + if len(m.in) != 1 { + t.Fatal("observation did not enter queue") + } + cfg := matrixTestConfig() + cfg.Enabled = false + m.setConfig(cfg) + if len(m.in) != 0 { + t.Fatal("policy change retained queued code") + } + m.policyMu.Lock() + done := make(chan struct{}) + go func() { m.Observe(matrixObs(2, "h")); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + m.policyMu.Unlock() + t.Fatal("observer blocked on policy update") + } + m.policyMu.Unlock() + +} + +func TestCheckpointConcurrentObserversNotDropped(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + // Another observer in flight holds the shared side of the policy lock. + m.policyMu.RLock() + defer m.policyMu.RUnlock() + done := make(chan struct{}) + go func() { + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("concurrent code")})) + close(done) + }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("observer blocked on a concurrent observer") + } + if got := m.Dropped(); got != 0 { + t.Fatalf("Dropped() = %d, want 0: concurrent observer discarded", got) + } + if len(m.in) != 1 { + t.Fatal("concurrent observation did not enter queue") + } +} + +func TestCheckpointUnchangedPolicyDoesNotBlockObservers(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + epoch := m.checkpoints.policyEpoch() + // An observer in flight holds the shared side of the policy lock; the + // reader poll re-applying the same policy must not wait for or evict it. + m.policyMu.RLock() + defer m.policyMu.RUnlock() + done := make(chan struct{}) + go func() { m.setConfig(matrixTestConfig()); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("unchanged policy refresh took the exclusive policy lock") + } + if m.checkpoints.policyEpoch() != epoch { + t.Fatal("unchanged policy refresh rotated the epoch") + } + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("polled code")})) + if got := m.Dropped(); got != 0 { + t.Fatalf("Dropped() = %d, want 0: observer dropped during an unchanged policy refresh", got) + } + if len(m.in) != 1 { + t.Fatal("observation did not enter queue") + } +} + +func TestCheckpointWholeBounds(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + now := time.Now() + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(append(matrixUniqueLines("safe", 199), "last", "over")...)}) + if c.ingest(obs, c.policyEpoch(), now) != 0 { + t.Fatal("per-head bound sliced oversized region") + } + for pr := 2; pr < 25; pr++ { + obs = matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(matrixUniqueLines("safe", 99)...)}) + c.ingest(obs, c.policyEpoch(), now.Add(time.Duration(pr)*time.Minute)) + } + got := c.since(0, 10000) + if c.lines > matrixBacklogCap || c.bytes > checkpointMaxBytes || len(got.Regions) != matrixBacklogCap/99 { + t.Fatalf("buffer bounds lines=%d bytes=%d regions=%d", c.lines, c.bytes, len(got.Regions)) + } + for _, r := range got.Regions { + if len(r.Lines) != 99 { + t.Fatal("eviction sliced region") + } + } + // Byte bound is independent of line count, and cloned text keeps retained + // strings from pinning the much larger original patch backing storage. + c = newCheckpointSource(matrixTestConfig()) + text := strings.Repeat("safe text ", 300) + for pr := 1; pr <= 40; pr++ { + c.ingest(matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(text, text, text, text, text)}), c.policyEpoch(), now.Add(time.Duration(pr)*time.Minute)) + } + if c.bytes > checkpointMaxBytes || len(c.regions) >= 40 { + t.Fatal("text byte bound not enforced") + } + c = newCheckpointSource(matrixTestConfig()) + for pr := 1; pr <= 4; pr++ { + n := c.ingest(matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(matrixUniqueLines("safe", 199)...)}), c.policyEpoch(), now) + if (pr <= 3 && n != 199) || (pr == 4 && n != 0) { + t.Fatalf("rate bound split region: pr=%d n=%d", pr, n) + } + } +} + +func TestCheckpointAPIAuthColdAndEpoch(t *testing.T) { + s := NewServerWithAuth(0, "checkpoint-test-token", slog.New(slog.NewTextHandler(io.Discard, nil))) + s.mux.HandleFunc("GET /api/matrix/lines", s.handleMatrixLines) + // Active configuration exists before the sentinel has created its observer. + cfg := matrixTestConfig() + s.deps = &Dependencies{Config: &config.Config{}} + s.deps.Config.Dashboard.Matrix = cfg + defer func() { + if s.matrix != nil { + s.matrix.close() + <-s.matrix.done + } + }() + request := func(auth, role string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/matrix/lines?since=0&format=regions&max=1", nil) + req.Header.Set("Authorization", auth) + req.Header.Set("X-Hive-Role", role) + rr := httptest.NewRecorder() + s.Handler().ServeHTTP(rr, req) + if rr.Header().Get("Cache-Control") != "no-store" { + t.Fatal("cacheable response") + } + return rr + } + for _, role := range []string{"", config.RoleOwner} { + if rr := request("", role); rr.Code != 401 { + t.Fatalf("anonymous/forged role got %d", rr.Code) + } + } + rr := request("Bearer checkpoint-test-token", "") + var cold checkpointResponse + if rr.Code != 200 || json.Unmarshal(rr.Body.Bytes(), &cold) != nil || cold.Epoch == "" || cold.LastIngestAt != nil || len(cold.Regions) != 0 || cold.Source != checkpointSourceLabel || cold.Stage != checkpointStage { + t.Fatalf("cold response %d %s", rr.Code, rr.Body.String()) + } + // Feed the real observer queue, including a deletion-only checkpoint. + // Wait for the nudge frame rather than the ingest: the observer goroutine + // reads the matrix config while broadcasting, so the policy edits below + // must not start until that frame has been delivered. + frames := make(chan []byte, 8) + s.sseMu.Lock() + s.sseClients[frames] = struct{}{} + s.sseMu.Unlock() + s.MatrixObserver(cfg)(matrixObs(1, "real-head", sentinel.File{Path: "a.go", Patch: "@@ -1,2 +0,0 @@\n-old\n-old\n"})) + select { + case frame := <-frames: + if string(frame) != matrixCodeLinesSSEFrame(0) { + t.Fatalf("unexpected frame %q", frame) + } + case <-time.After(2 * time.Second): + t.Fatal("observer did not feed checkpoint source") + } + s.sseMu.Lock() + delete(s.sseClients, frames) + s.sseMu.Unlock() + if len(s.matrix.checkpoints.since(0, 1).Regions) == 0 { + t.Fatal("checkpoint source empty after nudge") + } + s.RecordMatrixIngest(time.Now().UTC(), time.Minute) + rr = request("Bearer checkpoint-test-token", "") + var page checkpointResponse + if json.Unmarshal(rr.Body.Bytes(), &page) != nil || len(page.Regions) != 1 || len(page.Regions[0].Lines) != 2 || page.Seq != page.Latest || page.LastIngestAt == nil { + t.Fatalf("whole response %s", rr.Body.String()) + } + cfg.ExcludePaths = []string{"a.go"} + s.deps.Config.Dashboard.Matrix = cfg + rr = request("Bearer checkpoint-test-token", "") + var changed checkpointResponse + if json.Unmarshal(rr.Body.Bytes(), &changed) != nil || changed.Epoch == cold.Epoch || len(changed.Regions) != 0 { + t.Fatalf("policy change %s", rr.Body.String()) + } + s.deps.Config.Dashboard.Matrix.Enabled = false + if rr := request("Bearer checkpoint-test-token", ""); rr.Code != 404 { + t.Fatalf("disabled=%d", rr.Code) + } +} + +// The legacy persistence format cannot retain or restore checkpoint regions. +func TestCheckpointMemoryOnly(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + m.checkpoints.ingest(obs, m.checkpoints.policyEpoch(), time.Now()) + restored := newMatrixSource(matrixTestConfig(), nil) + if len(restored.checkpoints.since(0, 200).Regions) != 0 || restored.checkpoints.policyEpoch() == m.checkpoints.policyEpoch() { + t.Fatal("new source restored checkpoint history") + } + // The superseded persistent line history must never re-enter the feed and + // is left untouched for the operator to remove, rather than silently + // deleted or rewritten as part of a dashboard upgrade. + path := filepath.Join(t.TempDir(), "matrix-lines.json") + seed := []byte(`{"seq":7,"lines":[{"seq":7,"repo":"org/repo","pr":1,"line":"old retained code"}]}`) + if err := os.WriteFile(path, seed, 0600); err != nil { + t.Fatal(err) + } + s := &Server{} + observe := s.MatrixObserver(matrixTestConfig()) + defer func() { s.matrix.close(); <-s.matrix.done }() + if s.matrix.Latest() != 0 || len(s.matrix.checkpoints.since(0, 200).Regions) != 0 { + t.Fatal("legacy persistent code restored") + } + observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("fresh checkpoint")})) + waitFor(t, func() bool { return s.matrix.Latest() != 0 }, "observer ingest") + if got, err := os.ReadFile(path); err != nil || string(got) != string(seed) { + t.Fatal("legacy history file changed") + } + // Compile-time assertion: the public observer still receives the existing + // authoritative transport, with no extra patch collector or endpoint. + var _ func(github.SentinelPatchObservation) = m.Observe +} diff --git a/src/pkg/dashboard/contribute_select_lock_scope_test.go b/src/pkg/dashboard/contribute_select_lock_scope_test.go index 0a521c3ccd..c2fe817c7f 100644 --- a/src/pkg/dashboard/contribute_select_lock_scope_test.go +++ b/src/pkg/dashboard/contribute_select_lock_scope_test.go @@ -11,10 +11,12 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "sync" "testing" "time" + "github.com/gorilla/websocket" ghpkg "github.com/hivecommons/hive/pkg/github" ) @@ -225,47 +227,84 @@ func TestSelectTask_MintFailureRollsBackClaim(t *testing.T) { // disconnect path finds no task to "release" and books no cooldown on an issue // the contributor never saw, and no rate slot or lease is spent on it. func TestHandleReady_SendFailureRollsBackClaim(t *testing.T) { - hub, s := covK2Hub(t) - oneActionableIssue(s) - s.deps.GHAppAuth = newSucceedingAppAuth(t, "ghs_7775_dead_socket") + for _, tc := range []struct { + name string + closeSent bool + level string + }{ + {name: "close frame already sent", closeSent: true, level: "INFO"}, + {name: "other write failure", level: "WARN"}, + } { + t.Run(tc.name, func(t *testing.T) { + hub, s := covK2Hub(t) + var logs lockedBuffer + hub.logger = slog.New(slog.NewTextHandler(&logs, nil)) + oneActionableIssue(s) + s.deps.GHAppAuth = newSucceedingAppAuth(t, "ghs_7775_dead_socket") - server, client := wsPipe(t) - conn := lockScopeConn(hub, "erin", "c-erin") - conn.ws = server - // The peer is gone and the hub's own side is closed — the shape the - // heartbeat loop leaves behind after a missed pong. - client.Close() - server.Close() + server, client := wsPipe(t) + t.Cleanup(func() { server.Close() }) + conn := lockScopeConn(hub, "erin", "c-erin") + conn.ws = server + if tc.closeSent { + // Leave TCP open after sending Close so the next data write returns + // gorilla's ErrCloseSent, matching the #16496 diagnostics. + if err := server.WriteControl(websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.CloseNormalClosure, "closing"), + time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + } else { + // Other write failures must retain warning visibility. + client.Close() + server.Close() + } - sess := &wsSession{h: hub, conn: server, contributor: conn} - if stop := sess.handleReady(WSMessage{Type: "ready", Seq: 1}); !stop { - t.Fatalf("a failed task_assign send must stop the session") - } + sess := &wsSession{h: hub, conn: server, contributor: conn} + if stop := sess.handleReady(WSMessage{Type: "ready", Seq: 1}); !stop { + t.Fatalf("a failed task_assign send must stop the session") + } - conn.mu.Lock() - task := conn.currentTask - conn.mu.Unlock() - if task != nil { - t.Fatalf("#7775: an assignment whose task_assign never left the hub was left on the dead connection: %+v", task) - } - if got := len(hub.leases); got != 0 { - t.Fatalf("#7775: a lease survived the undeliverable assignment: %d lease(s)", got) - } - if hour, day := hub.rateWindowCounts(identityOf(conn), time.Now()); hour != 0 || day != 0 { - t.Fatalf("#7775: the undeliverable assignment still occupies a rate-window slot: hour=%d day=%d", hour, day) - } + var failureLine string + for _, line := range strings.Split(logs.String(), "\n") { + if strings.Contains(line, "failed to send task_assign; releasing the undelivered claim") { + failureLine = line + break + } + } + if !strings.Contains(failureLine, "level="+tc.level) || !strings.Contains(failureLine, "task=") || !strings.Contains(failureLine, "error=") { + t.Fatalf("want %s assignment failure with task and error details, got: %s", tc.level, logs.String()) + } + if tc.closeSent && !strings.Contains(failureLine, websocket.ErrCloseSent.Error()) { + t.Fatalf("expected ErrCloseSent, got: %s", failureLine) + } - // releaseOnDisconnect now runs, as it does for every socket that closes. It - // must find nothing to release: no cooldown on #101, and the issue offerable - // to the next contributor at once. - sess.releaseOnDisconnect() - if hub.isTaskInFailureCooldown("myorg/repo1", 101) { - t.Fatalf("#7775: the disconnect path booked a release cooldown on an issue the contributor never received") - } - next := lockScopeConn(hub, "frank", "c-frank") - again := hub.selectTask(next) - if again == nil || again.Type != "task_assign" || again.Number != 101 { - t.Fatalf("the issue must be offerable again after the undeliverable assignment, got %+v", again) + conn.mu.Lock() + task := conn.currentTask + conn.mu.Unlock() + if task != nil { + t.Fatalf("#7775: an assignment whose task_assign never left the hub was left on the dead connection: %+v", task) + } + if got := len(hub.leases); got != 0 { + t.Fatalf("#7775: a lease survived the undeliverable assignment: %d lease(s)", got) + } + if hour, day := hub.rateWindowCounts(identityOf(conn), time.Now()); hour != 0 || day != 0 { + t.Fatalf("#7775: the undeliverable assignment still occupies a rate-window slot: hour=%d day=%d", hour, day) + } + + // releaseOnDisconnect now runs, as it does for every socket that closes. It + // must find nothing to release: no cooldown on #101, and the issue offerable + // to the next contributor at once. + sess.releaseOnDisconnect() + if hub.isTaskInFailureCooldown("myorg/repo1", 101) { + t.Fatalf("#7775: the disconnect path booked a release cooldown on an issue the contributor never received") + } + next := lockScopeConn(hub, "frank", "c-frank") + again := hub.selectTask(next) + if again == nil || again.Type != "task_assign" || again.Number != 101 { + t.Fatalf("the issue must be offerable again after the undeliverable assignment, got %+v", again) + } + }) } } diff --git a/src/pkg/dashboard/contribute_ws.go b/src/pkg/dashboard/contribute_ws.go index 783fbb6a25..db61d08cfc 100644 --- a/src/pkg/dashboard/contribute_ws.go +++ b/src/pkg/dashboard/contribute_ws.go @@ -3735,7 +3735,13 @@ func (s *wsSession) handleReady(msg WSMessage) (stop bool) { // the disconnect path finds nothing to release: no release cooldown // on an issue the contributor never received, no lease left to // expire, no rate-window slot spent on a task that never shipped. - h.logger.Warn("[contribute-ws] failed to send task_assign; releasing the undelivered claim", "error", err, "task", task.TaskID) + // A Close frame can win the race with selection's GitHub calls. + // ErrCloseSent is then expected teardown, not a hub defect (#16496). + level := slog.LevelWarn + if errors.Is(err, websocket.ErrCloseSent) { + level = slog.LevelInfo + } + h.logger.Log(context.Background(), level, "[contribute-ws] failed to send task_assign; releasing the undelivered claim", "error", err, "task", task.TaskID) h.rollbackAssignment(s.contributor, task.TaskID) return true } diff --git a/src/pkg/dashboard/deferred_init_promise_test.go b/src/pkg/dashboard/deferred_init_promise_test.go index 6a11a31e87..c69cb36985 100644 --- a/src/pkg/dashboard/deferred_init_promise_test.go +++ b/src/pkg/dashboard/deferred_init_promise_test.go @@ -177,7 +177,7 @@ func TestDeferredInitGuardsCoverEveryEntry(t *testing.T) { // Count TOP-LEVEL entries only: one per line, at the array's indentation. // Counting every `() =>` in the block would also count the nested arrows // inside each entry's own .then chains. - entryLine := regexp.MustCompile(`(?m)^\s+\(\)\s*=>`) + entryLine := regexp.MustCompile(`(?m)^\s+\['[^']+',\s*\(\)\s*=>`) entries := len(entryLine.FindAllString(block, -1)) matched := len(deferredEntryCall.FindAllString(block, -1)) if entries == 0 { diff --git a/src/pkg/dashboard/fixer_queue_test.go b/src/pkg/dashboard/fixer_queue_test.go new file mode 100644 index 0000000000..76aaba7f75 --- /dev/null +++ b/src/pkg/dashboard/fixer_queue_test.go @@ -0,0 +1,92 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/governor" +) + +func TestGovernorPRModelsIncludesLiveFixerQueue(t *testing.T) { + s := covApiServer(t) + s.deps.Governor = &governor.Governor{} + at := time.Now() + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#1", at) + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#2", at.Add(time.Second)) + + get := func() governorPRModelsResponse { + t.Helper() + rec := httptest.NewRecorder() + s.handleGovernorPRModels(rec, httptest.NewRequest(http.MethodGet, "/api/governor/pr-models", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rec.Code, rec.Body.String()) + } + var resp governorPRModelsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.FixerQueue) == 0 && strings.Contains(rec.Body.String(), `"fixer_queue"`) { + t.Fatal("empty queue must be omitted") + } + return resp + } + // Queue visibility is independent of attribution and the model window. + resp := get() + if resp.Total != 0 || len(resp.FixerQueue) != 2 || resp.FixerQueue["myorg/repo1#2"].FixerQueuePosition != 2 { + t.Fatalf("response = %+v", resp) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#1") + second := get().FixerQueue["myorg/repo1#2"] + if second.FixerQueuePosition != 1 || second.FixerQueueAhead == nil || *second.FixerQueueAhead != 0 { + t.Fatalf("after delivery = %+v", second) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#2") + get() + s.deps.Governor = nil + get() +} + +func TestReviewQueueFixerFieldsAreOptionalAndKeepGlobalPosition(t *testing.T) { + s := reviewQueueTestServer(t, filepath.Join(t.TempDir(), "missing.json")) + s.deps.Governor = &governor.Governor{} + at := time.Now() + s.deps.Governor.RecordFixKickDeferred("myorg/other#99", at) + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#2", at.Add(time.Second)) + + get := func() []map[string]json.RawMessage { + t.Helper() + rec := doOwnerGet(s, "/api/review/queue?limit=1") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + Items []map[string]json.RawMessage `json:"items"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp.Items + } + items := get() + if len(items) != 1 || string(items[0]["number"]) != "2" || string(items[0]["fixer_queue_position"]) != "2" || string(items[0]["fixer_queue_ahead"]) != "1" { + t.Fatalf("paged items = %+v", items) + } + s.deps.Governor.RecordFixKickDelivered("myorg/other#99") + items = get() + if string(items[0]["fixer_queue_position"]) != "1" || string(items[0]["fixer_queue_ahead"]) != "0" { + t.Fatalf("first queued item must explicitly emit zero ahead: %+v", items) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#2") + items = get() + if _, ok := items[0]["fixer_queue_position"]; ok { + t.Fatal("delivered item still emits fixer_queue_position") + } + if _, ok := items[0]["fixer_queue_ahead"]; ok { + t.Fatal("delivered item still emits fixer_queue_ahead") + } +} diff --git a/src/pkg/dashboard/kiosk_cta.test.js b/src/pkg/dashboard/kiosk_cta.test.js index 7fbcef84f2..71bf418627 100644 --- a/src/pkg/dashboard/kiosk_cta.test.js +++ b/src/pkg/dashboard/kiosk_cta.test.js @@ -16,7 +16,7 @@ test('hiveKioskCTAOn: kiosk=1 only, cta=off opts out', () => { new Function('window', m[0])(window); const on = window.hiveKioskCTAOn; assert.strictEqual(on('https://hive.example/?kiosk=1#section-activity-monitor-section'), true); - assert.strictEqual(on('https://hive.example/?kiosk=1&view=matrix&sound=off'), true); + assert.strictEqual(on('https://hive.example/?kiosk=1&view=reader&sound=off'), true); assert.strictEqual(on('https://hive.example/?kiosk=1&cta=off'), false); assert.strictEqual(on('https://hive.example/'), false); assert.strictEqual(on('https://hive.example/?display=1'), false); @@ -24,12 +24,12 @@ test('hiveKioskCTAOn: kiosk=1 only, cta=off opts out', () => { assert.strictEqual(on('not a url'), false); }); -test('badge wiring: placeholder outside the root, hidden without the body class, lifted and dimmed in matrix', () => { +test('badge wiring: placeholder outside the root, hidden without the body class, lifted and dimmed in Code activity', () => { assert.ok(html.includes("if(window.hiveKioskCTAOn(window.location.href)) document.body.classList.add('kiosk-cta-on');")); const root = html.indexOf(''); const ph = html.indexOf(''); assert.ok(root > 0 && ph > root, 'placeholder must follow the dashboard root'); assert.ok(html.includes('#kiosk-cta { display: none; }')); assert.ok(html.includes('body.kiosk-cta-on #kiosk-cta {')); - assert.ok(html.includes('body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; }')); + assert.ok(html.includes('body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; }')); }); diff --git a/src/pkg/dashboard/matrix_header_tab_test.go b/src/pkg/dashboard/matrix_header_tab_test.go index 40aa056fef..a9178f59bc 100644 --- a/src/pkg/dashboard/matrix_header_tab_test.go +++ b/src/pkg/dashboard/matrix_header_tab_test.go @@ -10,7 +10,7 @@ import ( "github.com/hivecommons/hive/pkg/config" ) -func TestDashboardMatrixHeaderTabHiddenByDefault(t *testing.T) { +func TestDashboardCodeActivityHeaderTabHiddenByDefault(t *testing.T) { raw, err := staticFS.ReadFile("static/index.html") if err != nil { t.Fatalf("reading embedded static/index.html: %v", err) @@ -18,17 +18,27 @@ func TestDashboardMatrixHeaderTabHiddenByDefault(t *testing.T) { html := string(raw) start := strings.Index(html, `id="oc-matrix-tab"`) if start < 0 { - t.Fatal("static/index.html missing the Matrix header tab") + t.Fatal("static/index.html missing the Code activity header tab") } open := html[strings.LastIndex(html[:start], "")] - for _, want := range []string{`href="?kiosk=1&view=matrix"`, ` hidden`, `nav-chip`} { + for _, want := range []string{`href="?kiosk=1&view=reader"`, `target="_blank"`, `rel="noopener"`, ` hidden`, `nav-chip`} { if !strings.Contains(open, want) { - t.Fatalf("Matrix header tab %q missing %q", open, want) + t.Fatalf("Code activity header tab %q missing %q", open, want) } } + if !strings.Contains(html[start:], `>Code activity`) { + t.Fatal("toolbar entry must be labelled Code activity") + } + // One entry: the legacy oc-matrix-tab id is retained, with no side-by-side tab. + if strings.Count(html, `id="oc-matrix-tab"`) != 1 || strings.Contains(html, `id="oc-reader-tab"`) { + t.Fatal("toolbar must carry exactly one Code activity entry") + } + if strings.Contains(html, "view=matrix\"") { + t.Fatal("toolbar still links the retired Matrix view") + } if !strings.Contains(html, "data.matrixEnabled") { - t.Fatal("static/index.html never toggles the Matrix tab from the status payload") + t.Fatal("static/index.html never toggles the Code activity tab from the status payload") } } diff --git a/src/pkg/dashboard/matrix_persist_test.go b/src/pkg/dashboard/matrix_persist_test.go deleted file mode 100644 index 320ce65174..0000000000 --- a/src/pkg/dashboard/matrix_persist_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package dashboard - -import ( - "encoding/json" - "os" - "path/filepath" - "strconv" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/sentinel" -) - -// The backlog survives a restart (#16276): a new source on the same path -// serves the persisted lines, continues the sequence counter so a kiosk -// never sees seq go backwards, and treats a re-observed head as already -// seen. -func TestMatrixSourcePersistRestore(t *testing.T) { - path := filepath.Join(t.TempDir(), "matrix-lines.json") - m, clk := newTestMatrixSource(t, matrixTestConfig()) - m.persistPath = path - m.restore() // no file yet is the normal first boot - if m.Latest() != 0 || len(m.ring) != 0 { - t.Fatalf("missing file restored seq=%d lines=%d", m.Latest(), len(m.ring)) - } - file := sentinel.File{Path: "a.go", Patch: matrixPatch("one", "two")} - if got := m.ingest(matrixObs(1, "h1", file)); got != 2 { - t.Fatalf("ingest = %d, want 2", got) - } - m.persist() - raw, err := os.ReadFile(path) - if err != nil { - t.Fatalf("persisted file: %v", err) - } - var f matrixPersistFile - if err := json.Unmarshal(raw, &f); err != nil || f.Seq != 2 || len(f.Lines) != 2 || f.Lines[1].Line != "two" { - t.Fatalf("persisted %+v err=%v", f, err) - } - - restored, _ := newTestMatrixSource(t, matrixTestConfig()) - restored.now = clk.now - restored.persistPath = path - restored.restore() - lines, latest := restored.Since(0, 10) - if latest != 2 || len(lines) != 2 || lines[0].Line != "one" || lines[1].Seq != 2 { - t.Fatalf("restored latest=%d lines=%+v", latest, lines) - } - if got := restored.ingest(matrixObs(1, "h1", file)); got != 0 { - t.Fatalf("re-observed head after restart added %d lines", got) - } - if got := restored.ingest(matrixObs(2, "h", sentinel.File{Path: "b.go", Patch: matrixPatch("three")})); got != 1 { - t.Fatalf("new PR after restart added %d", got) - } - if restored.Latest() != 3 { - t.Fatalf("sequence did not continue: latest=%d", restored.Latest()) - } - - // A source with no path never touches disk. - plain, _ := newTestMatrixSource(t, matrixTestConfig()) - plain.ingest(matrixObs(1, "h1", file)) - plain.persist() - if entries, _ := os.ReadDir(filepath.Dir(path)); len(entries) != 1 { - t.Fatalf("unexpected files: %v", entries) - } -} - -func TestMatrixSourcePersistCapsAndTolerates(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "matrix-lines.json") - m, _ := newTestMatrixSource(t, matrixTestConfig()) - m.persistPath = path - // More distinct lines than the persist cap, spread over PRs so the - // per-head cap does not bite. - total := matrixPersistLines + 50 - for pr := 0; pr*100 < total; pr++ { - var ls []string - for i := 0; i < 100 && pr*100+i < total; i++ { - ls = append(ls, "line"+strconv.Itoa(pr*100+i)) - } - m.ingest(matrixObs(pr+1, "h", sentinel.File{Path: "a.go", Patch: matrixPatch(ls...)})) - } - if m.Latest() != uint64(total) { - t.Fatalf("latest=%d want %d", m.Latest(), total) - } - m.persist() - restored, _ := newTestMatrixSource(t, matrixTestConfig()) - restored.persistPath = path - restored.restore() - lines, latest := restored.Since(0, matrixBacklogCap) - if latest != uint64(total) || len(lines) != matrixPersistLines || lines[0].Seq != uint64(total-matrixPersistLines+1) { - t.Fatalf("restored latest=%d n=%d first=%d", latest, len(lines), lines[0].Seq) - } - - // Disabling the matrix empties the file too, so a later re-enable does - // not resurrect lines captured under the old config. - m.setConfig(config.DashboardMatrixConfig{}) - m.reset() - empty, _ := newTestMatrixSource(t, matrixTestConfig()) - empty.persistPath = path - empty.restore() - if n := len(empty.ring); n != 0 || empty.Latest() != uint64(total) { - t.Fatalf("after reset restored %d lines, seq %d", n, empty.Latest()) - } - - // Garbage on disk is logged and ignored, never fatal. - if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil { - t.Fatal(err) - } - bad, _ := newTestMatrixSource(t, matrixTestConfig()) - bad.persistPath = path - bad.restore() - if bad.Latest() != 0 || len(bad.ring) != 0 { - t.Fatalf("malformed file restored seq=%d lines=%d", bad.Latest(), len(bad.ring)) - } -} - -// Server.SetMatrixPersistPath hands the path to the source MatrixObserver -// builds, and a source built first still picks the backlog up when it has -// nothing of its own. -func TestServerSetMatrixPersistPath(t *testing.T) { - path := filepath.Join(t.TempDir(), "matrix-lines.json") - seed := matrixPersistFile{Seq: 7, Lines: []matrixLine{{Seq: 7, Repo: matrixTestRepo, PR: 1, Head: "h", Path: "a.go", Line: "kept", At: time.Now().UTC()}}} - raw, _ := json.Marshal(seed) - if err := os.WriteFile(path, raw, 0o644); err != nil { - t.Fatal(err) - } - s := &Server{} - s.SetMatrixPersistPath(path) - if s.MatrixObserver(matrixTestConfig()) == nil { - t.Fatal("no observer") - } - t.Cleanup(s.matrix.close) - if lines, latest := s.matrix.Since(0, 10); latest != 7 || len(lines) != 1 || lines[0].Line != "kept" { - t.Fatalf("observer-built source: latest=%d lines=%+v", latest, lines) - } - - late := &Server{} - if late.MatrixObserver(matrixTestConfig()) == nil { - t.Fatal("no observer") - } - t.Cleanup(late.matrix.close) - late.SetMatrixPersistPath(path) - if latest := late.matrix.Latest(); latest != 7 { - t.Fatalf("late path on an empty source: latest=%d, want 7", latest) - } - var nilSrv *Server - nilSrv.SetMatrixPersistPath(path) -} diff --git a/src/pkg/dashboard/matrix_source.go b/src/pkg/dashboard/matrix_source.go index cb83e374db..863db35127 100644 --- a/src/pkg/dashboard/matrix_source.go +++ b/src/pkg/dashboard/matrix_source.go @@ -2,11 +2,8 @@ package dashboard import ( "crypto/sha256" - "encoding/json" - "errors" - "fmt" "log/slog" - "os" + "slices" "strconv" "sync" "sync/atomic" @@ -30,20 +27,8 @@ const ( matrixMaxFilesPerObs = 300 matrixMaxPatchBytes = 512 << 10 matrixDefaultSinceMax = 200 - // matrixPersistLines is how many of the newest lines survive a restart - // (#16276): enough to refill the kiosk's 120-line window with headroom, - // small enough that each write is a few tens of kilobytes. - matrixPersistLines = 500 ) -// matrixPersistFile is the on-disk shape of the backlog. Seq is the newest -// sequence number so the counter continues across restarts and a kiosk -// never sees seq go backwards (matrix.js resets on that). -type matrixPersistFile struct { - Seq uint64 `json:"seq"` - Lines []matrixLine `json:"lines"` -} - // matrixMaxDedupHashes caps dedup hashes across every tracked PR; a var so // tests can exercise the bound without 100k lines. var matrixMaxDedupHashes = 100000 @@ -67,15 +52,27 @@ type matrixPRState struct { touched time.Time } +type matrixQueuedObservation struct { + observation github.SentinelPatchObservation + epoch string +} + // matrixSource turns sentinel patch observations into a bounded, scrubbed, -// de-duplicated in-memory backlog. Observe never blocks; one goroutine does -// all the parsing. Nothing is written to disk. +// de-duplicated in-memory backlog. It owns the shared observer queue and its +// legacy line projection. Observe never blocks; one goroutine does all the +// parsing. Nothing is written to disk. type matrixSource struct { - cfg atomic.Pointer[config.DashboardMatrixConfig] - in chan github.SentinelPatchObservation - dropped atomic.Uint64 - logger *slog.Logger - now func() time.Time + checkpoints *checkpointSource + // policyMu is held exclusively by setConfig and shared by observers, so + // concurrent Observe calls never contend with each other; only a policy + // update in flight makes an observer back off. + policyMu sync.RWMutex + queuedEpoch atomic.Pointer[string] + cfg atomic.Pointer[config.DashboardMatrixConfig] + in chan matrixQueuedObservation + dropped atomic.Uint64 + logger *slog.Logger + now func() time.Time startOnce sync.Once stopOnce sync.Once @@ -99,11 +96,6 @@ type matrixSource struct { // /api/matrix/lines so the kiosk can tell "no pushes" from "no ingest". ingestAt atomic.Int64 ingestEvery atomic.Int64 - - // persistPath, when set, receives the newest matrixPersistLines lines - // and the sequence counter after every ingest that added lines and on - // reset; restore reads it back on construction. - persistPath string } func newMatrixSource(cfg config.DashboardMatrixConfig, logger *slog.Logger) *matrixSource { @@ -111,7 +103,7 @@ func newMatrixSource(cfg config.DashboardMatrixConfig, logger *slog.Logger) *mat logger = slog.Default() } m := &matrixSource{ - in: make(chan github.SentinelPatchObservation, matrixIngestCap), + in: make(chan matrixQueuedObservation, matrixIngestCap), logger: logger, now: time.Now, stop: make(chan struct{}), @@ -119,15 +111,50 @@ func newMatrixSource(cfg config.DashboardMatrixConfig, logger *slog.Logger) *mat ring: make([]matrixLine, 0, matrixBacklogCap), prs: make(map[string]*matrixPRState), } + m.checkpoints = newCheckpointSource(cfg) m.setConfig(cfg) return m } +// samePolicy reports whether cfg matches the policy already in force. The +// reader poll refreshes the policy on every GET, so an unchanged policy must +// not take the exclusive lock that makes observers back off. +func (m *matrixSource) samePolicy(cfg config.DashboardMatrixConfig) bool { + cur := m.cfg.Load() + return cur != nil && m.queuedEpoch.Load() != nil && cur.Enabled == cfg.Enabled && + slices.Equal(cur.Repos, cfg.Repos) && slices.Equal(cur.ExcludePaths, cfg.ExcludePaths) +} + func (m *matrixSource) setConfig(cfg config.DashboardMatrixConfig) { + if m.samePolicy(cfg) { + return + } + m.policyMu.Lock() + defer m.policyMu.Unlock() + if m.samePolicy(cfg) { + return + } c := cfg c.Repos = append([]string(nil), cfg.Repos...) c.ExcludePaths = append([]string(nil), cfg.ExcludePaths...) m.cfg.Store(&c) + if m.checkpoints != nil { + epoch := m.checkpoints.policyEpoch() + m.checkpoints.configure(c) + nextEpoch := m.checkpoints.policyEpoch() + m.queuedEpoch.Store(&nextEpoch) + if epoch != nextEpoch { + m.reset() + // Drop queued code as well as admitted code on policy changes. + for { + select { + case <-m.in: + default: + return + } + } + } + } } // admits applies the observation-level gates: Matrix active, hive-identified @@ -138,14 +165,21 @@ func (m *matrixSource) admits(obs github.SentinelPatchObservation) bool { } // Observe is the sentinel PatchObserver. It gates the observation, then hands -// it off without blocking: when the ingest channel is full the observation -// is dropped and counted. +// it off without blocking: when a policy update is in flight or the ingest +// channel is full the observation is dropped and counted. Observers hold the +// policy read lock, so sweeps running many observers at once do not drop +// each other. func (m *matrixSource) Observe(obs github.SentinelPatchObservation) { + if !m.policyMu.TryRLock() { + m.dropped.Add(1) + return + } + defer m.policyMu.RUnlock() if !m.admits(obs) { return } select { - case m.in <- obs: + case m.in <- matrixQueuedObservation{observation: obs, epoch: *m.queuedEpoch.Load()}: default: m.dropped.Add(1) } @@ -168,112 +202,49 @@ func (m *matrixSource) run() { select { case <-m.stop: return - case obs := <-m.in: - if m.safeIngest(obs) > 0 { - m.persist() + case queued := <-m.in: + if queued.epoch != m.checkpoints.policyEpoch() { + // Queued under a policy that no longer applies: neither + // projection ingests it. setConfig already reset the + // legacy backlog for the same change, so admitting the + // stale observation there would leak code the new policy + // never saw. + continue + } + before := m.Latest() + added := m.checkpoints.ingest(queued.observation, queued.epoch, m.now()) + m.safeIngest(queued.observation) + if added > 0 && m.Latest() == before { + // Deletion-only checkpoints also wake the reader. The frame + // contains only the legacy sequence hint, never code. + m.nudgeCheckpoint() } } } } -func (m *matrixSource) safeIngest(obs github.SentinelPatchObservation) (added int) { +func (m *matrixSource) nudgeCheckpoint() { defer func() { - if r := recover(); r != nil { - added = 0 - m.logger.Warn("matrix line source dropped an observation after a panic", "repo", obs.Repo, "number", obs.Number, "panic", fmt.Sprint(r)) + if recover() != nil { + m.logger.Warn("checkpoint notification failed") } }() - return m.ingest(obs) -} - -// restore loads the persisted backlog: the lines refill the ring oldest -// first, the sequence counter resumes from the file, and each line's hash -// re-enters its PR's dedup set so re-observing the same head after a -// restart adds nothing. A missing file is the normal first boot; a -// malformed one is logged and ignored. -func (m *matrixSource) restore() { - if m.persistPath == "" { - return - } - raw, err := os.ReadFile(m.persistPath) - if err != nil { - if !errors.Is(err, os.ErrNotExist) { - m.logger.Warn("matrix line source: state file unreadable; starting empty", "path", m.persistPath, "error", err) - } - return - } - var f matrixPersistFile - if err := json.Unmarshal(raw, &f); err != nil { - m.logger.Warn("matrix line source: state file malformed; starting empty", "path", m.persistPath, "error", err) - return - } - if len(f.Lines) > matrixPersistLines { - f.Lines = f.Lines[len(f.Lines)-matrixPersistLines:] - } - now := m.now() m.mu.Lock() - defer m.mu.Unlock() - var last uint64 - for _, l := range f.Lines { - if l.Line == "" || l.Seq <= last { - continue - } - last = l.Seq - m.appendLocked(l) - key := l.Repo + "#" + strconv.Itoa(l.PR) - st := m.prs[key] - if st == nil { - st = &matrixPRState{hashes: make(map[[sha256.Size]byte]time.Time)} - m.prs[key] = st - } - st.touched = now - if st.head != l.Head { - st.head = l.Head - st.headCount = 0 - } - h := sha256.Sum256([]byte(l.Path + "\x00" + l.Line)) - if _, dup := st.hashes[h]; !dup { - m.totalHashes++ - } - st.hashes[h] = l.At - st.headCount++ - } - m.seq = max(f.Seq, last) - if m.seq > 0 { - m.logger.Info("matrix line source restored", "lines", len(m.ring), "seq", m.seq) + seq, notify := m.seq, m.notify + m.mu.Unlock() + if notify != nil { + notify(seq) } } -// persist writes the newest matrixPersistLines lines and the sequence -// counter to persistPath atomically. It snapshots under the lock and writes -// outside it; no path is a no-op. -func (m *matrixSource) persist() { - if m.persistPath == "" { - return - } - m.mu.Lock() - n := len(m.ring) - start := 0 - if n > matrixPersistLines { - start = n - matrixPersistLines - } - f := matrixPersistFile{Seq: m.seq, Lines: make([]matrixLine, 0, n-start)} - for i := start; i < n; i++ { - f.Lines = append(f.Lines, m.ring[(m.next+i)%n]) - } - m.mu.Unlock() - raw, err := json.Marshal(f) - if err != nil { - return - } - tmp := m.persistPath + ".tmp" - err = os.WriteFile(tmp, raw, 0o644) - if err == nil { - err = os.Rename(tmp, m.persistPath) - } - if err != nil { - m.logger.Warn("matrix line source: state file write failed", "path", m.persistPath, "error", err) - } +func (m *matrixSource) safeIngest(obs github.SentinelPatchObservation) (added int) { + defer func() { + if r := recover(); r != nil { + added = 0 + m.logger.Warn("matrix line source dropped an observation after a panic", "repo", obs.Repo, "number", obs.Number) + } + }() + return m.ingest(obs) } // ingest filters one observation into the backlog and returns how many lines @@ -412,13 +383,15 @@ func (m *matrixSource) removeLocked(key string) { // Since returns up to limit backlog lines with Seq > seq, oldest first, and the // latest sequence number. limit <= 0 means a default page. func (m *matrixSource) Since(seq uint64, limit int) ([]matrixLine, uint64) { - return m.SinceMatching(seq, limit, nil) + lines, latest, _ := m.SinceMatching(seq, limit, nil) + return lines, latest } // SinceMatching is Since restricted to lines keep accepts (nil keeps all). // limit counts only kept lines, so a page is never emptied by lines the caller // may not see while kept lines remain past it (hivecommons/hive#15979). -func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine) bool) ([]matrixLine, uint64) { +// The final result reports whether another kept line remains after this page. +func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine) bool) ([]matrixLine, uint64, bool) { if limit <= 0 { limit = matrixDefaultSinceMax } @@ -426,13 +399,16 @@ func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine defer m.mu.Unlock() n := len(m.ring) out := make([]matrixLine, 0, min(limit, n)) - for i := 0; i < n && len(out) < limit; i++ { + for i := 0; i < n; i++ { l := m.ring[(m.next+i)%n] if l.Seq > seq && (keep == nil || keep(l)) { + if len(out) == limit { + return out, m.seq, true + } out = append(out, l) } } - return out, m.seq + return out, m.seq, false } // Latest is the sequence number of the newest accepted line; 0 when none. @@ -446,12 +422,12 @@ func (m *matrixSource) Latest() uint64 { // never sees a sequence number reused. func (m *matrixSource) reset() { m.mu.Lock() + clear(m.ring) m.ring = m.ring[:0] m.next = 0 m.prs = make(map[string]*matrixPRState) m.totalHashes = 0 m.mu.Unlock() - m.persist() } // recordIngest notes that an ingest pass finished at `at` and the next one @@ -505,8 +481,6 @@ func (s *Server) MatrixObserver(cfg config.DashboardMatrixConfig) func(github.Se } if s.matrix == nil { s.matrix = newMatrixSource(cfg, s.logger) - s.matrix.persistPath = s.matrixPersistPath - s.matrix.restore() s.matrix.setNotify(s.nudgeMatrixLines) s.matrix.start() } else { @@ -532,24 +506,3 @@ func (s *Server) RecordMatrixIngest(at time.Time, every time.Duration) { } m.recordIngest(at, every) } - -// SetMatrixPersistPath names the file the Matrix line source keeps its -// newest lines and sequence counter in (#16276), so a restart refills the -// kiosk instead of showing it empty until the next sweep. It must be called -// before the first active MatrixObserver; empty keeps the source in-memory. -func (s *Server) SetMatrixPersistPath(path string) { - if s == nil { - return - } - s.matrixMu.Lock() - defer s.matrixMu.Unlock() - s.matrixPersistPath = path - // A source that already exists but has nothing yet can still take the - // backlog; one with lines keeps them and only persists from here on. - if s.matrix != nil && s.matrix.persistPath == "" && path != "" { - s.matrix.persistPath = path - if s.matrix.Latest() == 0 { - s.matrix.restore() - } - } -} diff --git a/src/pkg/dashboard/matrix_ui_test.go b/src/pkg/dashboard/matrix_ui_test.go index 3b2f0413dc..b8bc26ffe4 100644 --- a/src/pkg/dashboard/matrix_ui_test.go +++ b/src/pkg/dashboard/matrix_ui_test.go @@ -7,142 +7,46 @@ import ( "testing" ) -func TestMatrixUIWiring(t *testing.T) { +func TestMatrixPresentationRetired(t *testing.T) { html := indexHTML(t) - read := func(name string) string { - t.Helper() - b, err := os.ReadFile("static-src/" + name) - if err != nil { - t.Fatal(err) + for _, obsolete := range []string{"HIVE_MATRIX", "hiveMatrixStart", "hiveMatrixAttach", "matrix-mode", "matrix-canvas", "mx.effect", "hive.matrix.", `id="oc-reader-tab"`} { + if strings.Contains(html, obsolete) { + t.Errorf("shipped page retains retired Matrix presentation %q", obsolete) } - return string(b) } - js := read("js/matrix.js") - for _, forbidden := range []string{"innerHTML", "insertAdjacentHTML", "document.write", "new EventSource"} { - if strings.Contains(js, forbidden) { - t.Errorf("matrix.js contains forbidden sink/stream %q", forbidden) - } - } - for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "cancelAnimationFrame", "text.textContent = line.line", "source.addEventListener('code-lines'", "hive.matrix.", "mx.", "'ghost'", "'terminal'", "effect === 'ghost'", "effect === 'terminal'"} { - if !strings.Contains(js, want) { - t.Errorf("matrix.js missing %q", want) - } - } - for _, want := range []string{"window.HIVE_MATRIX = kiosk && view === 'matrix';", "if(window.HIVE_MATRIX){", "hiveMatrixStart();", "if (window.HIVE_MATRIX) window.hiveMatrixAttach(source);"} { - if !strings.Contains(html, want) { - t.Errorf("generated page missing %q", want) - } - } - css := read("css/matrix.css") - for _, rule := range strings.Split(css, "}") { - selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") - if !ok { - continue - } - for _, part := range strings.Split(selector, ",") { - if !strings.HasPrefix(strings.TrimSpace(part), "body.matrix-mode ") { - t.Errorf("unscoped Matrix selector %q", part) - } - } - } - manifest := read("manifest.txt") - for _, file := range []string{"js/matrix.js", "css/matrix.css"} { - if !strings.Contains(manifest, file+"\n") { - t.Errorf("manifest missing %s", file) - } - if !strings.Contains(html, read(file)) { - t.Errorf("generated page is missing current %s", file) + for _, name := range []string{"js/matrix.js", "css/matrix.css"} { + if _, err := os.Stat("static-src/" + name); !os.IsNotExist(err) { + t.Errorf("retired asset %s still exists (err=%v)", name, err) } } } -// Exercise browser lifecycle and pull behavior with deterministic DOM/clock -// doubles. No browser dependencies, network or real animation timers required. -func TestMatrixUIBehavior(t *testing.T) { +// Exercise the status-controlled visibility of the actual toolbar element. +// The reader browser scenarios follow its shipped href and boot the reader. +func TestCodeActivityToolbarStatus(t *testing.T) { node, err := exec.LookPath("node") if err != nil { t.Skip("node unavailable") } - cmd := exec.Command(node, "-e", matrixBrowserTest) + cmd := exec.Command(node, "-e", codeActivityToolbarTest) if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("Matrix browser behavior: %v\n%s", err, out) + t.Fatalf("Code activity toolbar: %v\n%s", err, out) } } -const matrixBrowserTest = ` +const codeActivityToolbarTest = ` const assert = require('assert'); const fs = require('fs'); const vm = require('vm'); -const matrix = fs.readFileSync('static-src/js/matrix.js', 'utf8'); -const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; -async function scenario(query, reduced = false, status = 200) { - const events = {}, docEvents = {}, raf = new Map(), timers = new Map(), requests = [], draws = []; - let id = 0, responseStatus = status, responseSeq = 1; - const context = {clearRect(){}, fillRect(){}, fillText(...a){draws.push(a)}, drawImage(...a){draws.push(a)}}; - const elements = []; - function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], style: {setProperty(){}}, - classList: {add(){}}, setAttribute(){}, append(...a){this.children.push(...a)}, - appendChild(a){this.children.push(a)}, replaceChildren(...a){this.children = a}, getContext(){return context}}; - elements.push(e); return e; } - const body = el('body'); - const doc = {body, hidden: false, createElement: el, - getElementById(id){return elements.find(e => e.id === id)}, - addEventListener(n, fn){(docEvents[n] ||= []).push(fn)}}; - const motion = {matches: reduced, addEventListener(n, fn){this.change = fn}}; - const win = {location: {href: 'https://hive.test/' + query}, innerWidth: 800, innerHeight: 600, - matchMedia(){return motion}, addEventListener(){}}; - const c = vm.createContext({window: win, document: doc, URL, location: {hash: '#activity'}, - history: {replaceState(){}}, localStorage: {getItem(){return null}, setItem(){}}, - requestAnimationFrame(fn){raf.set(++id, fn); return id}, cancelAnimationFrame(i){raf.delete(i)}, - setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, - fetch(url){requests.push(url); return Promise.resolve({status: responseStatus, ok: responseStatus === 200, - json(){return Promise.resolve({seq: responseSeq, lines: [{line: '', repo: 'org/repo', pr: 2, path: 'main.go', at: new Date().toISOString()}]})}})}, - Date, Math}); - vm.runInContext(matrix, c); c.hiveMatrixStart = win.hiveMatrixStart; - vm.runInContext(boot, c); - for (const fn of docEvents.DOMContentLoaded || []) fn(); - const flush = async () => {for(let i=0;i<12;i++) await Promise.resolve()}; - await flush(); - if (!win.HIVE_MATRIX) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-matrix')); return;} - const byClass = n => elements.find(e => e.className === n); - assert.equal(requests[0], '/api/matrix/lines?since=0'); - assert(byClass('matrix-labels').children[0].textContent.includes('public allowlisted repos')); - if (status !== 200) { - assert.equal(raf.size, 0); assert(byClass('matrix-canvas').hidden); - assert(byClass('matrix-notice').textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); - return; - } - if (reduced) { - assert.equal(raf.size, 0); - assert.equal(byClass('matrix-list').children[0].children[1].textContent, ''); - assert(timers.size > 0); - } else { - assert.equal(raf.size, 1); - for (const time of [1, 100]) {const fn = [...raf.values()][0]; raf.clear(); fn(time)} - assert(draws.length > 0); - if (/cascade|ghost|terminal/.test(query)) assert(draws.some(a => a[0] === 'org/repo#2 · main.go')); - if (query.includes('ghost')) assert(draws.some(a => a[0] === 'main.go')); - if (query.includes('terminal')) assert(draws.some(a => a[0] === '+ ')); - } - doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); - assert.equal(raf.size, 0); assert.equal(timers.size, 0); - assert.equal(byClass('matrix-labels').children[2].textContent, 'paused'); - doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); - docEvents.keydown[0]({key: 'p', target: el('body'), preventDefault(){}}); - assert.equal(raf.size, 0); assert.equal(timers.size, 0); - win.hiveMatrixAttach({addEventListener(n, fn){events[n] = fn}}); - responseSeq = 2; events['code-lines'](); await flush(); - assert.equal(requests.at(-1), '/api/matrix/lines?since=1'); - responseStatus = 403; events['code-lines'](); await flush(); - assert(byClass('matrix-canvas').hidden); assert.equal(byClass('matrix-list').children.length, 0); +const html = fs.readFileSync('static/index.html', 'utf8'); +const entry = html.match(/]*id="oc-matrix-tab"[^>]*>[\s\S]*?<\/a>/)[0]; +assert(entry.includes(' hidden')); assert(entry.includes('>Code activity')); +const tab = {hidden: true}; +const document = {getElementById(id) {assert.equal(id, 'oc-matrix-tab'); return tab;}}; +// Use the shipped status handler, including its boolean guard. +const handler = html.match(/if \(typeof data.matrixEnabled === 'boolean'\) \{[^}]*\}/)[0]; +for (const [value, expected] of [[undefined, true], [false, true], [true, false], [undefined, false], [false, true]]) { + vm.runInNewContext(handler, {document, data: {matrixEnabled: value}}); + assert.equal(tab.hidden, expected); } -(async () => { - await scenario(''); await scenario('?view=matrix'); await scenario('?kiosk=1'); - await scenario('?kiosk=1&view=matrix'); - await scenario('?kiosk=1&view=matrix&mx.effect=cascade'); - await scenario('?kiosk=1&view=matrix&mx.effect=ghost'); - await scenario('?kiosk=1&view=matrix&mx.effect=terminal'); - await scenario('?kiosk=1&view=matrix', true); - for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=matrix', false, status); -})().catch(e => {console.error(e); process.exit(1)}); ` diff --git a/src/pkg/dashboard/pr_throughput_ui_test.go b/src/pkg/dashboard/pr_throughput_ui_test.go index 11e7d1673f..acd636c152 100644 --- a/src/pkg/dashboard/pr_throughput_ui_test.go +++ b/src/pkg/dashboard/pr_throughput_ui_test.go @@ -53,7 +53,8 @@ func TestPRThroughputCardPinned(t *testing.T) { "function prtWindowLabel", "dto.recorded_since", "of recorded history", - "fetchPRThroughput(); fetchApprovals();", + "['pr-throughput', fetchPRThroughput]", + "['approvals', fetchApprovals]", "'governor','runs-section','pr-throughput-section','repos-section',", } { if !strings.Contains(html, snippet) { diff --git a/src/pkg/dashboard/progressive_loading.test.js b/src/pkg/dashboard/progressive_loading.test.js new file mode 100644 index 0000000000..1f19093b2c --- /dev/null +++ b/src/pkg/dashboard/progressive_loading.test.js @@ -0,0 +1,366 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const source = fs.readFileSync(path.join(__dirname, 'static-src/js/progressive.js'), 'utf8'); +const html = fs.readFileSync(path.join(__dirname, 'static/index.html'), 'utf8'); +const flush = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); }; +const deferred = () => { + let resolve; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +}; + +function environment({ hidden = false, idle = true } = {}) { + const turns = [], timers = [], errors = [], listeners = {}, intervals = new Map(); + let intervalID = 0; + const window = { location: { hash: '' }, innerHeight: 900 }; + if (idle) window.requestIdleCallback = fn => { turns.push(fn); }; + const sections = new Map(); + const document = { + hidden, + getElementById: id => sections.get(id), + addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, + }; + const statusGuard = html.match(/function dashboardStatusCanRender\(data\) \{[\s\S]*?\n \}/); + assert.ok(statusGuard); + const intervalSource = html.slice(html.indexOf(' function dashboardSetInterval('), html.indexOf(' let historyData =')); + assert.ok(intervalSource.includes('function dashboardRunInterval')); + const api = new Function('window', 'document', 'setTimeout', 'console', 'setInterval', 'clearInterval', + 'let _statusSeqFloor = 0, _lastStatusSeq = 0, _statusInstance = "";\n' + + 'const DASHBOARD_INTERVALS = {};\n' + statusGuard[0] + '\n' + source + '\n' + intervalSource + + '\nreturn {dashboardScheduleWork, dashboardRenderSection, dashboardProgressiveWake, dashboardSetInterval,' + + 'setStatus(floor, latest, instance) {_statusSeqFloor=floor; _lastStatusSeq=latest; _statusInstance=instance;}};' + )(window, document, (fn, ms) => { timers.push({ fn, ms }); }, { + error(...args) { errors.push(args); }, + }, (fn, ms) => { const id = ++intervalID; intervals.set(id, { fn, ms }); return id; }, + id => intervals.delete(id)); + return { + api, window, document, sections, errors, turns, timers, intervals, + start() { timers.shift().fn(); }, + async turn() { assert.ok(turns.length, 'an idle turn must be scheduled'); turns.shift()(); await flush(); }, + visibility(value) { + document.hidden = value; + for (const fn of listeners.visibilitychange || []) fn(); + }, + }; +} + +test('the generated dashboard carries the progressive scheduler', () => { + assert.ok(html.includes(source)); + assert.ok(!html.includes("document.body.style.opacity='0'")); + const afterPaint = html.slice(html.indexOf('function _afterPaint('), html.indexOf('const NAVBAR_CLOCK_TICK_MS')); + assert.ok(afterPaint.includes('requestAnimationFrame')); + assert.ok(!afterPaint.includes('_deferredLoadPromise'), 'navigation cannot await every background API'); +}); + +test('background work yields, stays bounded through decoding, and coalesces repeated ticks', async () => { + const e = environment(); + const gates = [deferred(), deferred(), deferred()]; + const started = []; + const promises = gates.map((gate, index) => + e.api.dashboardScheduleWork('job-' + index, async () => { + started.push(index); + await gate.promise; + return index; + })); + assert.equal(e.api.dashboardScheduleWork('job-0', () => assert.fail('duplicate flight')), promises[0]); + assert.equal(e.turns.length, 0, 'critical status/config get a head start'); + e.start(); + await e.turn(); + await e.turn(); + assert.deepEqual(started, [0, 1]); + assert.equal(e.turns.length, 0, 'no more than two unfinished jobs'); + gates[0].resolve(); + await flush(); + await e.turn(); + assert.deepEqual(started, [0, 1, 2]); + gates[1].resolve(); + gates[2].resolve(); + assert.deepEqual(await Promise.all(promises), [0, 1, 2]); + let refreshed = false; + const again = e.api.dashboardScheduleWork('job-0', () => { refreshed = true; }); + await e.turn(); + await again; + assert.equal(refreshed, true, 'settled jobs can refresh immediately after awaiting them'); +}); + +test('the selected section wins before visible panels, then background panels', async () => { + const e = environment(); + const order = []; + e.window.location.hash = '#section-activity-monitor-section'; + e.sections.set('overview-section', { + getClientRects: () => [{}], + getBoundingClientRect: () => ({ top: 10, bottom: 300 }), + }); + const a = e.api.dashboardScheduleWork('knowledge-stats', () => order.push('background')); + const b = e.api.dashboardScheduleWork('overview-kpi-history', () => order.push('visible')); + const c = e.api.dashboardScheduleWork('stage-tracker', () => order.push('selected')); + e.start(); + while (e.turns.length) await e.turn(); + await Promise.all([a, b, c]); + assert.deepEqual(order, ['selected', 'visible', 'background']); +}); + +test('priority is recomputed after navigation while other work is in flight', async () => { + const e = environment(); + const gate = deferred(), order = []; + e.api.dashboardScheduleWork('first', () => gate.promise); + e.api.dashboardScheduleWork('second', () => gate.promise); + e.api.dashboardScheduleWork('knowledge-stats', () => order.push('knowledge')); + e.api.dashboardScheduleWork('stage-tracker', () => order.push('tracker')); + e.start(); + await e.turn(); + await e.turn(); + e.window.location.hash = '#section-activity-monitor-section'; + gate.resolve(); + await flush(); + await e.turn(); + assert.equal(order[0], 'tracker'); + while (e.turns.length) await e.turn(); +}); + +test('hidden tabs retain jobs without starting them and resume once', async () => { + const e = environment({ hidden: true }); + let runs = 0; + const pending = e.api.dashboardScheduleWork('cost', () => runs++); + e.start(); + assert.equal(e.turns.length, 0); + e.visibility(false); + e.visibility(true); + await e.turn(); + assert.equal(runs, 0, 'a tab can become hidden after scheduling'); + e.visibility(false); + await e.turn(); + await pending; + assert.equal(runs, 1); +}); + +test('synchronous failures reject, release their slot, and do not strand other panels', async () => { + const e = environment(); + const rejected = assert.rejects(e.api.dashboardScheduleWork('bad', () => { + throw new Error('broken panel'); + }), /broken panel/); + let ran = false; + const good = e.api.dashboardScheduleWork('good', () => { ran = true; }); + e.start(); + while (e.turns.length) await e.turn(); + await rejected; + await good; + assert.equal(ran, true); +}); + +test('visibility resume and overlapping poll ticks use the same bounded flights', async () => { + const e = environment(), gate = deferred(), started = []; + for (const key of ['cost', 'git-version', 'stage-tracker']) { + e.api.dashboardSetInterval(key, async () => { + started.push(key); + await gate.promise; + }, 1000); + } + let watchdog = 0; + e.api.dashboardSetInterval('sse-watchdog', () => watchdog++, 1000); + e.visibility(true); + assert.equal(e.intervals.size, 0); + e.visibility(false); + assert.equal(watchdog, 1, 'liveness must not wait behind background panels'); + e.start(); + await e.turn(); + await e.turn(); + assert.equal(started.length, 2); + for (const timer of e.intervals.values()) timer.fn(); + await flush(); + assert.equal(started.length, 2, 'new ticks cannot overlap existing panel requests'); + gate.resolve(); + await flush(); + while (e.turns.length) await e.turn(); + assert.equal(started.length, 3); + assert.equal(new Set(started).size, 3); +}); + +test('advisory and approvals bootstrap uses the same bounded queue instead of a request burst', async () => { + const e = environment(), gate = deferred(), started = []; + const panels = html.match(/function v4RefreshPanels\(\) \{[\s\S]*?\n \}/); + assert.ok(panels); + const keys = ['advice', 'recommendation', 'lifecycle', 'throughput', 'approvals']; + const functions = keys.map(key => async () => { started.push(key); await gate.promise; }); + new Function('dashboardScheduleWork', 'fetchHiveAdvice', 'fetchACMMReco', 'fetchLifecycle', + 'fetchPRThroughput', 'fetchApprovals', panels[0] + '\nv4RefreshPanels();', + )(e.api.dashboardScheduleWork, ...functions); + e.start(); + await e.turn(); + await e.turn(); + assert.equal(started.length, 2); + gate.resolve(); + await flush(); + while (e.turns.length) await e.turn(); + assert.deepEqual(started, keys); +}); + +test('rendering coalesces snapshots and paints one section per idle turn', async () => { + const e = environment(), rendered = []; + e.api.dashboardRenderSection('tokens', ['token-panel'], () => rendered.push('stale')); + e.api.dashboardRenderSection('tokens', ['token-panel'], () => rendered.push('latest')); + e.api.dashboardRenderSection('tracker', ['activity-monitor-section'], () => rendered.push('tracker')); + e.window.location.hash = '#section-activity-monitor-section'; + await e.turn(); + assert.deepEqual(rendered, ['tracker']); + await e.turn(); + assert.deepEqual(rendered, ['tracker', 'latest']); +}); + +test('hidden render snapshots stay bounded and resume with the newest state', async () => { + const e = environment({ hidden: true }); + let rendered; + for (let i = 0; i < 100; i++) { + e.api.dashboardRenderSection('agents', ['agents-section'], () => { rendered = i; }); + } + assert.equal(e.turns.length, 0); + e.visibility(false); + await e.turn(); + assert.equal(rendered, 99); + assert.equal(e.turns.length, 0); +}); + +test('a broken renderer is reported without blocking another section', async () => { + const e = environment(); + let ran = false; + e.api.dashboardRenderSection('bad', [], () => { throw new Error('bad render'); }); + e.api.dashboardRenderSection('good', [], () => { ran = true; }); + await e.turn(); + assert.equal(e.errors.length, 1); + await e.turn(); + assert.equal(ran, true); +}); + +test('queued snapshots recheck mutation floors, ordering, and server instance at execution', async () => { + const e = environment(), rendered = []; + e.api.dashboardRenderSection('old', [], () => rendered.push('old'), { statusSeq: 4, statusInstance: 'a' }); + e.api.setStatus(5, 5, 'a'); + await e.turn(); + assert.deepEqual(rendered, [], 'an optimistic mutation cannot be reverted by queued old data'); + e.api.dashboardRenderSection('old-instance', [], () => rendered.push('old-instance'), { statusSeq: 100, statusInstance: 'a' }); + e.api.setStatus(0, 1, 'b'); + await e.turn(); + assert.deepEqual(rendered, [], 'a restarted server invalidates queued snapshots from its predecessor'); + e.api.dashboardRenderSection('older', [], () => rendered.push('older'), { statusSeq: 1, statusInstance: 'b' }); + e.api.setStatus(0, 2, 'b'); + await e.turn(); + assert.deepEqual(rendered, []); + e.api.dashboardRenderSection('fresh', [], () => rendered.push('fresh'), { statusSeq: 2, statusInstance: 'b' }); + await e.turn(); + assert.deepEqual(rendered, ['fresh']); + e.api.dashboardRenderSection('legacy', [], () => rendered.push('legacy'), {}); + await e.turn(); + assert.deepEqual(rendered, ['fresh', 'legacy']); +}); + +test('a queued worker redraw survives newer status snapshots with unchanged workers', async () => { + const e = environment(); + const redraw = html.match(/dashboardRenderSection\('tracker-workers',[^\n]+/); + assert.ok(redraw); + let latestWorkers = ['working'], rendered; + const snapshot = { statusSeq: 1, statusInstance: 'a' }; + new Function('dashboardRenderSection', 'renderStageTracker', 'data', redraw[0])( + e.api.dashboardRenderSection, () => { rendered = latestWorkers; }, snapshot, + ); + e.api.setStatus(0, 2, 'a'); + latestWorkers = ['working', 'newest']; + await e.turn(); + assert.deepEqual(rendered, ['working', 'newest']); +}); + +test('agent-status bursts do not rebuild hidden cost and agent tables', async () => { + const e = environment({ hidden: true }); + e.window._lastStatus = { agents: [] }; + const begin = html.indexOf(" source.addEventListener('agent-status',"); + const end = html.indexOf(' // The pod announces', begin); + assert.ok(begin > 0 && end > begin); + let handler, costs = 0, agents = 0; + const noop = () => {}; + const source = { addEventListener(event, fn) { assert.equal(event, 'agent-status'); handler = fn; } }; + new Function('window', 'source', 'noteSSEFrame', 'noteAgentNowUpdate', 'ocUpdateSidebarAgents', + '_ocSelectedAgent', 'ocRenderAgentDetail', 'applyPinOverrides', 'dashboardRenderSection', + '_dropdownOpen', '_configModalOpen', 'renderAgents', '_lastCost', 'renderCost', + 'ocUpdateFocusedState', 'applyACMMVisibility', 'refreshWelcomeAutoChecks', + html.slice(begin, end), + )(e.window, source, noop, noop, noop, null, noop, noop, e.api.dashboardRenderSection, + false, false, () => agents++, {}, () => costs++, noop, noop, noop); + for (let i = 0; i < 10; i++) handler({ data: JSON.stringify({ agents: [{ name: 'worker-' + i }] }) }); + assert.equal(agents, 0); + assert.equal(costs, 0); + e.visibility(false); + await e.turn(); + await e.turn(); + assert.equal(agents, 1); + assert.equal(costs, 1); + assert.equal(e.window._lastStatus.agents[0].name, 'worker-9'); +}); + +test('browsers without requestIdleCallback still yield with bounded work', async () => { + const e = environment({ idle: false }); + let ran = false; + const result = e.api.dashboardScheduleWork('cost', () => { ran = true; }); + e.start(); + assert.equal(ran, false); + assert.equal(e.timers.length, 1); + assert.ok(e.timers[0].ms > 0); + e.timers.shift().fn(); + await result; + assert.equal(ran, true); +}); + +test('backend discovery retains its slot until each model request is decoded', async () => { + const discovery = html.match(/async function refreshBackendDiscovery\(force\) \{[\s\S]*?\n \}/); + assert.ok(discovery); + const calls = [], gate = deferred(); + const run = new Function('INFERENCE_BACKENDS', 'fetchInferenceModels', 'fetchConfiguredGateways', + discovery[0] + '\nreturn refreshBackendDiscovery(true);' + )(['one', 'two'], async (backend, force) => { + assert.equal(force, true); + calls.push(backend); + if (backend === 'one') await gate.promise; + }, async () => { calls.push('gateways'); }); + await flush(); + assert.deepEqual(calls, ['one']); + gate.resolve(); + await run; + assert.deepEqual(calls, ['one', 'two', 'gateways']); +}); + +for (const readyState of ['loading', 'interactive', 'complete']) { + test('modal initialization waits for later main-script constants when readyState is ' + readyState, () => { + const install = html.match(/\(function installModalScrollLock\(\) \{[\s\S]*?\n \}\)\(\);/); + const helpers = html.slice(html.indexOf(' const HIVE_MODAL_SCROLL_EPS ='), html.indexOf(' // On narrow viewports a .hive-dialog')); + assert.ok(install); + assert.ok(helpers.includes('function hiveModalScrollInit')); + assert.ok(html.indexOf(install[0]) < html.indexOf(helpers), 'exercise production declaration order'); + const callbacks = [], classes = new Set(['modal-scroll']); + const scroller = { + scrollHeight: 100, clientHeight: 10, scrollTop: 0, dataset: {}, + addEventListener() {}, + classList: { + contains: cls => classes.has(cls), add: cls => classes.add(cls), + toggle(cls, on) { if (on) classes.add(cls); else classes.delete(cls); }, + }, + }; + const root = { classList: { toggle() {} } }; + const document = { + readyState, body: root, documentElement: root, + querySelectorAll: selector => selector.startsWith('.modal-scroll') ? [scroller] : [], + addEventListener(event, callback) { + assert.equal(event, 'DOMContentLoaded'); + callbacks.push(callback); + }, + }; + assert.doesNotThrow(() => new Function('document', 'window', 'MutationObserver', 'queueMicrotask', + install[0] + '\n' + helpers, + )(document, { addEventListener() {} }, class { observe() {} }, fn => callbacks.push(fn))); + assert.equal(scroller.dataset.modalScrollWired, undefined, 'initialization must not run mid-script'); + assert.equal(callbacks.length, 1); + callbacks[0](); + assert.equal(scroller.dataset.modalScrollWired, '1'); + assert.equal(classes.has('is-scrollable-more'), true); + }); +} diff --git a/src/pkg/dashboard/progressive_loading_test.go b/src/pkg/dashboard/progressive_loading_test.go new file mode 100644 index 0000000000..713471b8da --- /dev/null +++ b/src/pkg/dashboard/progressive_loading_test.go @@ -0,0 +1,16 @@ +package dashboard + +import ( + "os/exec" + "testing" +) + +func TestDashboardProgressiveLoading(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not on PATH — progressive dashboard behavior not executed") + } + if out, err := exec.Command(node, "--test", "progressive_loading.test.js").CombinedOutput(); err != nil { + t.Fatalf("progressive dashboard behavior failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/reader_ui_test.go b/src/pkg/dashboard/reader_ui_test.go new file mode 100644 index 0000000000..fa3c891a07 --- /dev/null +++ b/src/pkg/dashboard/reader_ui_test.go @@ -0,0 +1,267 @@ +package dashboard + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +func TestReaderUIWiring(t *testing.T) { + html := indexHTML(t) + read := func(name string) string { + t.Helper() + b, err := os.ReadFile("static-src/" + name) + if err != nil { + t.Fatal(err) + } + return string(b) + } + js := read("js/reader.js") + for _, forbidden := range []string{"innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "new EventSource", "Math.random", "AudioContext", "new Audio"} { + if strings.Contains(js, forbidden) { + t.Errorf("reader.js contains forbidden sink/effect %q", forbidden) + } + } + for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "'&format=regions'", "source.addEventListener('code-lines'", "'wheel'", "'touchstart'", "'\\u2212 '"} { + if !strings.Contains(js, want) { + t.Errorf("reader.js missing %q", want) + } + } + for _, want := range []string{"window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix');", "document.body.classList.add('reader-mode');", "hiveReaderStart();", "if (window.HIVE_READER) window.hiveReaderAttach(source);", `id="oc-matrix-tab" href="?kiosk=1&view=reader"`, "getElementById('oc-matrix-tab')"} { + if !strings.Contains(html, want) { + t.Errorf("generated page missing %q", want) + } + } + start := strings.Index(html, `id="oc-matrix-tab"`) + open := html[strings.LastIndex(html[:start], "")] + if !strings.Contains(open, " hidden") { + t.Errorf("reader header tab %q must be hidden until the status payload enables it", open) + } + css := read("css/reader.css") + // Long text wraps at a fixed size and the feed scrolls natively. + for _, want := range []string{"white-space: pre-wrap; overflow-wrap: anywhere;", "body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto;", "font: 20px/1.5 monospace;", "body.reader-mode .reader-context { color: var(--reader-text); }"} { + if !strings.Contains(css, want) { + t.Errorf("reader.css missing %q", want) + } + } + for _, forbidden := range []string{"text-overflow", "vw;", "line-clamp", "nowrap"} { + if strings.Contains(css, forbidden) { + t.Errorf("reader.css must not shrink or truncate text (%q)", forbidden) + } + } + for _, rule := range strings.Split(css, "}") { + selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") + if !ok { + continue + } + for _, part := range strings.Split(selector, ",") { + if !strings.HasPrefix(strings.TrimSpace(part), "body.reader-mode ") { + t.Errorf("unscoped reader selector %q", part) + } + } + } + manifest := read("manifest.txt") + for _, file := range []string{"js/reader.js", "css/reader.css"} { + if !strings.Contains(manifest, file+"\n") { + t.Errorf("manifest missing %s", file) + } + if !strings.Contains(html, read(file)) { + t.Errorf("generated page is missing current %s", file) + } + } +} + +// Exercise rendering, pacing, pause and reduced motion with deterministic +// DOM/clock doubles; no browser, network or real timers required. +func TestReaderUIBehavior(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node unavailable") + } + cmd := exec.Command(node, "-e", readerBrowserTest) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("reader browser behavior: %v\n%s", err, out) + } +} + +const readerBrowserTest = ` +const assert = require('assert'); +const fs = require('fs'); +const vm = require('vm'); +const reader = fs.readFileSync('static-src/js/reader.js', 'utf8'); +// Follow the actual shipped toolbar link, rather than a separately hard-coded URL. +const page = fs.readFileSync('static/index.html', 'utf8'); +const toolbar = page.match(/]*id="oc-matrix-tab"[^>]*>/)[0]; +assert(toolbar.includes('target="_blank"')); assert(toolbar.includes('rel="noopener"')); +const toolbarQuery = toolbar.match(/href="([^"]+)"/)[1].replaceAll('&', '&'); +const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; +const at = '2026-11-03T12:00:00Z'; +const first = [ + {seq: 1, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', op: '+', at}, + {seq: 2, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', at}, + {seq: 3, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, + {seq: 4, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, + {seq: 5, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: ' old()', op: '-', at}, + {seq: 6, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tunchanged()', op: ' ', at}, + {seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', op: ' ', at}, + {seq: 8, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://github.com/org/other/pull/7', at}, +]; +async function scenario(query, opts = {}) { + const docEvents = {}, timers = new Map(), requests = [], scrolls = [], sse = {}; + let id = 0, status = opts.status || 200, seq = 8, lines = first; + const elements = []; + function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], listeners: {}, attrs: {}, className: '', + textContent: '', hidden: false, scrollTop: 0, offsetHeight: 10, classList: {add(){}}, + setAttribute(k, v){this.attrs[k] = v}, append(...a){this.children.push(...a)}, appendChild(a){this.children.push(a); return a}, + removeChild(a){this.children.splice(this.children.indexOf(a), 1)}, replaceChildren(...a){this.children = a}, + addEventListener(n, fn){this.listeners[n] = fn}, scrollIntoView(o){scrolls.push(o)}}; + elements.push(e); return e; } + const doc = {body: el('body'), hidden: false, createElement: el, + getElementById(id){return elements.find(e => e.id === id)}, + addEventListener(n, fn){(docEvents[n] ||= []).push(fn)}}; + const motion = {matches: !!opts.reduced, addEventListener(n, fn){this.change = fn}}; + const win = {location: {href: 'https://hive.test/' + query}, matchMedia(){return motion}, addEventListener(){}}; + const c = vm.createContext({window: win, document: doc, URL, location: {hash: ''}, history: {replaceState(){}}, + localStorage: {getItem(){return null}, setItem(){}}, + requestAnimationFrame(){throw new Error('reader must not animate frames')}, + setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, + fetch(url){requests.push(url); const regions = []; + lines.forEach(line => { + let last = regions[regions.length - 1]; + if (!last || last.path !== line.path || last.repo !== line.repo) regions.push(last = {...line, seq: line.seq, lines: []}); + last.lines.push({op: line.op || '+', line: line.line}); + }); + let body = {seq, latest: seq, epoch: 'policy-1', source: 'Pushed PR', regions}; lines = []; + if (opts.pages && opts.pages.length) body = opts.pages.shift(); + return Promise.resolve({status, ok: status === 200, json(){return Promise.resolve(body)}})}, + Date, Math}); + vm.runInContext(reader, c); c.hiveReaderStart = win.hiveReaderStart; + vm.runInContext(boot, c); + for (const fn of docEvents.DOMContentLoaded || []) fn(); + const flush = async () => {for (let i = 0; i < 64; i++) await Promise.resolve()}; + await flush(); + assert.equal(!!win.HIVE_READER, /[?&]kiosk=1(&|$)/.test(query) && /[?&]view=(reader|matrix)(&|$)/.test(query), query); + if (!win.HIVE_READER) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-reader')); return;} + const byClass = n => elements.find(e => e.className === n); + const feed = byClass('reader-feed'), statusEl = byClass('reader-status'), button = byClass('reader-pause'); + const fire = () => {assert.equal(timers.size, 1); const [k, fn] = [...timers][0]; timers.delete(k); fn()}; + const key = (key, code) => docEvents.keydown[0]({key, code, target: doc.body, preventDefault(){}}); + assert.equal(requests[0], '/api/matrix/lines?since=0&format=regions'); + if (status !== 200) { + assert.equal(feed.children.length, 0); assert.equal(timers.size, 0); + assert(statusEl.textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); + return; + } + const meta = card => card.children[0].children, rows = card => card.children[1].children.map(r => r.textContent); + if (opts.boundaries) { + // Two complete regions in one file remain separate across pages. The + // reader follows continuation rather than skipping to source.latest. + assert.equal(requests.length, 2); + assert.equal(requests[1], '/api/matrix/lines?since=1&format=regions'); + assert.equal(feed.children.length, 2); + assert.deepEqual(rows(feed.children[0]), ['+ one\n']); + assert.deepEqual(rows(feed.children[1]), ['− two\n']); + assert.equal(meta(feed.children[1])[3].textContent, 'Buffered snapshot'); + win.hiveReaderAttach({addEventListener(n, fn){sse[n] = fn}}); + opts.pages.push({seq: 3, latest: 3, epoch: 'policy-2', regions: [{repo: 'org/repo', pr: 2, path: 'main.go', seq: 3, at, lines: [{op: '+', line: 'new policy'}]}]}); + sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 1); + assert.deepEqual(rows(feed.children[0]), ['+ new policy\n']); + byClass('reader-pause reader-replay').listeners.click(); + assert.equal(feed.children.length, 1); // old policy is gone from replay too + assert.deepEqual(rows(feed.children[0]), ['+ new policy\n']); + // Busy feeds evict whole regions under line, text and viewport bounds. + const base = {repo: 'org/repo', pr: 2, path: 'main.go', at}; + opts.pages.push({seq: 10, latest: 10, epoch: 'policy-2', regions: Array.from({length: 7}, (_, i) => ({...base, seq: i + 4, lines: Array.from({length: 200}, () => ({op: '+', line: 'bounded line'}))}))}); + sse['code-lines'](); await flush(); + assert(feed.children.reduce((n, card) => n + rows(card).length, 0) <= 1200); + assert(feed.children.every(card => rows(card).length === 1 || rows(card).length === 200)); + opts.pages.push({seq: 50, latest: 50, epoch: 'policy-2', regions: Array.from({length: 40}, (_, i) => ({...base, seq: i + 11, lines: [{op: '+', line: 'one'}]}))}); + sse['code-lines'](); await flush(); assert.equal(feed.children.length, 32); + opts.pages.push({seq: 70, latest: 70, epoch: 'policy-2', regions: Array.from({length: 20}, (_, i) => ({...base, seq: i + 51, lines: [{op: '+', line: 'safe '.repeat(3000)}]}))}); + sse['code-lines'](); await flush(); + assert(feed.children.reduce((n, card) => n + rows(card).join('').length * 2, 0) < 256 * 1024); + status = 404; sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 0); + return; + } + + const checkFirst = card => { + // One contiguous region: blank, indented and repeated lines kept as text. + // Context retains its space prefix and stays neutral, including blank lines. + assert.deepEqual(rows(card), ['+ \n', '+ \n', '+ \tx := 1\n', '+ \tx := 1\n', '\u2212 old()\n', ' \tunchanged()\n', ' \n']); + assert.equal(card.children[1].tagName, 'PRE'); + assert.deepEqual(card.children[1].children.map(r => r.className), ['reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-del', 'reader-line reader-context', 'reader-line reader-context']); + const [repo, file, stage, delivery, time] = meta(card); + assert.equal(repo.tagName, 'A'); assert.equal(repo.textContent, 'org/repo #2'); + assert.equal(repo.href, 'https://github.com/org/repo/pull/2'); assert.equal(repo.attrs.rel, 'noopener noreferrer'); + assert.equal(file.textContent, 'main.go'); assert.equal(stage.textContent, 'Pushed PR'); assert.equal(delivery.textContent, 'Buffered snapshot'); + assert.equal(time.tagName, 'TIME'); assert.equal(time.attrs.datetime, '2026-11-03T12:00:00.000Z'); + assert(time.textContent.startsWith('observed ')); + }; + const checkSecond = card => { + assert.equal(meta(card)[0].href, 'https://github.com/org/other/pull/7'); + assert.equal(meta(card)[1].textContent, 'README.md'); + assert.equal(rows(card)[0], '+ ' + 'a very long line '.repeat(40) + '\n'); + }; + win.hiveReaderAttach({addEventListener(n, fn){sse[n] = fn}}); + if (opts.reduced) { + // Static and scrollable: everything shown at once, nothing scheduled or scrolled. + assert.equal(feed.children.length, 2); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); + checkFirst(feed.children[0]); checkSecond(feed.children[1]); + lines = [{seq: 9, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 9; + sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 3); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); + return; + } + // The first paragraph is shown; the next waits for it to be read. + assert.equal(feed.children.length, 1); checkFirst(feed.children[0]); + assert.equal(timers.size, 1); assert.equal(scrolls.at(-1).behavior, 'smooth'); + assert(statusEl.textContent.includes('1 change waiting')); + // Incoming work queues behind the paragraph being read. + lines = [{seq: 9, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 9; + sse['code-lines'](); await flush(); + assert.equal(requests.at(-1), '/api/matrix/lines?since=8&format=regions'); + assert.equal(feed.children.length, 1); assert.equal(timers.size, 1); + // P pauses and resumes; the button mirrors it. + key('p'); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); + assert.equal(button.attrs['aria-pressed'], 'true'); assert(statusEl.textContent.startsWith('paused')); + key(' ', 'Space'); assert.equal(timers.size, 1); assert.equal(button.textContent, 'Pause'); + fire(); assert.equal(feed.children.length, 2); checkSecond(feed.children[1]); + // Wheel, touch and navigation keys pause for inspection; the button resumes. + byClass('reader-scroll').listeners.wheel(); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); + button.listeners.click(); assert.equal(timers.size, 1); + byClass('reader-scroll').listeners.touchstart(); assert.equal(timers.size, 0); + button.listeners.click(); key('PageDown'); assert.equal(timers.size, 0); + button.listeners.click(); assert.equal(timers.size, 1); + // Quiet hold after consuming the queued paragraph; no automatic replay. + fire(); assert.equal(feed.children.length, 3); assert.equal(rows(feed.children[2])[0], '+ next\n'); + fire(); assert.equal(timers.size, 0); assert(statusEl.textContent.includes('Caught up')); + sse['code-lines'](); await flush(); assert.equal(timers.size, 0); assert.equal(feed.children.length, 3); + // Replay requires a deliberate click and is labelled on every card. + byClass('reader-pause reader-replay').listeners.click(); + assert.equal(feed.children.length, 1); assert.equal(meta(feed.children[0])[3].textContent, 'Replay · buffered snapshot'); + doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); + assert.equal(timers.size, 0); assert.equal(feed.children.length, 0); + doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); + assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('No buffered checkpoints')); + assert(byClass('reader-freshness').textContent.includes('empty does not mean no work')); + status = 403; sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('Sign in')); +} +(async () => { + await scenario(''); await scenario('?view=reader'); await scenario('?view=matrix'); await scenario('?kiosk=1'); + // Saved Matrix display URLs (view=matrix) are a deprecated alias for the reader. + await scenario('?kiosk=1&view=matrix&sound=off'); + await scenario(toolbarQuery); + await scenario('?kiosk=1&view=reader', {reduced: true}); + const region = {repo: 'org/repo', pr: 2, path: 'main.go', at}; + await scenario('?kiosk=1&view=reader', {reduced: true, boundaries: true, pages: [ + {seq: 1, latest: 2, epoch: 'policy-1', regions: [{...region, seq: 1, lines: [{op: '+', line: 'one'}]}]}, + {seq: 2, latest: 2, epoch: 'policy-1', regions: [{...region, seq: 2, lines: [{op: '-', line: 'two'}]}]}, + ]}); + for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=reader', {status}); +})().catch(e => {console.error(e); process.exit(1)}); +` diff --git a/src/pkg/dashboard/review_question_autodecide.go b/src/pkg/dashboard/review_question_autodecide.go new file mode 100644 index 0000000000..e37d8d127b --- /dev/null +++ b/src/pkg/dashboard/review_question_autodecide.go @@ -0,0 +1,473 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Reviewer-question auto-decide (hivecommons/hive#16578 follow-up). +// +// A review perspective on the hive's own PR sometimes ends with a QUESTION +// rather than a finding — "should this merge ahead of the workflow edit?", +// "confirm the relay may lift the hold" — and the tracker parked the row at +// 085 "Needs human decision" on the wording alone (docs#618 sat with CI 4/4 +// and Review 5/5 clean; hive#16456 likewise). The owner's verdict on those: +// "this is auto-merge material, not needs-human". +// +// This sweep classifies the ask (review.ClassifyDecisionQuestion): a +// POLICY SIGN-OFF stays the person's; a SCOPE / FOLLOW-UP QUESTION on a +// hive-authored PR with CI green and no unresolved finding runs the +// existing "Let hive decide" pipeline (runDelegatedDecision) with the +// hive as requester. An approve verdict admits the PR to the merge queue +// and files the question as a follow-up issue; a direction verdict routes +// the fixer; an owner-only / recommend-only verdict keeps the park, with +// the recommendation on the row. At most one auto-delegate runs per head +// (a new push asks again). Off switch: governor.review.auto_decide_questions. + +const ( + // reviewQuestionAutodecideInterval paces the sweep between published + // status snapshots. + reviewQuestionAutodecideInterval = 2 * time.Minute + // reviewQuestionAutodecideMaxPerSweep bounds the paid decisions one + // sweep may start. + reviewQuestionAutodecideMaxPerSweep = 3 + // reviewQuestionAutodecideCountWindow is the /api/status counter's window + // (review_questions_autodecided_1h). + reviewQuestionAutodecideCountWindow = time.Hour + // reviewQuestionAutodecideRetention bounds the marker ledger. + reviewQuestionAutodecideRetention = 30 * 24 * time.Hour + // reviewQuestionFollowUpTitleMax caps the follow-up issue title. + reviewQuestionFollowUpTitleMax = 120 + // reviewQuestionFollowUpLabel marks the follow-up issues this sweep files. + reviewQuestionFollowUpLabel = "follow-up" +) + +// reviewQuestionAutodecidePath is the once-per-head marker ledger. +var reviewQuestionAutodecidePath = "/data/review-question-autodecide.json" + +// reviewQuestionAutodecideMarker records one auto-delegate on a head. +type reviewQuestionAutodecideMarker struct { + Head string `json:"head"` + At time.Time `json:"at"` + Class string `json:"class"` + Reason string `json:"reason"` + Verdict string `json:"verdict,omitempty"` + Rule string `json:"rule,omitempty"` + // FollowUp is the follow-up issue filed on an approve verdict (0: none). + FollowUp int `json:"follow_up,omitempty"` +} + +// reviewQuestionAutodecide is the sweep's pacing state and marker ledger. +type reviewQuestionAutodecide struct { + mu sync.Mutex + running bool + lastAt time.Time + path string + loaded bool + items map[string]reviewQuestionAutodecideMarker +} + +func (st *reviewQuestionAutodecide) filePath() string { + if st.path != "" { + return st.path + } + return reviewQuestionAutodecidePath +} + +// load reads the ledger once; an unreadable file starts empty. +func (st *reviewQuestionAutodecide) load() { + if st.loaded { + return + } + st.loaded = true + if st.items == nil { + st.items = map[string]reviewQuestionAutodecideMarker{} + } + data, err := os.ReadFile(st.filePath()) + if err != nil { + return + } + var items map[string]reviewQuestionAutodecideMarker + if json.Unmarshal(data, &items) == nil && items != nil { + st.items = items + } +} + +func (st *reviewQuestionAutodecide) persist() error { + data, err := json.MarshalIndent(st.items, "", " ") + if err != nil { + return err + } + path := st.filePath() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// seen reports whether repo#number already auto-delegated on head. +func (st *reviewQuestionAutodecide) seen(repo string, number int, head string) bool { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + m, ok := st.items[operatorActionKey(repo, number)] + return ok && strings.EqualFold(m.Head, head) +} + +// mark records an auto-delegate on head, dropping markers past retention. +func (st *reviewQuestionAutodecide) mark(repo string, number int, m reviewQuestionAutodecideMarker) error { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + for k, old := range st.items { + if m.At.Sub(old.At) > reviewQuestionAutodecideRetention { + delete(st.items, k) + } + } + st.items[operatorActionKey(repo, number)] = m + return st.persist() +} + +// update rewrites the marker for repo#number in place (verdict, follow-up). +func (st *reviewQuestionAutodecide) update(repo string, number int, fn func(*reviewQuestionAutodecideMarker)) error { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + key := operatorActionKey(repo, number) + m, ok := st.items[key] + if !ok { + return nil + } + fn(&m) + st.items[key] = m + return st.persist() +} + +// countSince is the number of auto-delegates recorded within window of now. +func (st *reviewQuestionAutodecide) countSince(now time.Time, window time.Duration) int { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + n := 0 + for _, m := range st.items { + if !m.At.IsZero() && now.Sub(m.At) <= window && !m.At.After(now) { + n++ + } + } + return n +} + +// reviewQuestionsAutodecided1h is the /api/status counter. +func (s *Server) reviewQuestionsAutodecided1h(now time.Time) int { + if s == nil { + return 0 + } + return s.reviewQuestionAuto.countSince(now, reviewQuestionAutodecideCountWindow) +} + +// reviewQuestionAutodecideEnabled is governor.review.auto_decide_questions +// (default on); unreadable config counts as on. +func (s *Server) reviewQuestionAutodecideEnabled() bool { + if s == nil || s.deps == nil || s.deps.Config == nil { + return config.GovernorReviewConfig{}.AutoDecideQuestionsEnabled() + } + return s.deps.Config.Governor.Review.AutoDecideQuestionsEnabled() +} + +// reviewQuestionCandidate is one 085 row a reviewer's question parked. +type reviewQuestionCandidate struct { + Repo string + Number int + Head string + Question string + Reason string + Caption string + // HiveAuthored is the row's own authorship read (hive-authored or + // adopted in place by the hive). + HiveAuthored bool +} + +// reviewQuestionCandidates picks the tracker rows the sweep may consider: a +// PR parked at 085 by a reviewer's question, on a known head, not on hold, +// CI neither red nor still running. Classification (fork, files, findings) +// happens per candidate afterwards. +func reviewQuestionCandidates(items []StageTrackerItem, qualify func(string) string) []reviewQuestionCandidate { + var out []reviewQuestionCandidate + for _, it := range items { + if it.Kind != "pr" || it.Stage != trackerNumberNeedsDecision || it.Head == "" { + continue + } + dn := it.DecisionNeeded + if dn == nil || dn.AskedBy != decisionAskedByReviewer || strings.TrimSpace(dn.Question) == "" { + continue + } + if it.Hold != nil || it.OnHold || it.ciRed || it.ciChecking { + continue + } + repo := it.Repo + if qualify != nil { + repo = qualify(repo) + } + if !strings.Contains(repo, "/") { + continue + } + out = append(out, reviewQuestionCandidate{ + Repo: repo, Number: it.Number, Head: it.Head, Question: strings.TrimSpace(dn.Question), + Reason: it.Reason, Caption: it.Caption, + HiveAuthored: it.AuthorKind == authorKindHive || it.AdoptedBy > 0, + }) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Repo != out[j].Repo { + return out[i].Repo < out[j].Repo + } + return out[i].Number < out[j].Number + }) + return out +} + +// reviewQuestionUnresolvedFindings reports whether the head's aggregate +// still carries something a person or the fixer must answer: a backed +// decision finding, an in-scope finding, or a perspective that asked for +// changes. A bare question with none of these is what this sweep decides. +func reviewQuestionUnresolvedFindings(agg review.Aggregate) bool { + if strings.TrimSpace(agg.DecisionFinding) != "" { + return true + } + for _, f := range agg.Findings { + if review.InScopeFinding(f.Finding) { + return true + } + } + for _, v := range agg.Perspectives { + if v == review.VerdictChangesRequested || v == review.VerdictReject { + return true + } + } + return false +} + +// maybeAutoDecideReviewQuestions starts a sweep in the background when one +// is due and none is running; it reports whether it started one. +// UpdateStatusIfFresh calls it on every published snapshot. +func (s *Server) maybeAutoDecideReviewQuestions(status *StatusPayload, now time.Time) bool { + if s == nil || s.deps == nil || status == nil || !s.reviewQuestionAutodecideEnabled() { + return false + } + if s.deps.GHClient == nil || s.deps.GHClient.GoGitHub() == nil { + return false + } + st := &s.reviewQuestionAuto + st.mu.Lock() + if st.running || (!st.lastAt.IsZero() && now.Sub(st.lastAt) < reviewQuestionAutodecideInterval) { + st.mu.Unlock() + return false + } + st.running = true + st.lastAt = now + st.mu.Unlock() + ctx := context.Background() + if s.deps.Ctx != nil { + ctx = s.deps.Ctx + } + go func() { + defer func() { + st.mu.Lock() + st.running = false + st.mu.Unlock() + }() + s.autoDecideReviewQuestions(ctx, status, now) + }() + return true +} + +// autoDecideReviewQuestions runs one sweep synchronously. +func (s *Server) autoDecideReviewQuestions(ctx context.Context, status *StatusPayload, now time.Time) int { + items := s.buildStageTracker(status, s.stageStoreOrShared(), now).Items + cands := reviewQuestionCandidates(items, stageTrackerRepoQualifier(status)) + if len(cands) == 0 { + return 0 + } + var lookup func(string, int, string, bool) (review.Aggregate, bool) + if art, err := review.LoadArtifact(""); err == nil { + lookup = stageTrackerDecisionVerdictLookup(&art) + } + started := 0 + for _, c := range cands { + if started >= reviewQuestionAutodecideMaxPerSweep || ctx.Err() != nil { + break + } + if !s.delegateDecisionEnabled(c.Repo) || s.reviewQuestionAuto.seen(c.Repo, c.Number, c.Head) { + continue + } + if s.autoDecideReviewQuestion(ctx, c, lookup, now) { + started++ + } + } + return started +} + +// autoDecideReviewQuestion classifies one candidate and, for a scope +// question, runs the delegated decision. It reports whether one ran. +func (s *Server) autoDecideReviewQuestion(ctx context.Context, c reviewQuestionCandidate, lookup func(string, int, string, bool) (review.Aggregate, bool), now time.Time) bool { + in := review.DecisionQuestionInput{Question: c.Question, HiveAuthored: c.HiveAuthored, CIGreen: true} + if lookup != nil { + if agg, ok := lookup(c.Repo, c.Number, c.Head, true); ok { + in.UnresolvedFindings = reviewQuestionUnresolvedFindings(agg) + if agg.HiveAuthoredKnown { + in.HiveAuthored = in.HiveAuthored || agg.HiveAuthored + } + } + } + fromFork, files, err := s.reviewQuestionPRFacts(ctx, c.Repo, c.Number) + if err != nil { + s.reviewQuestionLogger().Debug("reviewer question auto-decide skipped: PR read failed", "repo", c.Repo, "pr", c.Number, "error", err) + return false + } + in.FromFork, in.Files = fromFork, files + class, reason := review.ClassifyDecisionQuestion(in) + if class != review.DecisionQuestionScope { + s.reviewQuestionLogger().Debug("reviewer question kept for a person", "repo", c.Repo, "pr", c.Number, "head", c.Head, "class", string(class), "reason", reason) + return false + } + hiveID := s.delegateHiveID() + marker := reviewQuestionAutodecideMarker{Head: c.Head, At: now, Class: string(class), Reason: reason} + if err := s.reviewQuestionAuto.mark(c.Repo, c.Number, marker); err != nil { + s.reviewQuestionLogger().Warn("reviewer question auto-decide ledger write failed", "path", s.reviewQuestionAuto.filePath(), "error", err) + } + key := delegatedJobKey(c.Repo, c.Number) + job := &delegatedDecisionJob{ + ID: key + "@" + strconv.FormatInt(now.UnixNano(), 36), Repo: c.Repo, Number: c.Number, Type: "pr", + Status: delegatedJobStatusRunning, Requester: hiveID, StartedAt: now, Marker: delegatedecision.Marker(hiveID), + } + if _, ok := s.delegatedJobs.start(key, job, now); !ok { + return false + } + s.delegatedJobs.plans.forget(c.Repo, c.Number) + if err := s.operatorActions().Record(c.Repo, c.Number, OperatorAction{ + Action: operatorActionLetHiveDecide, Actor: hiveID, At: now, Outcome: operatorActionOutcomePending, + HeadSHA: c.Head, Stage: trackerNumberNeedsDecision, Note: "auto: " + reason, + }); err != nil { + s.reviewQuestionLogger().Warn("operator action ledger write failed", "path", operatorActionsPath, "error", err) + } + s.runDelegatedDecision(ctx, key, c.Repo, c.Number, "pr", hiveID, false, delegatedDecisionRequest{ + Type: "pr", Reason: c.Reason, Caption: c.Caption, Head: c.Head, + }) + done, _ := s.delegatedJobs.get(key) + verdict, rule := "", "" + if done.Decision != nil { + verdict, rule = string(done.Decision.Verdict), done.Decision.Rule + } + followUp := 0 + if done.Decision != nil && done.Decision.Verdict == delegatedecision.VerdictApprove { + followUp = s.fileReviewQuestionFollowUp(ctx, c) + } + _ = s.reviewQuestionAuto.update(c.Repo, c.Number, func(m *reviewQuestionAutodecideMarker) { + m.Verdict, m.Rule, m.FollowUp = verdict, rule, followUp + }) + s.reviewQuestionLogger().Info("reviewer question auto-decided", + "repo", c.Repo, "pr", c.Number, "head", c.Head, "class", string(class), "reason", reason, + "verdict", verdict, "rule", rule, "status", done.Status, "error", done.Error, "follow_up", followUp) + s.invalidateStageTrackerCache() + return true +} + +// reviewQuestionPRFacts reads what the classifier needs from GitHub: whether +// the head lives on a fork, and the changed files with their patches. +func (s *Server) reviewQuestionPRFacts(ctx context.Context, repoFull string, number int) (bool, []review.DecisionQuestionFile, error) { + client := s.deps.GHClient.GoGitHub() + owner, name, ok := strings.Cut(repoFull, "/") + if !ok || client == nil { + return false, nil, errors.New("no GitHub client") + } + pr, _, err := client.PullRequests.Get(ctx, owner, name, number) + if err != nil { + return false, nil, err + } + fromFork := false + if pr.GetHead().GetRepo() != nil && pr.GetBase().GetRepo() != nil { + fromFork = !strings.EqualFold(pr.GetHead().GetRepo().GetFullName(), pr.GetBase().GetRepo().GetFullName()) + } + var files []review.DecisionQuestionFile + opt := &gh.ListOptions{PerPage: 100} + for { + page, resp, err := client.PullRequests.ListFiles(ctx, owner, name, number, opt) + if err != nil { + return fromFork, nil, err + } + for _, f := range page { + files = append(files, review.DecisionQuestionFile{Path: f.GetFilename(), Patch: f.GetPatch()}) + if prev := f.GetPreviousFilename(); prev != "" && prev != f.GetFilename() { + files = append(files, review.DecisionQuestionFile{Path: prev}) + } + } + if resp == nil || resp.NextPage == 0 { + break + } + opt.Page = resp.NextPage + } + return fromFork, files, nil +} + +// fileReviewQuestionFollowUp records the reviewer's question as a scanner +// issue linked to the PR once the hive admitted the PR as-is. It returns the +// issue number (0 when the gate refused or the create failed). +func (s *Server) fileReviewQuestionFollowUp(ctx context.Context, c reviewQuestionCandidate) int { + if s.deps == nil || s.deps.GHClient == nil { + return 0 + } + title := reviewQuestionFollowUpTitle(c.Question) + preview := "follow-up issue for reviewer question on " + c.Repo + "#" + strconv.Itoa(c.Number) + if !s.deps.GHClient.WritebackAllowed(c.Repo, writeback.Item{HiveAuthored: true}, writeback.KindIssueFile, preview).Allowed { + return 0 + } + body := fmt.Sprintf("A review perspective on #%d ended with a question rather than a finding. "+ + "The hive decided the PR merges as-is (governor.review.auto_decide_questions); the question is kept here as follow-up work.\n\n"+ + "> %s\n\nSource: %s#%d (head `%s`).\n", c.Number, strings.ReplaceAll(c.Question, "\n", "\n> "), c.Repo, c.Number, c.Head) + res, err := s.deps.GHClient.CreateIssue(ctx, ghpkg.CreateIssueRequest{ // writeback:gated + Repo: c.Repo, + Title: title, + Body: body, + Labels: []string{reviewQuestionFollowUpLabel}, + Origin: config.OriginSourceGovernor, + }) + if err != nil { + s.reviewQuestionLogger().Warn("reviewer question follow-up issue not filed", "repo", c.Repo, "pr", c.Number, "error", err) + return 0 + } + return res.Number +} + +// reviewQuestionFollowUpTitle is "follow-up: " on one line, +// capped at reviewQuestionFollowUpTitleMax runes. +func reviewQuestionFollowUpTitle(question string) string { + q := strings.Join(strings.Fields(question), " ") + title := "follow-up: " + q + if r := []rune(title); len(r) > reviewQuestionFollowUpTitleMax { + title = strings.TrimSpace(string(r[:reviewQuestionFollowUpTitleMax-1])) + "…" + } + return title +} + +func (s *Server) reviewQuestionLogger() *slog.Logger { return s.webhookLogger() } diff --git a/src/pkg/dashboard/review_question_autodecide_test.go b/src/pkg/dashboard/review_question_autodecide_test.go new file mode 100644 index 0000000000..ccfc0a9c17 --- /dev/null +++ b/src/pkg/dashboard/review_question_autodecide_test.go @@ -0,0 +1,107 @@ +package dashboard + +import ( + "path/filepath" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/outputschema" + "github.com/hivecommons/hive/pkg/review" +) + +func TestReviewQuestionCandidatesPicksReviewerQuestionsAt085(t *testing.T) { + ask := &StageTrackerDecision{Question: "@clubanderson should decide whether this merges ahead of the workflow edit.", AskedBy: decisionAskedByReviewer} + items := []StageTrackerItem{ + {Kind: "pr", Repo: "docs", Number: 618, Head: "abc", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 2, Head: "def", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, ciRed: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 3, Head: "ghi", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, ciChecking: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 4, Head: "jkl", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, OnHold: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 5, Head: "mno", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: &StageTrackerDecision{Question: "sentinel flagged", AskedBy: "sentinel"}}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 6, Head: "", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 7, Head: "pqr", Stage: 70, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "issue", Repo: "hivecommons/hive", Number: 8, Head: "stu", Stage: trackerNumberNeedsDecision, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 9, Head: "vwx", Stage: trackerNumberNeedsDecision, AuthorKind: "person", AdoptedBy: 10, DecisionNeeded: ask}, + } + qualify := func(r string) string { + if r == "docs" { + return "hivecommons/docs" + } + return r + } + got := reviewQuestionCandidates(items, qualify) + if len(got) != 2 { + t.Fatalf("candidates = %+v, want docs#618 and hive#9", got) + } + if got[0].Repo != "hivecommons/docs" || got[0].Number != 618 || !got[0].HiveAuthored { + t.Errorf("first = %+v, want qualified hive-authored docs#618", got[0]) + } + if got[1].Number != 9 || !got[1].HiveAuthored { + t.Errorf("second = %+v, want adopted hive#9 read as hive-authored", got[1]) + } +} + +func TestReviewQuestionUnresolvedFindings(t *testing.T) { + clean := review.Aggregate{DecisionQuestion: "should this merge ahead?", Perspectives: map[review.Perspective]review.Verdict{"security": review.VerdictApprove}} + if reviewQuestionUnresolvedFindings(clean) { + t.Errorf("a bare question with approving perspectives is not an unresolved finding") + } + backed := clean + backed.DecisionFinding = "security: token in workflow" + if !reviewQuestionUnresolvedFindings(backed) { + t.Errorf("a backed decision finding is unresolved") + } + changes := review.Aggregate{Perspectives: map[review.Perspective]review.Verdict{"correctness": review.VerdictChangesRequested}} + if !reviewQuestionUnresolvedFindings(changes) { + t.Errorf("changes_requested is unresolved") + } + finding := review.Aggregate{Findings: []review.PerspectiveFinding{{Perspective: "correctness", Finding: outputschema.Finding{Title: "nil deref", Severity: outputschema.SeverityHigh}}}} + if !reviewQuestionUnresolvedFindings(finding) { + t.Errorf("an in-scope finding is unresolved") + } +} + +func TestReviewQuestionAutodecideOncePerHead(t *testing.T) { + st := &reviewQuestionAutodecide{path: filepath.Join(t.TempDir(), "markers.json")} + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + if st.seen("hivecommons/docs", 618, "abc") { + t.Fatal("fresh ledger reports seen") + } + if err := st.mark("hivecommons/docs", 618, reviewQuestionAutodecideMarker{Head: "abc", At: now, Class: "scope-question", Reason: "r"}); err != nil { + t.Fatal(err) + } + if !st.seen("hivecommons/docs", 618, "ABC") { + t.Error("same head (case-insensitive) must read as seen") + } + if st.seen("hivecommons/docs", 618, "def") { + t.Error("a new push must ask again") + } + reloaded := &reviewQuestionAutodecide{path: st.path} + if !reloaded.seen("HiveCommons/Docs", 618, "abc") { + t.Error("marker must survive a reload") + } + if got := reloaded.countSince(now.Add(30*time.Minute), time.Hour); got != 1 { + t.Errorf("count within window = %d, want 1", got) + } + if got := reloaded.countSince(now.Add(2*time.Hour), time.Hour); got != 0 { + t.Errorf("count past window = %d, want 0", got) + } +} + +func TestReviewQuestionFollowUpTitle(t *testing.T) { + got := reviewQuestionFollowUpTitle(" should we\n also apply the opt-in? ") + if got != "follow-up: should we also apply the opt-in?" { + t.Errorf("title = %q", got) + } + long := reviewQuestionFollowUpTitle(repeatRune('q', 300)) + if r := []rune(long); len(r) != reviewQuestionFollowUpTitleMax || r[len(r)-1] != '…' { + t.Errorf("long title not capped: %d runes", len(r)) + } +} + +func repeatRune(r rune, n int) string { + out := make([]rune, n) + for i := range out { + out[i] = r + } + return string(out) +} diff --git a/src/pkg/dashboard/review_queue_view_9607_test.go b/src/pkg/dashboard/review_queue_view_9607_test.go index afaf8b9760..41a6010cc7 100644 --- a/src/pkg/dashboard/review_queue_view_9607_test.go +++ b/src/pkg/dashboard/review_queue_view_9607_test.go @@ -78,7 +78,7 @@ func TestReviewQueueViewStaticWiring(t *testing.T) { `reviewEvidenceButtonHtml(e.repo, e.number) +`, `function reviewEvidenceButtonHtml(repo, number)`, `data-action="openReviewEvidence"`, - `() => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }),`, + `['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })],`, } { if !strings.Contains(html, want) { t.Errorf("index.html is missing review-queue wiring %q", want) @@ -121,7 +121,7 @@ func TestReviewQueueEntryRendering(t *testing.T) { // The evidence button is role-gated on window state that does not exist // under node; its wiring is pinned in TestReviewQueueViewStaticWiring. source.WriteString("function reviewEvidenceButtonHtml() { return ''; }\n") - for _, name := range []string{"esc", "reviewQueuePriorityMeta", "reviewQueueAgeLabel", "reviewQueueSupersededHtml", "renderReviewQueueEntry"} { + for _, name := range []string{"esc", "reviewQueuePriorityMeta", "reviewQueueAgeLabel", "reviewQueueSupersededHtml", "fixerQueueHint", "renderReviewQueueEntry"} { source.WriteString(jsFunc(t, html, name)) source.WriteByte('\n') } @@ -167,6 +167,14 @@ assert.match(entry({ priority: 'weird' }), /review-priority\/normal/); assert.match(entry({ hive_authored: true }), /agent/); assert.match(entry({ held: true }), /held/); +// Fixer status is independent of review rank and disappears after delivery. +assert.doesNotMatch(entry(), /fixer queued/); +assert.match(entry({ fixer_queue_position: 3, fixer_queue_ahead: 2 }), /fixer queued, 2 ahead/); +assert.match(entry({ fixer_queue_position: 1, fixer_queue_ahead: 0 }), /fixer queued, 0 ahead/); +assert.doesNotMatch(entry({ fixer_queue_position: 0, fixer_queue_ahead: 0 }), /fixer queued/); +assert.doesNotMatch(entry({ fixer_queue_ahead: 4 }), /fixer queued/); +assert.doesNotMatch(entry({ fixer_queue_position: '' }), /fixer queued/); + // No reasons still renders without throwing. assert.match(entry({ reasons: [] }), /no ranking reasons recorded/); diff --git a/src/pkg/dashboard/review_settings_parity_test.go b/src/pkg/dashboard/review_settings_parity_test.go index 08d3eb93d0..5a8590c31c 100644 --- a/src/pkg/dashboard/review_settings_parity_test.go +++ b/src/pkg/dashboard/review_settings_parity_test.go @@ -78,6 +78,8 @@ func TestReviewSettingsRenderEveryKey(t *testing.T) { {"review.confidence_score", `data-section="review" data-key="confidence_score"`}, {"review.priority_labels", `data-section="review" data-key="priority_labels"`}, {"review.fixer_agent", `data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"`}, + {"review.fixer_fallback_agents[]", `data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"`}, + {"review.fixer_fallback_after_undeliverable", `data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"`}, {"review.human_decision_label", `data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"`}, {"review.self_authored_decision_policy", `data-arg0="review" data-arg1="self_authored_decision_policy" data-arg-types="s,s,v"`}, {"review.max_reviews_per_head", `data-arg0="review" data-arg1="max_reviews_per_head" data-arg-types="s,s,N"`}, @@ -99,3 +101,37 @@ func TestReviewSettingsRenderEveryKey(t *testing.T) { } } } + +func TestReviewFixerFallbackConfigPut(t *testing.T) { + s := covApiServer(t) + if rec := doPut(s, "/api/config/review", map[string]any{ + "fixer_fallback_agents": []string{" fixer ", "", "spare"}, + "fixer_fallback_after_undeliverable": 4, + }); rec.Code != http.StatusOK { + t.Fatalf("PUT: %d %s", rec.Code, rec.Body.String()) + } + rc := s.deps.Config.Review + if len(rc.FixerFallbackAgents) != 2 || rc.FixerFallbackAgents[0] != "fixer" || rc.FixerFallbackAgents[1] != "spare" || rc.FixerFallbackAfterUndeliverable != 4 { + t.Fatalf("fallback settings did not round-trip: %+v", rc) + } + if rec := doPut(s, "/api/config/review", map[string]any{ + "fixer_fallback_agents": []string{}, "fixer_fallback_after_undeliverable": -1, + }); rec.Code != http.StatusBadRequest { + t.Fatalf("negative threshold: %d", rec.Code) + } + if len(s.deps.Config.Review.FixerFallbackAgents) != 2 { + t.Fatal("rejected PUT mutated fallback settings") + } + if rec := doPut(s, "/api/config/review", map[string]any{"fixer_agent": "scanner"}); rec.Code != http.StatusOK { + t.Fatalf("partial PUT: %d", rec.Code) + } + if s.deps.Config.Review.FixerFallbackAfterUndeliverable != 4 || len(s.deps.Config.Review.FixerFallbackAgents) != 2 { + t.Fatal("partial PUT changed fallback settings") + } + if rec := doPut(s, "/api/config/review", map[string]any{"fixer_fallback_agents": []string{}}); rec.Code != http.StatusOK { + t.Fatalf("clear PUT: %d", rec.Code) + } + if s.deps.Config.Review.EffectiveFixerFallbackAfterUndeliverable() != 0 { + t.Fatal("empty list did not disable fallback routing") + } +} diff --git a/src/pkg/dashboard/row_action_result.go b/src/pkg/dashboard/row_action_result.go index 587891d64e..eb73664ba0 100644 --- a/src/pkg/dashboard/row_action_result.go +++ b/src/pkg/dashboard/row_action_result.go @@ -25,6 +25,10 @@ type RowActionResult struct { Next string `json:"next"` Rule string `json:"rule,omitempty"` AppliedAt *time.Time `json:"applied_at,omitempty"` + // Verdict is the delegate's verdict slug when the hive decided + // (owner-only, recommend-only, …), so the row caption can tell a + // recorded recommendation from an ask handed back to the person. + Verdict string `json:"verdict,omitempty"` // Why is the glossary slug for why a recorded decision has not taken // effect (Action no-effect); Options are the concrete next actions in // the popover's shape (hivecommons/hive#14822). Both additive. @@ -104,7 +108,7 @@ func delegatedRowActionResult(in delegatedecision.Input, d delegatedecision.Deci if in.Kind == delegatedecision.KindPR { kind = rowActionTargetPR } - out := RowActionResult{Target: rowActionTarget(in.Repo, kind, in.Number), Rule: d.Rule} + out := RowActionResult{Target: rowActionTarget(in.Repo, kind, in.Number), Rule: d.Rule, Verdict: string(d.Verdict)} ruleTag := "" if d.Rule != "" { ruleTag = " (" + delegatedecision.RulePlain(d.Rule) + ")" diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index b0c7e25d21..940b9f8c14 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -121,10 +121,9 @@ type Server struct { // matrix is the dashboard.matrix line source (matrix_source.go); nil // until MatrixObserver is called with an active config. - matrixMu sync.Mutex - matrix *matrixSource - matrixNudge stageTrackerNudger - matrixPersistPath string + matrixMu sync.Mutex + matrix *matrixSource + matrixNudge stageTrackerNudger port int authToken string @@ -247,6 +246,9 @@ type Server struct { // delegatedJobs tracks "Let hive decide" jobs by repo#number // (api_repo_item_decide_delegated.go). delegatedJobs delegatedDecisionJobs + // reviewQuestionAuto is the reviewer-question auto-decide sweep's + // pacing and once-per-head ledger (review_question_autodecide.go). + reviewQuestionAuto reviewQuestionAutodecide // operatorActionStore is the owner row-action ledger behind the // activity monitor's ✓ badge (operator_actions.go), opened on first use. operatorActionStore *operatorActionStore @@ -1854,13 +1856,15 @@ func (s *Server) Start() error { if err != nil { return fmt.Errorf("loading embedded static files: %w", err) } - // The SPA document gets a dedicated handler with a strong ETag and one-time - // gzip cache (see pkg/dashboard/webstatic): http.FileServer would serve the + // The SPA shell and content-addressed main script get dedicated ETag/gzip + // handlers (see pkg/dashboard/webstatic): http.FileServer would serve the // ~1.3 MB inline document uncompressed with no cache validators (embed.FS // has a zero ModTime, so not even Last-Modified), forcing a full re-download - // on every visit. "/{$}" matches the root path exactly; every other static - // path falls through to the plain file server below. + // on every visit. The generated monolith remains embedded for source + // consumers; extraction happens after all startup injections. "/{$}" matches + // the root exactly; other static paths use the revalidating file server below. var idx *webstatic.IndexDocument + var mainScript *webstatic.DashboardScript if rawIndex, err := fs.ReadFile(staticContent, "index.html"); err == nil { // Strings are baked in ONCE here, unlike custom.css which is read per // request: the document carries a strong ETag and one immutable gzip @@ -1871,6 +1875,14 @@ func (s *Server) Start() error { // The kiosk call-to-action badge (#16236) is baked in the same way: // its QR code and copy are static per process. branded = kioskcta.Inject(branded, s.kioskCTAOptions()) + branded, mainScript = webstatic.ExternalizeDashboardScript(branded) + if mainScript != nil { + // Keep registration statically discoverable by route parity checks; + // the handler serves only its exact content-addressed path. + s.mux.Handle("GET /assets/{script}", mainScript) + } else { + s.logger.Warn("dashboard main script extraction unavailable; serving original inline dashboard") + } idx = webstatic.NewIndexDocument(branded) // Hand the FINAL served bytes to the CSP layer explicitly, rather than // having the document constructor reach out and set global state: @@ -1893,7 +1905,7 @@ func (s *Server) Start() error { // index document itself remains immutable and one-time precompressed. s.mux.HandleFunc("GET /branding/custom.css", s.handleBrandingCSS) - s.mux.Handle("GET /", http.FileServer(http.FS(staticContent))) + s.mux.Handle("GET /", webstatic.FileServer(staticContent)) // authenticate is outermost so the identity headers it injects from a // per-user session are visible to roleEnforcement's read-only write-gate. @@ -1919,6 +1931,9 @@ func (s *Server) Start() error { // answer even when a saturated node is slow to build the static cache. go idx.Precompress() } + if mainScript != nil { + go mainScript.Precompress() + } // Viewer-independent cost sampling (#13483); the ring's throttle is the // same interval, so this is exactly one snapshot per period. costTicker := time.NewTicker(costHistoryMinIntervalMs * time.Millisecond) @@ -2145,6 +2160,9 @@ code{color:#e6edf3} // empty role and never block a read-only viewer's writes.) func (s *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/matrix/lines" { + w.Header().Set("Cache-Control", "no-store") // Cover 401 responses that never reach handleMatrixLines' no-store header. + } directRouteAuthz := s.directRouteAuthzEnabled() // FAIL CLOSED: a spoke with an authorized_users allowlist (direct-route) @@ -3046,6 +3064,9 @@ func (s *Server) UpdateStatusIfFresh(status *StatusPayload, buildEpoch uint64) b // Backstop for closed items whose delivery never arrived or whose // confirming read was refused (hivecommons/hive#14159, #14064). s.maybeSweepClosedRows(time.Now().UTC()) + // A reviewer's scope question on the hive's own green PR is the hive's + // to decide, not an 085 park (review_question_autodecide.go). + s.maybeAutoDecideReviewQuestions(status, time.Now().UTC()) s.AppendTokenSparkline(status) s.AppendTrendHistory(status) @@ -4029,7 +4050,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { status := s.status snapshot := s.statusWithOverviewBands(status, now) s.statusMu.RUnlock() - payload := statusWithWebhooks{StatusPayload: snapshot, Webhooks: github.WebhookHealthSnapshot(), CIFailureSignals: github.CIFailureSignals().Snapshot(), MatrixEnabled: s.currentMatrixConfig().Active()} + payload := statusWithWebhooks{StatusPayload: snapshot, Webhooks: github.WebhookHealthSnapshot(), CIFailureSignals: github.CIFailureSignals().Snapshot(), MatrixEnabled: s.currentMatrixConfig().Active(), ReviewQuestionsAutodecided1h: s.reviewQuestionsAutodecided1h(now)} if s.deps != nil && s.deps.EvalLoop != nil { loop := s.deps.EvalLoop() payload.EvalLoopStatus = &loop @@ -4037,9 +4058,28 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { payload.UpgradeProgress = s.upgradeProgress(status, now) payload.Writeback = s.WritebackStatus() payload.Hotspots = s.HotspotStatusBlock() + payload.Config = s.configHealthStatus() statusJSONResponse(w, r, filterStatusPayload(&payload, r.URL.Query().Get("fields"), r.URL.Query().Get("omit"))) } +// ConfigHealthStatus is the `config` block of /api/status: what the boot +// found wrong with the loaded config itself, as opposed to what it says. +type ConfigHealthStatus struct { + // GateRegressions lists the safety gates a previous runtime overlay + // carried that the running config lacks or weakens (#16438). Always a + // list, empty on a healthy boot, so the dashboard banner needs no + // presence check. + GateRegressions []config.GateRegression `json:"gate_regressions"` +} + +func (s *Server) configHealthStatus() *ConfigHealthStatus { + out := &ConfigHealthStatus{GateRegressions: []config.GateRegression{}} + if s.deps != nil && s.deps.Config != nil && len(s.deps.Config.GateRegressions) > 0 { + out.GateRegressions = append(out.GateRegressions, s.deps.Config.GateRegressions...) + } + return out +} + // statusWithWebhooks adds the live webhook health block (#11177) and the // governor loop's pacing (evalMode, lastWakeReason) to the cached status // payload at serve time, so neither is a whole eval cycle stale. @@ -4052,7 +4092,7 @@ type statusWithWebhooks struct { *EvalLoopStatus // MatrixEnabled reports whether the Matrix block is active (enabled with // at least one repo, see config.DashboardMatrixConfig.Active) so the header shows - // the Matrix tab only on hives whose /api/matrix/lines will serve it. + // the Code activity entry only where /api/matrix/lines will serve it. MatrixEnabled bool `json:"matrixEnabled"` // UpgradeProgress is the spoke's view of the scheduled-upgrade state // machine (scheduled / draining / pulling / … / missed) with the drain @@ -4067,6 +4107,14 @@ type statusWithWebhooks struct { // concurrent PRs in the window, how many warrant a split, how many have // a modularize issue filed. Absent when the advisor is not wired. Hotspots *HotspotStatus `json:"hotspots,omitempty"` + // Config reports boot-time findings about the loaded config itself: + // config.gate_regressions is the safety gates a previous runtime + // overlay carried that this boot dropped (#16438). + Config *ConfigHealthStatus `json:"config,omitempty"` + // ReviewQuestionsAutodecided1h counts the reviewer questions the hive + // decided itself in the last hour instead of parking the PR at 085 + // (review_question_autodecide.go, governor.review.auto_decide_questions). + ReviewQuestionsAutodecided1h int `json:"review_questions_autodecided_1h"` } func (s *Server) handleStatusSummary(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 98465e1ce3..9ddc121b22 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -201,6 +201,7 @@ github.attention.flap_window # single-admitter ownership and flap window are YAM github.attention.recipient_budget # per-recipient attention budget, off by default; yaml-only, see docs/notifications.md (#16271) github.attention.reminder_interval # attention-pilot reminder interval; yaml-only, see src/docs/attention-episodes.md (#16361) github.notifications.attention_pilot # opt-in attention-pilot issue status card; yaml-only, see docs/notifications.md (#16358) +github.notifications.claim_ledger # one per-issue claim-ledger comment edited in place; yaml-only, see operator-reference (#16433) github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 67a93de1e5..75ab1ca4fa 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -279,6 +279,9 @@ type StageTrackerItem struct { CIActivity *StageTrackerActivity `json:"ci_activity,omitempty"` ReviewActivity *StageTrackerActivity `json:"review_activity,omitempty"` CodeActivity *StageTrackerActivity `json:"code_activity,omitempty"` + // Remediation is the pickup evidence behind a red PR's code activity + // (stage_tracker_remediation.go); absent while nobody has picked it up. + Remediation *StageTrackerRemediation `json:"remediation,omitempty"` // DisplayColumn is presentation only; native stages, filters and merge gates remain unchanged. DisplayColumn int `json:"display_column,omitempty"` Preparation *StageTrackerPreparation `json:"preparation,omitempty"` @@ -296,6 +299,12 @@ type StageTrackerItem struct { ClaimReference bool `json:"claim_reference,omitempty"` IsTracker bool `json:"is_tracker,omitempty"` Children *github.IssueChildren `json:"children,omitempty"` + // OpenChildren is how many sub-issues of a decomposed parent are still + // open (the stage engine's "waiting on N open child issue(s)" suffix on + // a 010 reason). Non-zero means the parent is tracking its children, + // not waiting on the scanner, and the row reads "Tracking", not + // "Actionable" (hivecommons/hive#16481). + OpenChildren int `json:"open_children,omitempty"` // Labels are the item's GitHub labels as the snapshot saw them, so the // dashboard can offer a label filter without a second endpoint. Labels []string `json:"labels,omitempty"` @@ -491,9 +500,9 @@ type StageTrackerItem struct { // UnauthorizedStep is set when the item wears hive:unauthorized: the // step the hive's GitHub App is not permitted to take, in words // ("approve workflow runs"), from the `unauthorized:` stage - // reason; the gate cell reads "Awaiting human: ". Unauthorized - // is the pill's tooltip naming the permission and the human action - // (hivecommons/hive#14589). + // reason; the PR in progress chevron reads "Waiting for @who · + // on GitHub" (hive#16524). Unauthorized is the pill's tooltip naming + // the permission and the human action (hivecommons/hive#14589). UnauthorizedStep string `json:"unauthorized_step,omitempty"` Unauthorized string `json:"unauthorized,omitempty"` // DecisionNeeded is set on a row parked on a person (085 / 045 / 015, @@ -713,6 +722,9 @@ type StageTrackerLinkedPR struct { Stage int `json:"stage,omitempty"` StageSince *time.Time `json:"stage_since,omitempty"` Caption string `json:"caption,omitempty"` + // UnauthorizedStep mirrors the PR's own field so the nested chevron + // reads "Waiting for @who · on GitHub" too (hive#16524). + UnauthorizedStep string `json:"unauthorized_step,omitempty"` // NoteChangedAt mirrors the PR row's: when the caption last changed // meaning. NoteChangedAt *time.Time `json:"note_changed_at,omitempty"` @@ -1021,7 +1033,7 @@ func stageTrackerShort(s stagelabels.Stage) string { case stagelabels.Reviewed: return "Review passed" case stagelabels.Fixing: - return "Fixing" + return "Remediating" case stagelabels.NeedsAuthor: return "Needs author" case stagelabels.ReturnedToContributor: @@ -1046,9 +1058,13 @@ func stageTrackerStages(overrides map[string]time.Duration) []StageTrackerStage out := make([]StageTrackerStage, 0, len(stagelabels.Table)) for _, d := range stagelabels.Table { branch := stageTrackerBranchFrom(d.Number) + description := d.Description + if d.Stage == stagelabels.Fixing { + description = stageTrackerRemediationNeededCaption + } out = append(out, StageTrackerStage{ Number: d.Number, Slug: d.Slug, Label: d.Stage.Label(), Short: stageTrackerShort(d.Stage), - Description: d.Description, Issue: d.Issue, PR: d.PR, Main: branch == 0, BranchFrom: branch, + Description: description, Issue: d.Issue, PR: d.PR, Main: branch == 0, BranchFrom: branch, DwellSeconds: int64(stagelabels.Dwell(d.Stage, overrides) / time.Second), FallsTo: stageTrackerFallsTo(d), }) diff --git a/src/pkg/dashboard/stage_tracker_acting_caption_test.go b/src/pkg/dashboard/stage_tracker_acting_caption_test.go index 95675d0939..5514990bd4 100644 --- a/src/pkg/dashboard/stage_tracker_acting_caption_test.go +++ b/src/pkg/dashboard/stage_tracker_acting_caption_test.go @@ -14,13 +14,13 @@ import ( // sat on them in muted grey — unreadable — while "Ready for human merge · // untrusted author" still showed beside it, wrapped to four lines. While an // action is in flight a lit chevron shows ONE caption, on an opaque plate -// that meets WCAG AA in both themes, on one line. +// that meets WCAG AA in both themes, within the shared two-line budget. const stageTrackerActingHideRule = `.cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; }` // stageTrackerActingPlateRule is the plate: page surface under page text, -// above the stripes and the pulse overlay, one line with an ellipsis. -const stageTrackerActingPlateRule = `.ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }` +// above the stripes and the pulse overlay, wrapping within two lines. +const stageTrackerActingPlateRule = `.ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; }` // wcagMinContrastAA is the WCAG 2.x AA ratio for normal text. const wcagMinContrastAA = 4.5 @@ -139,8 +139,10 @@ for (const [label, item] of [['merge gate', gateIssue], ['decision', decideIssue const lit = (row.match(/
  • 0 && reachable === lit, label + ': ' + lit + ' lit chevron(s), ' + reachable + ' at row > .ham-strip-row > .ham-strip > .ham-seg.active:\n' + row); - // The word is a child of the lit chevron, so the hide rule reaches it. - assert.ok(/
  • ]*>(?:<[^l][^>]*>|)*?<(?:span|button) class="(?:ham-seg-t|ham-detour|ham-decision-trigger)/.test(row), label + ': the word is a direct child of the lit chevron:\n' + row); + // The focusable tooltip/copy wrapper is a direct child, so the hide rule + // reaches the complete wrapped word and its reserved glyphs together. + assert.ok(/
  • ]*> c.classList.contains('cue-acting-cap')); assert.strictEqual(caps.length, 1, 'exactly one caption'); assert.strictEqual(caps[0].lastChild.nodeValue, 'Queuing for merge…'); assert.strictEqual(caps[0].getAttribute('role'), 'status'); +assert.strictEqual(caps[0].title, 'Queuing for merge…', 'clamped action caption retains its full hover text'); +assert.strictEqual(caps[0].getAttribute('aria-label'), 'Queuing for merge…'); +assert.strictEqual(caps[0].getAttribute('tabindex'), '0', 'full status remains keyboard accessible'); const capEls = caps[0].children.filter(c => c.classList); // the stub lists the text node too assert.strictEqual(capEls.length, 1, 'spinner + text only'); assert.ok(capEls[0].classList.contains('cue-acting-spin')); const shown = seg.children.filter(c => !c.classList.contains('cue-acting-cap')); diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 455547218e..e85ee45610 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -1,11 +1,13 @@ package dashboard import ( + "fmt" "slices" "strings" "time" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/evidence" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" @@ -15,9 +17,13 @@ import ( // native stage and next mover. Worker activity requires assignment AND worker; // CI activity comes only from observed required checks. type StageTrackerActivity struct { - Head string `json:"head"` - State string `json:"state"` - Caption string `json:"caption"` + Head string `json:"head"` + State string `json:"state"` + Caption string `json:"caption"` + // Detail is the longer, plain-language sentence behind Caption: what + // the state means and what would move it. The chevron clamps Caption; + // the tooltip carries Detail in full. + Detail string `json:"detail,omitempty"` Actor string `json:"actor,omitempty"` Source string `json:"source"` ObservedAt *time.Time `json:"observed_at,omitempty"` @@ -25,6 +31,20 @@ type StageTrackerActivity struct { Blocker string `json:"blocker,omitempty"` URL string `json:"url,omitempty"` Active bool `json:"active,omitempty"` + // Check counts on the current head for the CI track (hivecommons/hive#16484): + // over the required checks when branch protection is known, otherwise + // over every check run observed on the head. ChecksTotal == 0 means no + // count could be made ("CI ?/?"). + ChecksPassed int `json:"checks_passed,omitempty"` + ChecksTotal int `json:"checks_total,omitempty"` + ChecksFailed int `json:"checks_failed,omitempty"` + ChecksFailing []string `json:"checks_failing,omitempty"` + // Perspective counts on the current head for the Review track: Total is + // the swarm's expected set for this PR (configured perspectives plus any + // extra one dispatched or reported for the head), Done the ones with a + // verdict for the current head. + PerspectivesDone int `json:"perspectives_done,omitempty"` + PerspectivesTotal int `json:"perspectives_total,omitempty"` } const trackerActivityFreshWindow = 2 * time.Minute @@ -34,7 +54,8 @@ func trackerUnknownActivity(head, caption string) *StageTrackerActivity { } func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerActivity { - out := trackerUnknownActivity(pr.HeadSHA, "CI unknown · required checks not observed") + out := trackerUnknownActivity(pr.HeadSHA, "CI unknown · no check results observed for this head yet") + out.Detail = "hive has not yet seen which checks branch protection requires, or any check run or commit status for the PR's current commit." a := pr.CIActivity if a == nil || pr.HeadSHA == "" || !strings.EqualFold(a.Head, pr.HeadSHA) { return out @@ -47,6 +68,7 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA out.Source += "+github-commit-statuses" } if !a.RequiredKnown || a.RequiredSource == "" || len(a.RequiredChecks) == 0 || len(a.Required) == 0 { + stageTrackerCountHeadChecks(out, a) return out } type requiredObservation struct { @@ -81,11 +103,20 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } if !found { + stageTrackerCountHeadChecks(out, a) return out } } - out.State, out.Caption = "passing", "CI passed" + out.State, out.Caption = "passing", "CI green" + // Per required-check name: the leading state across its observations, + // for the passed / failed counts. + perName := map[string]string{} running := false + // Per required-check name: which have a final result, for the running count. + settled := map[string]bool{} + for _, name := range a.Required { + settled[name] = true + } for _, observation := range observations { name := observation.name check := github.PRActivityCheck{} @@ -116,8 +147,14 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA state = "failing" } } + if state != "passing" && state != "failing" && state != "skipped" { + settled[name] = false + } // A red required check leads, then missing/unknown, then running/queued. rank := map[string]int{"passing": 0, "queued": 1, "running": 2, "skipped": 3, "unknown": 4, "missing": 5, "failing": 6} + if previous, seen := perName[name]; !seen || rank[state] >= rank[previous] { + perName[name] = state + } if rank[state] >= rank[out.State] { out.State, out.Since, out.URL = state, check.Since, check.URL out.ObservedAt = a.ObservedAt @@ -129,30 +166,254 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } } - if out.State == "passing" && a.NeedsCommitStatusEvidence() && !a.StatusesKnown { + statusesMissing := out.State == "passing" && a.NeedsCommitStatusEvidence() && !a.StatusesKnown + if statusesMissing { out.State, out.Blocker = "unknown", "commit statuses not observed" } + done := 0 + for _, name := range a.Required { + if settled[name] { + done++ + } + } + total := len(a.Required) + out.ChecksTotal = total + for _, name := range a.Required { + switch perName[name] { + case "passing": + out.ChecksPassed++ + case "failing": + out.ChecksFailed++ + out.ChecksFailing = append(out.ChecksFailing, name) + } + } + check := fmt.Sprintf("%q", out.Blocker) switch out.State { + case "passing": + out.Caption = "CI green · all " + plural(total, "required check") + " passed" + out.Detail = "Every check that branch protection requires has reported success for the PR's current commit." case "failing": - out.Caption = "CI failing · " + out.Blocker + out.Caption = "CI failing · " + check + " red" + out.Detail = "Required check " + check + " finished without success (failed, timed out, was cancelled, or needs action) on the PR's current commit. A fix or a re-run has to turn it green before CI can pass." case "running": - out.Caption = "CI running" + out.Caption = fmt.Sprintf("CI running · %d/%d checks done", done, total) + out.Detail = fmt.Sprintf("%d of the %s have a final result; the rest are still executing on the PR's current commit.", done, plural(total, "required check")) case "queued": - out.Caption = "CI queued" + out.Caption = "CI queued · " + check + " waiting for a runner" + out.Detail = "Required check " + check + " has been requested for the PR's current commit but has not started executing yet." case "missing": - out.Caption = "CI waiting · " + out.Blocker + " not observed" + if wa := a.WorkflowApproval; wa != nil && wa.Pending > 0 { + // Unreported because GitHub holds the runs behind its + // approve-workflows gate: a person's click, not a push, + // moves it (hivecommons/hive#16599). + out.Blocker = stageTrackerWorkflowApprovalBlocker(wa.Pending) + out.Caption = fmt.Sprintf("CI waiting · %s %s approval on GitHub", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "needs", "need")) + out.Detail = fmt.Sprintf("%s for the PR's current commit %s waiting for a maintainer to approve workflows on GitHub (the gate GitHub applies to dependabot and first-time or fork contributors), so required check %s cannot report until someone approves them.", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "is", "are"), check) + if wa.Actor != "" { + out.Actor = wa.Actor + } + if wa.ObservedAt != nil { + out.Since = wa.ObservedAt + } + break + } + out.Caption = "CI waiting · required check " + check + " hasn't reported for this head yet" + out.Detail = "Branch protection requires a check named " + check + ", but no check run or commit status with that name exists for the PR's current commit. Usually the workflow that produces it has not been triggered; a push, re-run, or label can start it." case "unknown": - out.Caption = "CI unknown · " + out.Blocker + if statusesMissing { + out.Caption = "CI unknown · commit statuses not observed for this head" + out.Detail = "A required check is reported as a commit status rather than a check run, and hive has not yet fetched commit statuses for the PR's current commit." + } else { + out.Caption = "CI unknown · " + check + " reported but with no conclusion" + out.Detail = "Required check " + check + " exists for the PR's current commit but hive cannot read a clear result from it (several runs share the name, or the run ended with no conclusion)." + } case "skipped": - out.Caption = "CI skipped · " + out.Blocker + out.Caption = "CI skipped · check " + check + " skipped" + out.Detail = "Required check " + check + " finished as skipped or neutral on the PR's current commit, which branch protection does not count as a pass." } out.Active = running && a.ObservedAt != nil && !a.ObservedAt.After(now) && now.Sub(*a.ObservedAt) <= trackerActivityFreshWindow if running && out.State != "running" { - out.Caption += " · others running" + out.Caption += " · other checks still running" } return out } +// stageTrackerWorkflowApprovalBlockerPrefix leads the CI blocker when the +// unreported checks are workflow runs waiting on GitHub's approve-workflows +// gate; the strip reads the count after the colon. +const stageTrackerWorkflowApprovalBlockerPrefix = "workflow-approval-required:" + +func stageTrackerWorkflowApprovalBlocker(n int) string { + return fmt.Sprintf("%s%d", stageTrackerWorkflowApprovalBlockerPrefix, n) +} + +func pluralVerb(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + +// stageTrackerCountHeadChecks fills the check counts from every check run +// observed on the head when the required set is not known: one entry per +// check name, red if any run of that name is red, green only if its latest +// run succeeded. +func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivity) { + type tally struct { + passing, failing bool + since time.Time + } + byName := map[string]*tally{} + var order []string + for _, check := range a.Checks { + if check.Head != "" && !strings.EqualFold(check.Head, a.Head) { + continue + } + t := byName[check.Name] + if t == nil { + t = &tally{} + byName[check.Name] = t + order = append(order, check.Name) + } + at := time.Time{} + if check.Since != nil { + at = *check.Since + } + red := check.State == "completed" && (check.Conclusion == "failure" || check.Conclusion == "timed_out" || check.Conclusion == "cancelled" || check.Conclusion == "action_required" || check.Conclusion == "startup_failure" || check.Conclusion == "stale") + if red { + t.failing = true + } + if !at.Before(t.since) { + t.since, t.passing = at, check.State == "completed" && check.Conclusion == "success" + } + } + out.ChecksTotal = len(order) + for _, name := range order { + t := byName[name] + switch { + case t.failing: + out.ChecksFailed++ + out.ChecksFailing = append(out.ChecksFailing, name) + case t.passing: + out.ChecksPassed++ + } + } +} + +// stageTrackerExpectedPerspectives is the swarm's perspective set for this +// hive: the configured list (built-ins when empty), falling back to the +// built-ins when the configuration cannot be resolved. +func stageTrackerExpectedPerspectives(cfg *config.Config) []review.Perspective { + var names []string + var prompts map[string]string + if cfg != nil { + names, prompts = cfg.Review.Perspectives, cfg.Review.PerspectivePrompts + } + if set, err := review.NewPerspectiveSet(names, prompts); err == nil && set.Len() > 0 { + return set.List() + } + return append([]review.Perspective(nil), review.DefaultPerspectives...) +} + +// stageTrackerCountPerspectives fills the Review track's done / total +// perspective counts for the PR's current head: total is the expected set +// plus any extra perspective dispatched or reported for the head; done the +// perspectives with a verdict for the head (the aggregate's, or the latest +// verified bundle verdict). +func stageTrackerCountPerspectives(out *StageTrackerActivity, pr github.PullRequest, bundle *evidence.Bundle, agg *review.Aggregate, dispatch review.DispatchState, qualify func(string) string, expected []review.Perspective) { + if out == nil || pr.HeadSHA == "" { + return + } + total := map[review.Perspective]bool{} + done := map[review.Perspective]bool{} + for _, p := range expected { + total[p] = true + } + if agg != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, agg.Repo, agg.Number, agg.HeadSHA) { + for p, v := range agg.Perspectives { + total[p] = true + if v != "" { + done[p] = true + } + } + } + if bundle != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, bundle.Repo, bundle.Number, bundle.HeadSHA) { + for _, verdict := range trackerLatestBundleVerdicts(bundle) { + if verdict.Perspective == "" { + continue + } + total[review.Perspective(verdict.Perspective)] = true + if verdict.Verdict != "" { + done[review.Perspective(verdict.Perspective)] = true + } + } + } + for _, pending := range dispatch.Pending { + if pending.Perspective != "" && !pending.Decision && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, qualify(pending.Repo), pending.Number, pending.HeadSHA) { + total[pending.Perspective] = true + } + } + out.PerspectivesTotal, out.PerspectivesDone = len(total), 0 + for p := range done { + if total[p] { + out.PerspectivesDone++ + } + } + // A swarm that is requested or queued has not started this round: no + // perspective of it is done, whatever an earlier round left behind. + // "Review 5/5 · swarm requested" contradicts itself (hivecommons/hive#16540). + if out.State == "unassigned" { + out.PerspectivesDone = 0 + if out.PerspectivesTotal == 0 { + out.PerspectivesTotal = len(expected) + } + } +} + +// stageTrackerReviewPendingState resolves the Review track for a PR the +// stage itself says is under review (050) when no verdict settled it: the +// swarm is in progress, so the track is "reviewing" (active) with the +// count of perspectives that posted for the current head — never +// "unknown", which left review-pending rows with no lit chevron +// (hivecommons/hive#16599). Without a head bundle or aggregate no +// perspective has posted: done is 0, whatever earlier rounds left behind. +func stageTrackerReviewPendingState(out *StageTrackerActivity, stage int, stageSince *time.Time) { + if out == nil || out.State != "unknown" || stage != trackerNumberReviewPending { + return + } + bundleSeen := strings.Contains(out.Source, "verified-review-bundle") + if !bundleSeen { + out.PerspectivesDone = 0 + } + total := out.PerspectivesTotal + done := out.PerspectivesDone + if total > 0 && done >= total && bundleSeen { + out.State = "adjudicating" + out.Caption = fmt.Sprintf("Review %d/%d · verdicts in · aggregating", done, total) + out.Detail = "Every perspective has posted a verdict for the PR's current commit; hive is combining them into the review decision." + } else { + out.State = "reviewing" + out.Caption = fmt.Sprintf("Review %d/%d · in progress", done, total) + out.Detail = fmt.Sprintf("The PR is at review pending: %d of %s have posted a verdict for the PR's current commit; the rest are still reviewing or waiting for a reviewer.", done, plural(total, "perspective")) + } + out.Active = true + // The stage label is the observation; its time is when the label + // landed (stable across rebuilds, so the payload ETag does not move). + if out.ObservedAt == nil && stageSince != nil { + at := *stageSince + out.ObservedAt = &at + } + if out.Since == nil && stageSince != nil { + at := *stageSince + out.Since = &at + } + if out.Source == "" || out.Source == "unavailable" { + out.Source = "stage-review-pending" + } else { + out.Source += "+stage-review-pending" + } +} + func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { return number == observedNumber && head != "" && strings.EqualFold(head, observedHead) && strings.EqualFold(repo, observedRepo) } @@ -277,7 +538,7 @@ func stageTrackerReviewActivity(pr github.PullRequest, bundle *evidence.Bundle, out.State, out.Caption = "changes_requested", "Review findings · awaiting author" out.Blocker = stageTrackerFixerExhaustedSummary(agg) case "requires_human": - out.State, out.Caption = "human_decision", "Review findings · human decision" + out.State, out.Caption = "human_decision", "Review findings · needs owner sign-off" out.Blocker = agg.DecisionQuestion } } @@ -416,7 +677,7 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc // Bind an observed successful, worktree-verified edit to the exact // actor/repo/head assignment; unsupported instrumentation is unknown. if codeWork := trackerAssignedCodeWorker(status, it.Repo, it.Number, it.Head, fix.Agent, fix.Dispatched, now); codeWork != nil { - out.State, out.Caption, out.Active = "fixing", "Fixing · "+fix.Agent, true + out.State, out.Caption, out.Active = "fixing", "Remediating · "+fix.Agent, true out.Source, out.ObservedAt = "fix-dispatch+"+codeWork.Source, timePtr(codeWork.At) it.DisplayColumn = trackerNumberPRInProgress } @@ -429,7 +690,8 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc if err != nil || at.Before(fix.Dispatched) || at.After(now) || now.Sub(at) > trackerActivityFreshWindow { continue } - out.State, out.Caption = "waiting_ci", "Fix task waiting on CI · not observed coding" + out.State, out.Caption = "waiting_ci", "Fix task idle · agent waiting for CI before coding" + out.Detail = "The assigned fix agent is holding until CI reports on the PR's current commit; no code edits have been observed yet." out.Source, out.ObservedAt = "fix-dispatch+current-worker-ci-wait", &at if it.Stage != trackerNumberNeedsAuthor && it.Stage != trackerNumberReturned && it.Stage != trackerNumberAdopted { it.DisplayColumn = trackerNumberReviewPending @@ -454,7 +716,8 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc out = &StageTrackerActivity{Head: it.Head, State: "pushed", Caption: "New head pushed · CI and re-review", Source: "recorded-push", Since: it.Push.Since} if it.Push.State == pushStateChecking { - out.State, out.Caption, out.Source = "waiting_ci", "CI retry · no new head observed", "recorded-ci-retry" + out.State, out.Caption, out.Source = "waiting_ci", "CI retry requested · no new commit pushed yet", "recorded-ci-retry" + out.Detail = "A CI re-run was requested on the PR's current commit; the PR head has not changed, so the tracker waits for the re-run's result." } } } @@ -462,15 +725,19 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc if it.Stage == trackerNumberNeedsDecision || it.Stage >= trackerNumberAwaitingMerge || it.Superseded != nil { it.DisplayColumn = 0 } - if out.State == "waiting_fixer" && strings.HasPrefix(it.Caption, "Fixing paused") { - out.Blocker = strings.Replace(it.Caption, "Fixing paused", "Fix task blocked", 1) + if out.State == "waiting_fixer" && (strings.HasPrefix(it.Caption, "Remediation paused") || strings.HasPrefix(it.Caption, "Fixing paused")) { + detail := strings.TrimPrefix(it.Caption, "Remediation paused") + if detail == it.Caption { + detail = strings.TrimPrefix(it.Caption, "Fixing paused") + } + out.Blocker = "Fix task blocked" + detail out.Source += "+fix-dispatch-status" } it.CodeActivity = out // Replace generic or previously projected activity, not independent // native facts such as a foreign bot conflict, hold or rebase episode. if it.Stage == trackerNumberFixing && it.Superseded == nil && - (it.Caption == "" || strings.HasPrefix(it.Caption, "Fixing") || activityCaption || out.Active) { + (it.Caption == "" || strings.HasPrefix(it.Caption, "Remediating") || strings.HasPrefix(it.Caption, "Remediation paused") || strings.HasPrefix(it.Caption, "Fixing") || activityCaption || out.Active) { it.Caption = out.Caption if out.Actor != "" && !out.Active { it.Caption += " · " + out.Actor diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index b0be4119a1..41ca00b281 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -2,6 +2,8 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); +const vm = require('node:vm'); +const { pathToFileURL } = require('node:url'); const root = path.join(__dirname, 'static-src', 'js'); const strip = fs.readFileSync(path.join(root, 'tracker-row-strip.js'), 'utf8'); @@ -20,7 +22,14 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc); +function constLine(source, name) { + const match = source.match(new RegExp('const ' + name + ' = [^\\n]*;')); + assert.ok(match, name); + return match[0]; +} +const trackConsts = ['STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER', 'STAGE_TRACKER_WORKFLOW_APPROVAL_TIP', 'STAGE_TRACKER_RING_SEGMENT_GAP_MAX', 'STAGE_TRACKER_RING_RADIUS', 'STAGE_TRACKER_RING_GAP_DEG'].map(name => constLine(strip, name)).join('\n'); +const trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerActivityTrackHtml'].map(name => fn(strip, name)).join('\n'); +const track = new Function('esc', 'stageTrackerIcon', trackConsts + '\n' + trackFns + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -37,7 +46,7 @@ test('header has visibly separate aligned CI and Review columns without serial s }); test('both tracks can be active on one PR and preserve their actual actors and sources', () => { - const item = { kind: 'pr', head: 'head', ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working · reviewer', true) }; + const item = { kind: 'pr', head: 'head', ci_activity: activity('running', 'CI running · 1/2 checks done', true), review_activity: activity('reviewing', 'Review working · reviewer', true) }; const html = ['ci', 'review'].map(kind => track(item, kind, {}, false, now)).join(''); assert.equal((html.match(/data-motion="active"/g) || []).length, 2); assert.match(html, /data-track="ci"/); @@ -48,10 +57,10 @@ test('both tracks can be active on one PR and preserve their actual actors and s }); test('CI green/review findings and review approved/CI red remain independent', () => { - const item = { head: 'head', ci_activity: activity('passing', 'CI passed'), review_activity: activity('changes_requested', 'Review findings · awaiting author') }; + const item = { head: 'head', ci_activity: activity('passing', 'CI green · all 2 required checks passed'), review_activity: activity('changes_requested', 'Review findings · awaiting author') }; assert.match(track(item, 'ci', {}, false, now), /ham-activity-track done/); assert.match(track(item, 'review', {}, false, now), /data-activity-state="changes_requested"/); - item.ci_activity = activity('failing', 'CI failing · build'); + item.ci_activity = activity('failing', 'CI failing · "build" red'); item.review_activity = activity('approved', 'Review approved'); assert.match(track(item, 'ci', {}, false, now), /data-activity-state="failing"/); assert.match(track(item, 'review', {}, false, now), /ham-activity-track done/); @@ -88,7 +97,7 @@ test('repair display projection returns to PR progress then current-head tracks; test('linked PRs carry independent evidence and hidden issue columns stay aligned', () => { const layout = fs.readFileSync(path.join(root, 'tracker-row-layout.js'), 'utf8'); const linked = new Function('stageTrackerLinkedPROpen', 'STAGE_TRACKER_TERMINAL', fn(layout, 'stageTrackerLinkedPRItem') + ';return stageTrackerLinkedPRItem;')(() => true, 110); - const lp = { number: 7, head: 'head', stage: 70, display_column: 30, ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working · reviewer', true), code_activity: activity('fixing', 'Fixing · fixer', true) }; + const lp = { number: 7, head: 'head', stage: 70, display_column: 30, ci_activity: activity('running', 'CI running · 1/2 checks done', true), review_activity: activity('reviewing', 'Review working · reviewer', true), code_activity: activity('fixing', 'Fixing · fixer', true) }; const item = linked({ repo: 'org/repo', number: 1, linked_prs: [lp, { number: 8 }] }, lp); assert.equal(item.number, 7); assert.equal(item.display_column, 30); @@ -99,6 +108,563 @@ test('linked PRs carry independent evidence and hidden issue columns stay aligne assert.match(render, /ci_activity: lp.ci_activity \|\| null, review_activity: lp.review_activity \|\| null/); }); +const rowSource = fs.readFileSync(path.join(root, 'tracker-row.js'), 'utf8'); +const segments = new Function('stageTrackerAnchor', globals + ` +const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; +const STAGE_TRACKER_HUMAN_GATED = 85, STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90, STAGE_TRACKER_ADOPTED_BY_HIVE = 74; +function stageTrackerSentinelInLane() { return false; } +function stageTrackerUnauthorizedWord() { return ''; } +function stageTrackerManualMergeWord() { return 'Ready for human merge'; } +` + fn(rowSource, 'stageTrackerSegments') + ';return stageTrackerSegments;')(getAnchor); +const makeStripRenderer = (helpers = {}) => new Function('esc', 'stageTrackerSegments', 'stageTrackerActivityTrackHtml', ...Object.keys(helpers), globals + ` +const STAGE_TRACKER_MOTION_STATIC = 'static', STAGE_TRACKER_MOTION_ACTIVE = 'active'; +const STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90; +function stageTrackerActorKind() { return ''; } +function stageTrackerActorTip() { return ''; } +function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } +function stageTrackerIcon(n) { return ''; } +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); +const renderStrip = makeStripRenderer(); + +function physicalTracks(item) { + const rendered = renderStrip(item, stages, null, now, {}); + const cells = [...rendered.matchAll(//g)].map(match => match[0]); + assert.equal(cells.length, 8, 'actual strip expands native 050 into two physical tracks plus history'); + assert.match(cells[4], /data-track="ci"/); + assert.match(cells[5], /data-track="review"/); + return { rendered, cells, ci: cells[4], review: cells[5] }; +} +const livePR = extra => ({ kind: 'pr', head: 'head', stage: 50, modifiers: [], ...extra }); + +const actions = fs.readFileSync(path.join(root, 'tracker-actions.js'), 'utf8'); + +test('remediation wording preserves native identifiers, source names and waiting semantics', () => { + for (const caption of ['Fixing · FixingBot', 'Remediating · FixingBot']) { + const code = activity('fixing', caption, true); + const item = livePR({ stage: 70, display_column: 30, title: 'Fixing a widget — public PR title', code_activity: code }); + const current = physicalTracks(item).cells[3]; + assert.match(current, /Remediating · FixingBot/); + assert.match(current, /data-motion="active"/); + assert.equal(code.state, 'fixing', 'internal state stays stable'); + assert.equal(code.caption, caption, 'rendering does not rewrite recorded source evidence'); + assert.equal(item.title, 'Fixing a widget — public PR title'); + code.observed_at = new Date(now - 300000).toISOString(); + const stale = physicalTracks(item).cells[3]; + assert.doesNotMatch(stale, /data-motion="active"/); + assert.match(stale, /Fix task assigned · activity unknown/); + assert.doesNotMatch(stale, /ham-detour[^>]*>Remediating/); + } +}); + +test('12:01 screenshot density preserves physical tracks for issue-only, one-to-one, multi-PR and PR-only rows', () => { + const fixture = JSON.parse(fs.readFileSync(path.join(__dirname, 'webstatic/testdata/tracker-activity-density.json'), 'utf8')); + const clock = Date.parse(fixture.clock); + const fixtureStages = [...stages, { number: 90, short: 'Ready for human merge', branch_from: 80 }]; + for (const row of fixture.rows) { + const linked = row.linked_prs || []; + const items = linked.length === 1 ? [{ ...linked[0], kind: 'pr', repo: row.repo }] : + [row, ...linked.map(pr => ({ ...pr, kind: 'pr', repo: row.repo }))]; + for (const item of items) { + const range = item === row && linked.length > 1 ? { to: 20 } : item !== row && linked.length > 1 ? { from: 30 } : null; + const rendered = renderStrip(item, fixtureStages, range, clock, {}); + const cells = [...rendered.matchAll(//g)].map(match => match[0]); + assert.equal(cells.length, 8, 'all row structures retain seven lanes plus history'); + if (range?.from) { + assert.ok(cells.slice(0, 3).every(cell => /class="ham-seg blank"/.test(cell)), 'nested PRs reserve the physical Open–Claimed slots'); + } + if (range?.to) { + assert.ok(cells.slice(3).every(cell => /class="ham-seg blank/.test(cell)), 'multi-PR issue owns no PR-side activity'); + } + if (item.number === 344) { + assert.match(cells[4], /active ham-current[^]*CI \?\/\? · queued /data-display-state="unknown"/.test(cell))) { + const content = cell.match(/aria-describedby="[^"]+">([^]*?)]*>/g, '').trim(); + if (/ham-current/.test(cell)) assert.match(words, /^(CI|Review)\b/, 'a track in the current phase always carries count words (#16484)'); + else assert.equal(words, '', 'a track not started on this head is the glyph alone'); + } + } + } +}); + +test('merge-gate claim decisions wrap the complete gate caption and use only their existing decision dialog', () => { + const gate = { word: 'Claim conflict · @' + 'unbrokenclaimanthandle'.repeat(12), detail: 'needs a pick', tip: 'Two claimants need a human decision' }; + const decisionOf = new Function('stageTrackerItemKey', fn(actions, 'stageTrackerDecisionOf') + ';return stageTrackerDecisionOf;')(item => item.repo + '/' + item.kind + '#' + item.number); + const trigger = new Function('esc', fn(actions, 'stageTrackerDecisionTriggerHtml') + ';return stageTrackerDecisionTriggerHtml;')(esc); + const gateSource = fs.readFileSync(path.join(root, 'tracker-words-gate.js'), 'utf8'); + const gateWord = new Function('esc', 'stageTrackerMergeGateInfo', fn(gateSource, 'stageTrackerMergeGateWordHtml') + ';return stageTrackerMergeGateWordHtml;')(esc, () => gate); + const render = makeStripRenderer({ + stageTrackerDecisionOf: decisionOf, stageTrackerDecisionTriggerHtml: trigger, + stageTrackerMergeGateInfo: () => gate, stageTrackerMergeGateWordHtml: gateWord, + }); + const item = livePR({ + repo: 'hivecommons/hive', number: 7, stage: 80, reason: 'Unabridged claim conflict reason', + decision_needed: { question: 'Which claimant should continue?', blocker: 'Do not merge until the claim conflict is resolved' }, + }); + const cells = [...render(item, stages, null, now, {}).matchAll(//g)].map(match => match[0]); + const cell = cells[6]; + assert.match(cell, /^
  • ]*>/); + assert.match(cell, /ham-chevron-copy">', + stageTrackerTooltip: () => 'tooltip', + stageTrackerPRPillsHtml: ref => `${ref}base v5`, + stageTrackerActedBadgeHtml: () => '', + stageTrackerChipsHtml: () => chips, + stageTrackerMoveAttrs: () => '', + stageTrackerSinceHtml: () => '2m', + stageTrackerCurrentStageHtml: () => '', + stageTrackerRowToolsHtml: () => '', + stageTrackerStripItems: () => '', + }); + for (const name of ['STAGE_TRACKER_PATH', 'STAGE_TRACKER_PR_COLUMN', 'STAGE_TRACKER_TERMINAL', + 'STAGE_TRACKER_CLOSED_ISSUE_TITLE', 'STAGE_TRACKER_UNTITLED_ISSUE', 'STAGE_TRACKER_SOFT_LINK_VIAS', 'STAGE_TRACKER_SOFT_LINK_TIP']) { + vm.runInContext(pick(new RegExp('const ' + name + ' = [^\\n]*'), name), ctx); + } + for (const name of ['stageTrackerHeadColsHtml', 'stageTrackerHeaderHtml', 'stageTrackerRowHtml', 'stageTrackerSubRowHtml', + 'stageTrackerPRRef', 'stageTrackerPRIssueSlot', 'stageTrackerTitleHtml', 'stageTrackerSplitTitleTag']) { + vm.runInContext(fn(name), ctx); + } + return ctx; +} +const pr = { kind: 'pr', repo: 'hivecommons/hive', number: 7, stage: 70, title, author: 'a-very-long-contributor', author_kind: 'human', url: 'https://github.com/hivecommons/hive/pull/7' }; +const issue = { kind: 'issue', repo: pr.repo, number: 1, stage: 20, title: '[scanner] ' + title, url: 'https://github.com/hivecommons/hive/issues/1' }; + +for (const [name, item] of [ + ['issue-only', issue], + ['linked issue/PR', { ...issue, linked_prs: [pr] }], + ['PR-only', pr], +]) test(name + ': full metadata stays in the correct header slots', () => { + const ctx = load(); + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: 1, repoChips: {} }); + const start = Number(rendered.match(/data-ham-pr-start="(\d+)"/)[1]); + assert.equal(start, 4, 'PR metadata starts at PR in progress, not Actionable'); + const lead = rendered.match(/
  • ([\s\S]*?)<\/li>/)[1]; + if (name === 'PR-only') { + assert.match(lead, /no linked issue/); + assert.doesNotMatch(lead, /#7/); + } else { + assert.match(lead, /#1/); + assert.ok(lead.includes(title), 'complete issue title, not a shortened replacement'); + assert.match(lead, /ham-title-tag/); + } + if (name !== 'issue-only') { + const ref = rendered.match(/
  • ]*>([\s\S]*?)<\/li>/)[1]; + assert.match(ref, /#7/); + assert.ok(ref.includes(title)); + assert.match(ref, /ham-author-human/); + if (name === 'linked issue/PR') assert.match(rendered, /data-ham-target-key="pr:7"/); + } + assert.ok(rendered.includes(chips), 'waiting, push, and regression metadata is retained'); +}); + +function rule(selector) { + // Match the whole selector, not its suffix in ".ham-cols .ham-strip". + const found = html.match(new RegExp('(?:^|[\\r\\n])[\\t ]*' + selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' \\{([^}]+)\\}')); + assert.ok(found, selector); + return found[1]; +} + +test('persistent human/preparation context wins the generic event-entry animation cascade', () => { + assert.match(rule('.cue-event'), /animation: cue-event-in/); + for (const selector of ['.cue-event.ham-human-context', '.cue-event.ham-preparation-comment']) { + assert.match(rule(selector), /animation: none/); + assert.ok(selector.split('.').length > '.cue-event'.split('.').length, + 'persistent context has greater specificity even when the generic event rule appears later'); + } +}); + +test('row materialization binds canonical header boundaries for root and nested rows', () => { + const headers = ['4', '5'].map(hamPrStart => ({ + dataset: { hamPrStart }, properties: {}, + style: { setProperty(name, value) { this.owner.properties[name] = value; } }, + })); + for (const header of headers) header.style.owner = header; + const node = { dataset: {}, querySelectorAll(selector) { + assert.equal(selector, '.ham-head-cols[data-ham-pr-start]'); + return headers; + } }; + const ctx = vm.createContext({ _stageTrackerRowSrc: null, + document: { createElement: () => ({ content: { firstElementChild: node } }) } }); + vm.runInContext(fn('stageTrackerRowNode'), ctx); + assert.equal(ctx.stageTrackerRowNode('issue:1', ''), node); + assert.equal(node.dataset.hamKey, 'issue:1'); + assert.deepEqual(headers.map(header => header.properties['--ham-pr-start']), ['4', '5']); +}); + +test('spans share the physical lane grid, including independent concurrent CI/Review', () => { + const ctx = load(); + const header = ctx.stageTrackerHeaderHtml([]); + const physicalCount = (header.match(/
  • CI<\/span>/); + assert.match(header, />Review<\/span>/); + const strip = rule('.ham-strip'); + assert.match(strip, /display: grid/); + assert.match(strip, /grid-template-columns: repeat\(var\(--ham-visible-columns\), minmax\(0, 1fr\)\) 4em/); + const laneCount = Number(strip.match(/--ham-visible-columns: (\d+)/)[1]); + assert.equal(laneCount, physicalCount - 1, 'CSS and actual rendered lane count must agree'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-lead'), /grid-column: 1 \/ var\(--ham-pr-start\)/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /grid-column: var\(--ham-pr-start\) \/ -2/); + assert.doesNotMatch(html, /\.ham-head-cols \.ham-seg\.cap \{/, 'no separate toolbar line between the title line and the chevrons'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /margin-left: auto/, 'chips right-anchor on the PR line'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /justify-content: flex-end/); + // Resolve the declared grid lines using the actual header's track count. + // Content cannot alter minmax(0,1fr) track widths; covered gaps belong to spans. + const start = Number(ctx.stageTrackerHeadColsHtml(['PR'], 'issue', chips).match(/data-ham-pr-start="(\d+)"/)[1]); + const gap = 4, cap = 48; + for (const width of [2400, 1440, 1110]) { + const lane = (width - cap - laneCount * gap) / laneCount; + const prLeft = (start - 1) * (lane + gap); + const issueRight = (start - 1) * lane + (start - 2) * gap; + const prRight = laneCount * lane + (laneCount - 1) * gap; + assert.ok(Math.abs(prLeft - issueRight - gap) < 1e-9, 'issue span ends one gutter before PR'); + assert.ok(Math.abs((prRight - prLeft) - ((laneCount - start + 1) * lane + (laneCount - start) * gap)) < 1e-9); + assert.ok(prRight < width - cap, 'PR span excludes the history cap'); + } + vm.runInContext('STAGE_TRACKER_PATH.splice(2, 0, 15)', ctx); + assert.match(ctx.stageTrackerHeadColsHtml(['PR']), /data-ham-pr-start="5"/, 'boundary derives from canonical stages, not a second hard-coded span'); +}); + +test('chevron height is one caption line (compact strip, single-line clamp) and the caption stays centred', () => { + const strip = rule('.ham-strip[aria-label="Pipeline progress"]'); + const seg = rule('.ham-strip[aria-label="Pipeline progress"] > .ham-seg'); + const copy = rule('.ham-chevron-copy'); + assert.match(strip, /grid-auto-rows: minmax\(calc\(var\(--ham-chevron-line-height\) \* 1em \+ 2 \* var\(--sp-1\) \+ 2 \* var\(--line-width\)\), auto\)/, + 'rows size to content above a one-line floor with sp-1 vertical padding (~20px strip)'); + assert.match(seg, /padding: var\(--sp-1\) calc\(var\(--ham-notch\) \+ var\(--sp-2\)\)/, 'sp-2 vertical padding doubled the strip height (hivecommons/hive#16454)'); + assert.match(rule('.ham-strip'), /--ham-chevron-text-lines: 1;/, 'captions are clamped to one line so the strip stays compact'); + assert.doesNotMatch(strip, /grid-auto-rows: calc\(var\(--ham-chevron-text-lines\)/, 'no fixed two-line row height around one line of text'); + assert.match(seg, /align-self: stretch/); + assert.doesNotMatch(seg, /height: 100%/, 'siblings follow the row, the row follows its content'); + assert.match(copy, /max-height: calc\(var\(--ham-chevron-text-lines\) \* var\(--ham-chevron-line-height\) \* 1em\)/, 'the clamp caps the copy at --ham-chevron-text-lines lines'); + assert.match(copy, /flex: 0 1 auto/, 'the copy shrink-wraps its text so justify-content: center centres it'); + assert.match(copy, /text-align: center/, 'a wrapped second line is centred under the first'); + assert.match(rule('.ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision'), /align-items: center; justify-content: center/); +}); + +test('the issue title sits inline after its chips on the first line, not on a line of its own', () => { + const ctx = load(); + const rendered = ctx.stageTrackerRowHtml({ ...issue, number: 16475 }, [], { nowMs: 1, repoChips: {} }); + // One flex container holds icon, repo chip, #ref, agent chip and title. + const main = rendered.match(/
    ([\s\S]*?)<\/div>/)[1]; + assert.match(main, /ham-kind-ico[\s\S]*ham-repo-chip[\s\S]*ham-ref[\s\S]*#16475[\s\S]*ham-title-tag[\s\S]*class="ham-title"/, + 'kind icon, repo chip, #ref, agent chip and title render in that order in one container'); + assert.doesNotMatch(main, /<(div|p|br)\b/, 'no block element splits the title from its chips'); + const container = rule('.ham-head-main'); + assert.match(container, /display: flex/); + assert.match(container, /flex-wrap: wrap/, 'chips may still wrap when a line is genuinely full'); + const t = rule('.ham-head-main > .ham-title'); + assert.match(t, /flex: 1 1 0/, 'a zero flex-basis keeps the title on the chip line and fills the rest of it (a max-content basis drops the whole title to line 2)'); + assert.match(t, /min-width: 0/); + assert.match(t, /white-space: normal/, 'the title wraps its own words only when there is no room'); + const prRef = rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line'); + assert.match(prRef, /flex: 1 1 0; min-width: min\(100%, 20em\)/, 'the PR ref shares its line with the right-anchored pills'); + assert.match(rule('.ham-head-pr .ham-pr-title'), /flex: 1 1 0/); +}); + +test('long metadata wraps in bounded slots and the narrow layout resets both grid axes', () => { + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /flex-wrap: wrap/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /flex-wrap: wrap/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /max-width: 100%/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /justify-content: flex-end/); + assert.match(rule('.ham-head-cols .ham-badge'), /white-space: normal; overflow-wrap: anywhere/); + assert.match(html, /\.ham-head-main > \.ham-title \{ flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); + assert.match(html, /\.ham-head-pr \.ham-pr-title \{ flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); + assert.match(html, /@media \(max-width: 1100px\) \{[\s\S]*?\.ham-head-cols \.ham-strip > \.ham-seg \{ grid-column: 1 \/ -1; grid-row: auto; padding: 0; \}/); + assert.doesNotMatch(html, /\.ham-strip:not\(\.ham-head-cols\)/, 'the old ancestor/element selector mistake must not return'); +}); + +test('issue-only, linked and PR-only controls ride the title line, right-anchored in the PR span, never a line of their own', () => { + for (const [number, label, history, blocked] of [ + [15329, 'Let hive decide', 1, false], + [16242, '', 0, false], + [16422, 'Accept triage', 0, false], + [16423, '', 1, false], + [16363, '', 0, false], + [16424, 'Close now', 0, false], + [431, '', 1, true], + ]) { + const ctx = load(); + ctx.stageTrackerActedBadgeHtml = () => history ? 'history ' + history + '' : ''; + ctx.stageTrackerChipsHtml = () => blocked ? 'blocked' : ''; + ctx.stageTrackerLeadButtonHtml = () => label ? '' : ''; + for (const item of [{ ...issue, number, is_tracker: number === 16242 }, { ...issue, number, linked_prs: [pr] }, { ...pr, number }]) { + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: 1 }); + assert.doesNotMatch(rendered, /
  • /, 'the title line has no separate toolbar cell'); + const prCell = rendered.match(/
  • ]*>([^]*?)<\/li>/)[1]; + const toolbar = prCell.match(/([^]*)<\/span>$/); + assert.ok(toolbar, 'chips are the trailing flex item of the PR cell'); + const chipsHtml = toolbar[1]; + if (!item.linked_prs && item.kind === 'issue') assert.match(rendered, /
  • /, 'an issue without PR refs still gets the PR cell for its chips'); + if (label) { + assert.ok(chipsHtml.includes(label)); + assert.equal(rendered.split(label).length - 1, 1, 'action is not duplicated to fake alignment'); + assert.match(chipsHtml, /type="button"[^]*data-action="fixtureAction"/); + } + if (history) assert.match(chipsHtml, /ham-acted" tabindex="0">history 1/); + if (blocked) assert.match(chipsHtml, />blocked([^]*?)<\/li>/)[1]; + assert.doesNotMatch(lead, /ham-lead-act|ham-acted|>blocked .ham-badges'); + assert.match(toolbar, /position: static/); + assert.match(toolbar, /margin-left: auto/); + assert.match(toolbar, /justify-content: flex-end/); + assert.doesNotMatch(toolbar, /position: absolute|[^-]left:|[^-]right:/, "flow layout, never an absolute overlay over the title"); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /grid-row: 1/, 'the PR cell, and so its chips, shares the title line'); + assert.doesNotMatch(html, /\.ham-head-cols [^{]*\{[^}]*grid-row: 2/, 'nothing in the title block claims a second grid row'); +}); + +test('12:01 screenshot density: real multi-PR/sub-row structure preserves distinct headers and full-width control ownership', () => { + const fixture = JSON.parse(fs.readFileSync(path.join(__dirname, 'webstatic/testdata/tracker-activity-density.json'), 'utf8')); + const ctx = load(); + vm.runInContext(fn('stageTrackerPRPillsHtml'), ctx); + ctx.stageTrackerChipsHtml = item => item.push ? `${esc('@' + item.push.login + ' · ' + (item.rework?.state || item.push.state))}` : ''; + ctx.stageTrackerLeadButtonHtml = item => { + const text = item.linked_prs?.length > 1 ? 'Let hive decide — all ' + item.linked_prs.length + ' PRs' : item.decision_needed ? 'Let hive decide' : item.manual_merge ? 'Approve and let hive merge' : ''; + return text ? `` : ''; + }; + ctx.stageTrackerActedBadgeHtml = item => item.operator_action_count ? 'history 1' : ''; + ctx.stageTrackerHumanContextHtml = item => item.reason ? `
    ${esc(item.reason)}
    ` : ''; + let multi = 0, nested = 0; + for (const item of fixture.rows) { + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: Date.parse(fixture.clock), repoChips: {} }); + const children = item.linked_prs?.length > 1 ? item.linked_prs : []; + multi += children.length > 1 ? 1 : 0; + nested += children.length; + assert.equal((rendered.match(/
    /g)) { + assert.match(header[1], /data-ham-pr-start="4"/); + assert.equal((header[1].match(/class="ham-badges"/g) || []).length, 1, 'one right-anchored toolbar per identity, on its title line'); + assert.doesNotMatch(header[1], /class="ham-seg cap"/, 'no separate toolbar line'); + const lead = header[1].match(/ham-head-lead[^"]*">([^]*?)<\/li>/)[1]; + assert.doesNotMatch(lead, /ham-badge-waiting|ham-lead-act|ham-acted/, 'activity/action/history controls never overprint the issue title slot'); + } + for (const pr of children) { + const start = rendered.indexOf('data-ham-sub-key="pr:' + pr.number + '"'); + assert.ok(start >= 0); + const sub = rendered.slice(start).split('
  • `, stageTrackerCurrentStageHtml: it => `${it.stage}`, - stageTrackerEventHtml: (key, ctx) => `

    ${esc(ctx && ctx.note || 'live note')}

    `, + stageTrackerEventHtml: (key, ctx) => ctx && ctx.events && ctx.events[key] ? `

    Hive: ${esc(ctx.events[key].text)}

    ` : '', stageTrackerActionCtx: () => ({ user: 'viewer' }), stageTrackerLeadActionOnRow: item => item.optionalAction ? { id: 'decide:delegate', label: 'Let hive decide' } : null, }); @@ -58,12 +59,16 @@ function issue(linked) { test('covered issue shows the exact PR requirement/requester in visible prose without overriding its actual stage', () => { const c = load(), child = pr(), item = issue([child]), before = plain(item); - const html = c.stageTrackerRowHtml(item, [], { nowMs: 1, note: 'review comment' }); + const html = c.stageTrackerRowHtml(item, [], { nowMs: 1, events: { 'hivecommons/hive/issue#15937': { who: 'hive', text: 'review comment', at: 1 } } }); assert.match(html, /data-ham-kind="issue".*data-ham-stage="40"/); assert.match(html, /data-stage="85"/); assert.match(html, /PR #15985 — Needs human: Confirm the compatibility policy · next move: @maintainer · requested by a reviewer/); assert.match(html, />View PR #15985<\/a>/); - assert.match(html, /cue-event-tuckable.*data-cue-key=.*review comment.*Reopen/); + // One note line: the hive's stage note rides the human line as a + // trailing clause instead of a second "Hive: …" line. + assert.equal((html.match(/class="cue-event/g) || []).length, 1); + assert.match(html, /requested by a reviewer ]*>View PR #15985<\/a> · review comment/); + assert.doesNotMatch(html, /Hive: review comment/); assert.doesNotMatch(html, /Needs you|ham-preparation-head|
    item.blocker ? { id: 'open:app-settings', label: 'Grant the App workflows: write' } : (item.decision_needed ? { id: 'decide:delegate', label: 'Let hive decide' } : null); + return c; +} +const why612 = "Hive can't do this one: the GitHub App has no `workflows` permission, so it cannot push changes to .github/workflows/*. Options: (a) grant the App workflows: write, (b) apply by hand."; +function issue612() { + const pr620 = { kind: 'pr', repo: 'hivecommons/docs', number: 620, stage: 50, state: 'open', head: 'h620', author: 'bob', author_kind: 'human', + title: 'ci: opt in', url: 'https://github.com/hivecommons/docs/pull/620', stage_actor: { kind: 'hive' } }; + return { kind: 'issue', repo: 'hivecommons/docs', number: 612, stage: 45, state: 'open', modifiers: ['needs-human'], needs_human: true, + title: 'Opt docs refresh into hive', url: 'https://github.com/hivecommons/docs/issues/612', linked_pr: 620, linked_prs: [pr620], + human_attention: { kind: 'issue', number: 612, reason: why612, asked_by: 'the hive' }, + blocker: { kind: 'capability:workflows-permission', short: 'App lacks workflows permission' }, + decision_needed: { question: 'Grant the permission or close as partial?', options: [{ action: 'decide:delegate', enabled: false, reason_if_disabled: 'No decision grants the App the permission' }] } }; +} + +test('covered issue on a capability blocker names the blocker, the ask, the asker, the lead move and who is pushing the PR', () => { + const c = needsHumanContext(); + const html = c.stageTrackerRowHtml(issue612(), [], { nowMs: 1 }); + assert.match(html, /#612 — Needs human: App lacks workflows permission — Hive can't do this one: the GitHub App has no `workflows` permission, so it cannot push changes to \.github\/workflows\/\*\./); + assert.match(html, /· requested by the hive · lead: Grant the App workflows: write ▸ · @bob is pushing it in #620/); + assert.doesNotMatch(html, /Options: \(a\)/, 'only the first sentence of the ask rides on the row'); + // The line is unchanged when the strip is the issue's own. + const alone = issue612(); alone.linked_prs = []; delete alone.linked_pr; + assert.doesNotMatch(c.stageTrackerHumanContextHtml(alone, [], 1), /is pushing it/); + assert.match(c.stageTrackerHumanContextHtml(alone, [], 1), /App lacks workflows permission/); + // A hive-authored covering PR is not "pushed by" anyone on the line. + const hive = issue612(); hive.linked_prs[0].author_kind = 'hive'; hive.linked_prs[0].author = 'hive-bot'; + assert.doesNotMatch(c.stageTrackerHumanContextHtml(hive, [], 1), /is pushing it/); +}); + +test('085 PR without human_attention still states the decision question from decision_needed', () => { + const c = needsHumanContext(); + const item = { kind: 'pr', repo: 'hivecommons/rationguard', number: 480, stage: 85, state: 'open', head: 'h480', modifiers: ['needs-decision'], + title: 'ci: pin runners', url: 'https://github.com/hivecommons/rationguard/pull/480', human_reason: 'workflow path', + stage_actor: { kind: 'human', why: 'a human decision is owed — workflow path', human_reason: 'workflow path' }, + decision_needed: { question: 'The hive never merges this by itself (it edits CI workflow files). Approve it for a maintainer to merge, give direction, or close it?', + blocker: 'The hive never merges this by itself. After approval, a maintainer merges.', asked_by: 'the hive' } }; + const ask = c.stageTrackerNeedsHumanAsk(item); + assert.ok(ask && ask.synthetic, JSON.stringify(ask)); + assert.equal(ask.reason, item.decision_needed.question); + const html = c.stageTrackerHumanContextHtml(item, [], 1); + assert.match(html, /Needs human: edits CI workflows — The hive never merges this by itself \(it edits CI workflow files\)\./); + assert.match(html, /Approve it for a maintainer to merge, give direction, or close it\?/, 'the full question stays on the line'); + assert.match(html, /· asked by the hive/); + assert.doesNotMatch(html, /lead: Let hive decide/, 'the optional delegation is not the person\'s move'); + // Human attention from the server wins over the synthesized ask; a parked + // stage with no evidence synthesizes nothing. + assert.equal(c.stageTrackerNeedsHumanAsk({ ...item, human_attention: { kind: 'pr', number: 480, head: 'h480', reason: 'x' } }), null); + assert.equal(c.stageTrackerNeedsHumanAsk({ ...item, decision_needed: null, stage_actor: { kind: 'hive' } }), null); + for (const mutate of [it => { it.state = 'closed'; }, it => { it.modifiers = ['draft']; }, it => { it.hold = { by: 'owner' }; }]) { + const changed = plain(item); mutate(changed); + assert.equal(c.stageTrackerNeedsHumanAsk(changed), null); + } +}); diff --git a/src/pkg/dashboard/stage_tracker_item_column_test.go b/src/pkg/dashboard/stage_tracker_item_column_test.go index 5713be02bc..6404ddc4b7 100644 --- a/src/pkg/dashboard/stage_tracker_item_column_test.go +++ b/src/pkg/dashboard/stage_tracker_item_column_test.go @@ -139,3 +139,68 @@ func TestStageTrackerFixingAfterMergeFailedColumn(t *testing.T) { t.Fatalf("linked_prs payload lacks left_train:\n%s", raw) } } + +// TestStageTrackerPersonActsOnPRColumn replays hive's own #16524: a PR +// parked at 085 under hive:unauthorized (a maintainer must rerun shared +// CI on GitHub) with CI unknown and review findings open. The ask is a +// person's move ON THE PR, so its chevron is PR in progress and the +// Merge queue column is empty — the gate is only for rows queued / +// merging / merged, or a merge-ready PR parked on a merge decision. +func TestStageTrackerPersonActsOnPRColumn(t *testing.T) { + head := "7879a51f276a0f9aa5adc995d9d09a74487bbcf4" + ci := func(state string) *StageTrackerActivity { return &StageTrackerActivity{Head: head, State: state} } + review := func(state string) *StageTrackerActivity { return &StageTrackerActivity{Head: head, State: state} } + live := func() StageTrackerItem { + return StageTrackerItem{Repo: "hivecommons/hive", Number: 16524, Kind: "pr", Stage: stagelabels.NeedsDecision.Number(), Head: head, + Reason: "unauthorized:rerun-shared-ci", UnauthorizedStep: "rerun shared ci", + CIActivity: ci("unknown"), ReviewActivity: review("changes_requested")} + } + cases := []struct { + name string + mut func(*StageTrackerItem) + want int + }{ + {"#16524 as served", func(*StageTrackerItem) {}, trackerColumnPR}, + {"unauthorized step, no track evidence", func(it *StageTrackerItem) { it.CIActivity, it.ReviewActivity = nil, nil }, trackerColumnPR}, + {"unauthorized step on a merge-ready head", func(it *StageTrackerItem) { it.CIActivity, it.ReviewActivity = ci("passing"), review("approved") }, trackerColumnMergeGate}, + {"decision with review findings open", func(it *StageTrackerItem) { it.Reason, it.UnauthorizedStep = "", "" }, trackerColumnPR}, + {"decision with CI red, review approved", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("failing"), review("approved") + }, trackerColumnPR}, + {"approved decision with CI running on the head keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("running"), review("approved") + }, trackerColumnMergeGate}, + {"approved decision with CI queued on the head keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("queued"), review("approved") + }, trackerColumnMergeGate}, + {"bare 085 decision keeps the gate (#14821)", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", nil, nil + }, trackerColumnMergeGate}, + {"merge-ready decision keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("passing"), review("approved") + }, trackerColumnMergeGate}, + {"stale track evidence on another head is not evidence", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep = "", "" + it.CIActivity.Head, it.ReviewActivity.Head = "old", "old" + }, trackerColumnMergeGate}, + {"a seated train member is a Merge queue matter", func(it *StageTrackerItem) { + it.MergeTrain = &StageTrackerMergeTrain{ID: "v5#1", State: MergeGateStateQueuedBehind, Front: 1, Position: 2, Size: 2} + }, trackerColumnMergeGate}, + {"a live merge attempt is a Merge queue matter", func(it *StageTrackerItem) { it.MergeGate = &StageTrackerMergeGate{State: MergeGateStateMerging} }, trackerColumnMergeGate}, + {"an issue at 085 is unchanged", func(it *StageTrackerItem) { it.Kind = "issue" }, stageTrackerColumn(stagelabels.NeedsDecision)}, + {"070 fixing is untouched", func(it *StageTrackerItem) { it.Stage = stagelabels.Fixing.Number() }, trackerColumnReview}, + } + for _, tc := range cases { + it := live() + tc.mut(&it) + if got := stageTrackerItemColumn(&it); got != tc.want { + t.Errorf("%s: column %d, want %d", tc.name, got, tc.want) + } + } + // The caption names the step as the person's move on GitHub, never as + // a merge-queue wait. + caption, actor := stageTrackerCaption(stagelabels.NeedsDecision, "unauthorized:rerun-shared-ci", "clubanderson", "pr", false, stagelabels.Record{}, false, 0, head) + if !strings.Contains(caption, "Waiting for a maintainer · rerun shared ci on GitHub") || strings.Contains(caption, "Awaiting human") || actor != "maintainer" { + t.Fatalf("caption %q actor %q", caption, actor) + } +} diff --git a/src/pkg/dashboard/stage_tracker_lead_action_test.go b/src/pkg/dashboard/stage_tracker_lead_action_test.go index ea28fc7b66..de9a82eb87 100644 --- a/src/pkg/dashboard/stage_tracker_lead_action_test.go +++ b/src/pkg/dashboard/stage_tracker_lead_action_test.go @@ -16,7 +16,9 @@ import ( // is the viewer's now renders its lead action as a real button in the chip // slot: the ⋯ menu's `lead` entry, else the first Decide… option, else // Adopt; the same id, hint and enable/disable reason, run down the same -// runRowAction path. One button only; everything else stays in ⋯. +// runRowAction path. One button only — plus "Let hive decide" beside the +// server's lead on a row parked on a human decision; everything else +// stays in ⋯. func TestStageTrackerLeadActionInline(t *testing.T) { html := indexHTML(t) @@ -27,6 +29,10 @@ func TestStageTrackerLeadActionInline(t *testing.T) { `stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : '')`, `stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : '')`, `.ham-lead-act[aria-disabled="true"]`, + `.ham-lead-act::after { content: '▸';`, + `.ham-lead-act.ham-act-secondary {`, + `.ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red);`, + `.ham-lead-act[aria-disabled="true"]::after { content: none; }`, } { if !strings.Contains(html, want) { t.Errorf("index.html lacks %q", want) @@ -48,7 +54,7 @@ assert.strictEqual(lead.id, 'accept-triage'); let h = stageTrackerLeadActionHtml(fresh, ctx); assert.strictEqual(buttons(h), 1, 'one inline button only: ' + h); assert.strictEqual(labelOf(h), 'Accept triage'); -assert.ok(h.startsWith(''), h); +let leads = stageTrackerLeadActionsOnRow(human, ctx); +assert.strictEqual(leads.length, 2); +assert.strictEqual(leads[1].id, 'decide:delegate'); +assert.strictEqual(leads[1].target, human, 'delegate carries the decide target'); +assert.strictEqual(leads[1].enabled, true); +// The parked issue whose lead already is delegate: one pill, never two. +assert.strictEqual(stageTrackerLeadActionsOnRow(parked, ctx).length, 1); +// A Give-direction lead (the #16456 row, a hive-authored PR whose fixer +// gave up — the hive re-authors those itself, so no re-author pill is +// offered): both pills, delegate disabled with its reason for a reader. +const reauthor = { ...human, number: 16456, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:direction', label: 'Give direction', enabled: true, lead: true, consequence: 'Tell the hive what to change; its next attempt starts from your words.' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +h = stageTrackerLeadActionHtml(reauthor, ctx); +assert.strictEqual(buttons(h), 2, h); +assert.strictEqual(labelOf(h), 'Give direction', h); +assert.ok(!h.includes('re-author'), 'no re-author pill on a hive-authored row: ' + h); +assert.ok(h.includes('data-ham-act="decide:delegate"'), h); +// Owner on that row: the lead read as a record of what happened — the +// action pills and the record pills ("adopted from #N", the base branch) +// wore the same outline. Inline actions are ') && h.includes('>Let hive decide'), h); +`) + runStageTrackerRowActionsScript(t, ` +const assert = require('assert'); +const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting · opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; +`+jsConstLine(t, html, "STAGE_TRACKER_PARK_KEPT_ACTING")+` +`+jsFunc(t, html, "stageTrackerDecidedActing")+` +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'owner-only' }, {}), 'Your decision needed · owner sign-off'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'operator-action' }, {}), 'Your action needed · operator step'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'recommend-only' }, {}), 'Recommendation recorded'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended' }, {}), 'Your decision needed', 'no verdict, no recommendation claimed'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'adopted' }, {}), 'Adopting · opening hive copy…'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'owner-only' }, { decided: { acting: 'from server' } }), 'from server'); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_single_note.test.js b/src/pkg/dashboard/stage_tracker_single_note.test.js new file mode 100644 index 0000000000..408c03f461 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_single_note.test.js @@ -0,0 +1,158 @@ +// One note line per Activity Monitor row. The owner saw a row carry two +// hive comments — "Needs human: … · requested by a reviewer View PR #16619" +// over "Hive: moved to Needs human decision" — and asked for one: +// needs-human / decision > blocker > next move > stage note, with the +// loser's facts folded in only when they add something the row does not +// already say. Runs the shipped tracker-motion + tracker-human-attention +// sources so the real tuckable line (⬡ icon, View link, one age) is what +// is asserted. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = name => fs.readFileSync(path.join(__dirname, 'static-src/js', name + '.js'), 'utf8'); +const fn = (file, name) => { + const text = source(file); + const match = text.match(new RegExp('function ' + name + '\\([^\\n]*\\) \\{[^\\n]*\\}\\s*(?:\\n|$)')) + || text.match(new RegExp('function ' + name + '\\([^\\n]*\\) \\{[\\s\\S]*?\\n \\}')); + assert.ok(match, name); + return match[0]; +}; +const esc = value => String(value).replace(/[&<>"']/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); +const STAGES = [ + { number: 40, label: 'stage/040-covered-by-pr', short: 'Covered by PR' }, + { number: 50, label: 'stage/050-ci-review', short: 'CI / Review' }, + { number: 85, label: 'stage/085-needs-human-decision', short: 'Needs human decision' }, +]; +function load() { + const c = vm.createContext({ Date, esc, console, + document: { hidden: false, getElementById: () => null }, + localStorage: { getItem: () => null, setItem: () => {} }, + setTimeout: () => 0, clearTimeout: () => {}, + dashboardSetInterval: () => 0, + STAGE_TRACKER_TERMINAL: 100, STAGE_TRACKER_PR_COLUMN: 40, + STAGE_TRACKER_PATH: [0, 10, 20, 40, 50, 80], + STAGE_TRACKER_LINKED_GLYPH: '↳', STAGE_TRACKER_SOFT_LINK_TIP: 'refs', + stageTrackerAnchor: n => Number(n) || 0, + stageTrackerAttentionTier: () => 1, + stageTrackerLeadStage: lp => lp.stage || 40, + stageTrackerIcon: (kind, cls) => ``, + stageTrackerPRRef: (n, url) => `#${n}`, + stageTrackerPRPillsHtml: ref => ref, + stageTrackerTitleHtml: text => `${esc(text)}`, + stageTrackerTooltip: it => it.caption || '', + stageTrackerLinkedTip: () => '', + stageTrackerActedBadgeHtml: () => '', stageTrackerRowToolsHtml: () => '', + stageTrackerChipsHtml: () => '', stageTrackerMoveAttrs: () => '', stageTrackerSinceHtml: () => '', + stageTrackerStripItems: it => `
  • `, + stageTrackerCurrentStageHtml: it => `

    ${esc((STAGES.find(s => s.number === Number(it.stage)) || {}).short || it.stage)}

    `, + stageTrackerActionCtx: () => ({ user: 'viewer' }), + stageTrackerLeadActionOnRow: () => null, + }); + vm.runInContext(fn('tracker-words-stage', 'stageTrackerStageName'), c); + for (const name of ['stageTrackerLinkedSuperseder', 'stageTrackerLinkedSupersededGone', 'stageTrackerLinkedSupersededText', 'stageTrackerLinkedSupersededTip']) vm.runInContext(fn('tracker-words-gate', name), c); + for (const name of ['stageTrackerItemKey', 'stageTrackerPRKey', 'stageTrackerRowPRKeys']) vm.runInContext(fn('tracker-merged', name), c); + for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml']) vm.runInContext(fn('tracker-row-layout', name), c); + vm.runInContext(fn('tracker-row-render', 'stageTrackerRowHtml'), c); + vm.runInContext(fn('tracker-filter', 'stageTrackerPRIssueSlot'), c); + vm.runInContext(source('tracker-motion'), c); + vm.runInContext(source('tracker-human-attention'), c); + // Row chrome outside the note line is not under test. + vm.runInContext('stageTrackerCueClasses = () => ""; stageTrackerCueLineHtml = () => "";', c); + return c; +} +const NOW = 1_700_000_000_000; +const lines = html => html.match(/

    ]*>[\s\S]*?<\/p>/g) || []; +const ages = html => (html.match(/cue-event-age" data-at="(\d+)"/g) || []).length; + +// The screenshot: the reviewer's ask on the row plus the stage note that +// landed 3 min earlier, under a strip lit at Needs human decision. +function screenshotRow() { + const pr = { kind: 'pr', repo: 'hivecommons/hive', number: 16619, stage: 85, state: 'open', head: 'h16619', + url: 'https://github.com/hivecommons/hive/pull/16619', title: 'fix', base_ref: 'v5', + human_attention: { kind: 'pr', number: 16619, head: 'h16619', asked_by: 'a reviewer', + reason: '@clubanderson should decide whether #16619 or your own #16622 lands for #16617 — both close the same issue' }, + stage_actor: { kind: 'human', login: 'clubanderson', why: 'decide which PR lands' } }; + const item = { kind: 'issue', repo: 'hivecommons/hive', number: 16617, stage: 85, mirrored: true, linked_pr: 16619, + title: 'Fleet relaunch', linked_prs: [pr], url: 'https://github.com/hivecommons/hive/issues/16617', stage_actor: pr.stage_actor }; + const events = { 'hivecommons/hive/issue#16617': { who: 'hive', text: 'moved to Needs human decision', at: NOW - 180000, openAt: NOW - 180000 } }; + return { item, events }; +} + +test('needs-human ask + stage note → one line, the chevron restatement dropped, View PR and one age kept', () => { + const c = load(), { item, events } = screenshotRow(); + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + const line = found[0]; + assert.match(line, /ham-human-context/); + assert.match(line, /cue-event-ico/, 'keeps its ⬡ icon'); + assert.match(line, /Needs human: @clubanderson should decide whether #16619 or your own #16622 lands for #16617/); + assert.match(line, /· requested by a reviewer ]*>View PR #16619<\/a>/); + assert.doesNotMatch(line, /moved to Needs human decision/, 'the lit chevron already reads Needs human decision'); + assert.doesNotMatch(html, /cue-event-who/, 'no second "Hive:" line'); + assert.equal(ages(line), 1, 'one relative timestamp'); +}); + +test('a stage note that says more than the chevron rides the human line as a trailing clause', () => { + const c = load(), { item, events } = screenshotRow(); + events['hivecommons/hive/issue#16617'].text = 'fell back to Needs human decision — reviewers split on the approach'; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1); + assert.match(found[0], /View PR #16619<\/a> · fell back to Needs human decision — reviewers split on the approach/); + assert.equal(ages(found[0]), 1); +}); + +test('a row with only a stage note still shows exactly one line, the hive note itself', () => { + const c = load(); + const item = { kind: 'issue', repo: 'hivecommons/hive', number: 16630, stage: 50, title: 'solo', state: 'open', + url: 'https://github.com/hivecommons/hive/issues/16630', linked_prs: [], stage_actor: { kind: 'hive' } }; + const events = { 'hivecommons/hive/issue#16630': { who: 'hive', text: 'moved to CI / Review', at: NOW - 5000 } }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + assert.match(found[0], /cue-event-who">Hive:<\/span> moved to CI \/ Review/); + assert.doesNotMatch(html, /ham-human-context/); +}); + +test('remediation next move + stage note → one line with the move first and the note folded', () => { + const c = load(); + const item = { kind: 'pr', repo: 'hivecommons/hive', number: 16640, stage: 50, state: 'open', head: 'h', title: 'pr', + url: 'https://github.com/hivecommons/hive/pull/16640', base_ref: 'v5', + stage_actor: { kind: 'human', login: 'author', why: '@author must push a fix; the hive does not edit a person’s PR' } }; + const events = { 'hivecommons/hive/pr#16640': { who: 'hive', text: 'needs a rebase', at: NOW - 60000 } }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + assert.match(found[0], /Next move: @author — @author must push a fix; the hive does not edit a person’s PR · needs a rebase/); + assert.doesNotMatch(html, /cue-event-who/); + assert.equal(ages(found[0]), 1); +}); + +test('PR sub-rows under an issue follow the same one-line rule', () => { + const c = load(), { item, events } = screenshotRow(); + // Two covering PRs: the asking one is drawn as a sub-row with its own note. + const other = { kind: 'pr', repo: 'hivecommons/hive', number: 16622, stage: 50, state: 'open', head: 'h2', title: 'mine', + url: 'https://github.com/hivecommons/hive/pull/16622', base_ref: 'v5', stage_actor: { kind: 'hive' } }; + item.linked_prs.push(other); item.mirrored = false; item.stage = 40; + events['hivecommons/hive/pr#16619'] = { who: 'hive', text: 'moved to Needs human decision', at: NOW - 180000 }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const sub = html.slice(html.indexOf('data-ham-sub-key="hivecommons/hive/pr#16619"'), html.indexOf('data-ham-sub-key="hivecommons/hive/pr#16622"')); + const found = lines(sub); + assert.equal(found.length, 1, sub); + assert.match(found[0], /Needs human: @clubanderson should decide/); + assert.doesNotMatch(found[0], /moved to Needs human decision/); +}); + +test('stage-note fold rules: restatements of the line or the lit chevron are dropped, new facts kept', () => { + const c = load(); + const item = { kind: 'pr', number: 1, repo: 'r', stage: 85 }; + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision', 'Needs human: x', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('waiting on a decision', 'PR #1 — Needs human: x', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('Confirm the policy', 'Needs human: Confirm the policy', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('moved to CI / Review', 'Needs human: x', item, STAGES), 'moved to CI / Review'); + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision — why', 'Needs human: x', item, STAGES), 'moved to Needs human decision — why'); + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision', 'Needs human: x', { kind: 'pr', number: 1, repo: 'r', stage: 85 }, []), 'moved to Needs human decision', 'no stage table: keep it'); +}); diff --git a/src/pkg/dashboard/stage_tracker_status_collection_test.go b/src/pkg/dashboard/stage_tracker_status_collection_test.go index fa8d775336..1c8daa6229 100644 --- a/src/pkg/dashboard/stage_tracker_status_collection_test.go +++ b/src/pkg/dashboard/stage_tracker_status_collection_test.go @@ -18,6 +18,9 @@ import ( func TestStageTrackerRESTCheckPaginationMustCompleteBeforeProjection(t *testing.T) { for _, mode := range []string{"complete", "partial", "malformed"} { t.Run(mode, func(t *testing.T) { + // Each mode observes the same head; the shared per-head CI + // evidence store must not carry one mode's listing into the next. + t.Cleanup(github.ResetCIEvidenceForTest(nil)) reads := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { diff --git a/src/pkg/dashboard/stage_tracker_test.go b/src/pkg/dashboard/stage_tracker_test.go index 49836794a6..82c0106454 100644 --- a/src/pkg/dashboard/stage_tracker_test.go +++ b/src/pkg/dashboard/stage_tracker_test.go @@ -95,13 +95,19 @@ func TestStageTrackerStagesFallsTo(t *testing.T) { // returned-to-contributor (clanker) are both review-side detours with their // own chevron word and an author-must-act caption. func TestStageTrackerNeedsAuthorAndReturnedWords(t *testing.T) { + for _, stage := range stageTrackerStages(nil) { + if stage.Number == stagelabels.Fixing.Number() && + (stage.Label != stagelabels.Fixing.Label() || stage.Short != "Remediating" || stage.Description != "CI failed or review changes requested; remediation needed") { + t.Fatalf("remediation display wording changed the native identity or lost its waiting-safe description: %+v", stage) + } + } for _, tc := range []struct { stage stagelabels.Stage word, captionHead string }{ {stagelabels.NeedsAuthor, "Needs author", "Needs @sam"}, {stagelabels.ReturnedToContributor, "Returned to contributor", "Returned to @sam"}, - {stagelabels.Fixing, "Fixing", "Red or changes requested; a hive agent is fixing it"}, + {stagelabels.Fixing, "Remediating", "CI failed or review changes requested; remediation needed"}, } { if got := stageTrackerShort(tc.stage); got != tc.word { t.Errorf("%v: short = %q, want %q", tc.stage, got, tc.word) diff --git a/src/pkg/dashboard/stage_tracker_tracking_test.go b/src/pkg/dashboard/stage_tracker_tracking_test.go new file mode 100644 index 0000000000..9a7ab2f305 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_tracking_test.go @@ -0,0 +1,97 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#16481: a decomposed parent at 010 whose reason carries +// the engine's "waiting on N open child issue(s)" suffix is tracking its +// children, not waiting on the scanner; the row must say so. + +func TestReasonOpenChildren(t *testing.T) { + cases := map[string]int{ + "actionable; waiting on 1 open child issue(s)": 1, + "open PR addresses part of it (references it without a closing keyword; PR at 050-review-pending); waiting on 2 open child issue(s)": 2, + "actionable": 0, + "": 0, + "actionable; waiting on x open child issue(s)": 0, + } + for reason, want := range cases { + if got := stageengine.ReasonOpenChildren(reason); got != want { + t.Errorf("ReasonOpenChildren(%q) = %d, want %d", reason, got, want) + } + } +} + +func TestStageTrackerTrackingParentIsNotWaitingOnScanner(t *testing.T) { + now := time.Date(2026, 11, 3, 23, 0, 0, 0, time.UTC) + stage := stagelabels.Actionable + it := StageTrackerItem{Kind: "issue", Number: 16242, Stage: stage.Number(), IsTracker: true, + Children: &github.IssueChildren{Total: 4, Completed: 3}, + Reason: "actionable; waiting on 1 open child issue(s)"} + it.Caption, it.Actor = stageTrackerCaption(stage, it.Reason, "hanthor", it.Kind, false, stagelabels.Record{}, false, 0, "") + stageTrackerApplyTracking(&it, stage) + if it.OpenChildren != 1 { + t.Fatalf("OpenChildren = %d, want 1", it.OpenChildren) + } + if !strings.HasPrefix(it.Caption, "Tracking — 3 of 4 children done; waiting on 1 open child issue(s)") || strings.Contains(it.Caption, "scanner to pick it up") { + t.Fatalf("caption still blames the scanner: %q", it.Caption) + } + if it.Actor != stageTrackerTrackingActor { + t.Fatalf("actor = %q, want %q", it.Actor, stageTrackerTrackingActor) + } + it.StageActor = stageTrackerStageActor(it, nil, now) + if it.StageActor.Kind != StageActorNone || !strings.Contains(it.StageActor.Why, "1 open child issue(s)") || strings.Contains(it.StageActor.Why, "pick it up") { + t.Fatalf("stage actor still waits on the scanner: %+v", it.StageActor) + } + + // No children known: the caption still counts the open ones. + only := StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable; waiting on 2 open child issue(s)"} + stageTrackerApplyTracking(&only, stage) + if only.OpenChildren != 2 || !strings.HasPrefix(only.Caption, "Tracking; waiting on 2 open child issue(s)") { + t.Fatalf("count-only parent: %+v", only) + } + + // A plain 010 issue, a PR, and a 040 parent are untouched. + for _, keep := range []struct { + it StageTrackerItem + stage stagelabels.Stage + }{ + {StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable", Caption: "c", Actor: "scanner"}, stage}, + {StageTrackerItem{Kind: "pr", Stage: stage.Number(), Reason: "actionable; waiting on 1 open child issue(s)", Caption: "c", Actor: "scanner"}, stage}, + {StageTrackerItem{Kind: "issue", Stage: 40, Reason: "open PR covers it; waiting on 1 open child issue(s)", Caption: "c", Actor: "its PR"}, stagelabels.CoveredByPR}, + } { + before := keep.it + stageTrackerApplyTracking(&keep.it, keep.stage) + if keep.it.OpenChildren != 0 || keep.it.Caption != before.Caption || keep.it.Actor != before.Actor { + t.Fatalf("row rewritten that should not be: before %+v after %+v", before, keep.it) + } + } + plain := StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable"} + if a := stageTrackerStageActor(plain, nil, now); a.Kind != StageActorHive || !strings.Contains(a.Why, "scanner") { + t.Fatalf("plain 010 issue lost its scanner actor: %+v", a) + } +} + +func TestStageTrackerTrackingWordJS(t *testing.T) { + html := indexHTML(t) + if !strings.Contains(html, `stageTrackerTrackingWord(item)`) { + t.Fatal("tracker-row.js does not consult stageTrackerTrackingWord for the lit 010 chevron") + } + runStageTrackerRowActionsScript(t, `const assert = require('assert'); +`+jsConstLine(t, html, "STAGE_TRACKER_TRACKING_WORD")+"\n"+ + jsFunc(t, html, "stageTrackerTrackingWord")+` +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 1, children: { total: 4, completed: 3 } }), 'Tracking · 3/4'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 1 }), 'Tracking · 1 open child'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 2 }), 'Tracking · 2 open children'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, is_tracker: true, children: { total: 6, completed: 0 } }), ''); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'pr', stage: 10, open_children: 1 }), ''); +assert.strictEqual(stageTrackerTrackingWord(null), ''); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index 26726a5cd7..125ad74733 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -97,6 +97,20 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerTrainIconHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), + jsFunc(t, html, "stageTrackerHiveOwnsRepair"), + jsConstLine(t, html, "STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER"), + jsConstLine(t, html, "STAGE_TRACKER_WORKFLOW_APPROVAL_TIP"), + jsFunc(t, html, "stageTrackerWorkflowApprovalPending"), + jsConstLine(t, html, "STAGE_TRACKER_RING_SEGMENT_GAP_MAX"), + jsConstLine(t, html, "STAGE_TRACKER_RING_RADIUS"), + jsConstLine(t, html, "STAGE_TRACKER_RING_GAP_DEG"), + jsFunc(t, html, "stageTrackerRingSvg"), + jsFunc(t, html, "stageTrackerStalledTrack"), + jsFunc(t, html, "stageTrackerQueueAheadWord"), + jsFunc(t, html, "stageTrackerStageTrack"), + jsFunc(t, html, "stageTrackerTrackWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), @@ -110,6 +124,14 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerHopName"), jsFunc(t, html, "stageTrackerTrailText"), jsFunc(t, html, "stageTrackerTooltip"), + jsConstLine(t, html, "STAGE_TRACKER_BLOCKED_WORD"), + jsFunc(t, html, "stageTrackerBlockerWord"), + jsConstBlock(t, html, "STAGE_TRACKER_NEEDS_HUMAN_SHORT"), + jsConstLine(t, html, "STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX"), + jsConstLine(t, html, "STAGE_TRACKER_NEEDS_HUMAN_WORD"), + jsFunc(t, html, "stageTrackerNeedsHumanShort"), + jsFunc(t, html, "stageTrackerNeedsHumanWord"), + jsFunc(t, html, "stageTrackerBlockedForDecisionPR"), jsFunc(t, html, "stageTrackerChipsHtml"), jsFunc(t, html, "stageTrackerHeadColsHtml"), jsFunc(t, html, "stageTrackerSinceHtml"), @@ -197,8 +219,28 @@ var _stageTracker = { stages }; // needs-rebase always lands a PR in 070/071/072 (automerge_stage_labels.go), so a // fixture pairing it with 050/060 would draw a contradictory row. const rebaseCoherent = (it) => { if ((it.modifiers || []).includes('needs-rebase')) assert.ok(![50, 60].includes(Number(it.stage)), 'fixture #' + it.number + ' pairs needs-rebase with stage ' + it.stage); (it.linked_prs || []).forEach(rebaseCoherent); }; +// hivecommons/hive#16540: no strip ever lights more than two chevrons. Lit = +// the stage chevron's active fill (a settled-current one is not amber) or a +// CI / Review track in the active class. Checked on every fixture rendered. +const litChevrons = (html) => (html.match(/class="ham-seg active(?! [^"]*ham-settled-current)|class="ham-seg ham-activity-track active\b/g) || []).length; +// hivecommons/hive#16599 (canonical): 1 ≤ active ≤ 2 — the stage column is +// always active (a settled-current one counts as filled), a track only while +// it runs or is the stage's own / stalled track; and words ride ONLY active +// chevrons — an inactive CI / Review track is its icon alone. +const filledChevrons = (html) => litChevrons(html) + (html.match(/class="ham-seg active [^"]*ham-settled-current/g) || []).length; +const trackCopyText = (li) => ((/([\s\S]*?)<\/span>(?:/g, '').replace(/<[^>]+>/g, '').trim(); +const wordsOnlyWhenActive = (item, s) => Array.from(s.matchAll(/

  • /g)).forEach(m => { + const words = trackCopyText(m[0]); + if (/\bactive\b/.test(m[1])) assert.ok(words, 'fixture #' + item.number + ' active track without words: ' + m[0]); + else assert.strictEqual(words, '', 'fixture #' + item.number + ' inactive track carries words: ' + m[0]); +}); +const atMostTwoLit = (item, row) => row.split('aria-label="Pipeline progress"').slice(1).forEach((s, i) => { + assert.ok(litChevrons(s) <= 2, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' lights ' + litChevrons(s) + ' chevrons: ' + s); + if (s.includes('aria-current="step"')) assert.ok(filledChevrons(s) >= 1, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' has no filled chevron: ' + s); + wordsOnlyWhenActive(item, s); +}); const rawRowHtml = stageTrackerRowHtml; -stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); return rawRowHtml(item, stages, ctx); }; +stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); const row = rawRowHtml(item, stages, ctx); atMostTwoLit(item, row); return row; }; // A row is a title line, its strip, then zero or more nested PR sub-rows. const strips = (row) => row.split('aria-label="Pipeline progress"').slice(1); const strip = (row) => strips(row)[0].split('
    Array.from(strip(html).matchAll(/
  • ]*>(.*?)<\/a>/g)).map(m => m[1]); const B = 'blank'; -const text = (h) => h.replace(/<[^>]+>/g, '').replace(/'/g, "'").replace(/\s+/g, ' ').trim(); +const visibleMarkup = (h) => h.replace(/]*class="config-tooltip ham-chevron-tip"[^>]*>[^<]*<\/span>/g, ''); +const text = (h) => visibleMarkup(h).replace(/<[^>]+>/g, '').replace(/'/g, "'").replace(/\s+/g, ' ').trim(); // The row tooltip rides the issue's #N link on an issue row and the PR link // (after "PR title · ") on a PR row; the issue slot of a PR row carries none. const tooltip = (row) => (/]*title="([^"]*)"/.exec(row) || /]*title="([^"]*)"/.exec(row))[1]; diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index e5e84828b0..8a297d0ff5 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -29,13 +29,15 @@ assert.ok(row.includes('30m'), row); // The age and the chip belong to the strip they describe, not to a title line // that may wrap: the since text closes the strip row (an empty spacer keeps // the title line's width) and the chip is the last thing in the title line's -// ghost strip, right above the strip's cap. +// ghost strip — trailing the PR cell (ham-head-tools when there is no PR), +// right-anchored on the title line, never a toolbar line of its own. assert.ok(row.indexOf('30m') > row.indexOf('aria-label="Pipeline progress"'), 'since sits on the strip row, in line with the chevrons'); assert.ok(/aria-label="Pipeline progress">[\s\S]*?<\/ol>\s*30m<\/span>\s*<\/div>/.test(row), 'the strip row ends with the since cell'); -assert.ok(/
  • [\s\S]*?<\/span><\/li><\/ol><\/span><\/div>\s*<\/div>\s*
    /.test(row), 'the chip cell closes the title line, directly above its own strip row'); +assert.ok(/
  • [\s\S]*?<\/span><\/li><\/ol><\/span><\/div>\s*<\/div>\s*
    /.test(row), 'the chip cell closes the title line, directly above its own strip row'); +assert.ok(!row.includes('
  • '), 'no separate toolbar line between the title and the chevrons'); assert.ok(row.indexOf('
    ') < row.indexOf('ham-badges') && row.indexOf('ham-badges') < row.indexOf('aria-label="Pipeline progress"'), 'chip and strip share one row container'); assert.ok(row.includes('ham-kind-ico'), 'kind icon'); -assert.strictEqual((strip(row).match(/triage needed'), row); -assert.ok(/aria-current="step">]*>[\s\S]*?<\/svg>Open<\/span><\/li>/.test(row), row); +assert.ok(/aria-current="step">]*>]*>[\s\S]*?<\/svg>Open<\/span><\/span>/.test(row), row); assert.ok(tooltip(row).startsWith('Open No stage recorded yet') && tooltip(row).includes('Flags: triage needed'), tooltip(row)); // 015 triage-needed: the Actionable column lights (not a detour) with the @@ -75,7 +77,7 @@ assert.ok(tooltip(row).startsWith('Open No stage recorded yet') && tooltip(row). // chevron tooltip name the stage; the server already dropped the chip. row = stageTrackerRowHtml({ repo: 'acme/console', number: 13262, kind: 'issue', title: 'Review backlog (security)', stage: 15, author: 'hive-bot', author_kind: 'hive', caption: 'Actionable, but no maintainer has looked at it yet; waiting for triage' }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, 'active', T, T, T, T, 'todo cap'], '015 lights the Actionable column: ' + row); -assert.ok(/aria-current="step">]*>[\s\S]*?<\/svg>Triage needed<\/span>]*>]*>[\s\S]*?<\/svg>Triage needed<\/span><\/span>]*>[\s\S]*?<\/svg>Actionable<\/span><\/li>/.test(row), row); +assert.ok(/aria-current="step">]*>]*>[\s\S]*?<\/svg>Actionable<\/span><\/span>/.test(row), row); // Plain Open (no stage label, not held) says how long it has sat there, from // the same instant the since column draws (stage_since), with the ISO time on @@ -212,7 +214,7 @@ assert.ok(!stageTrackerRowHtml({ repo: 'acme/console', number: 30, kind: 'pr', t // With the PR's stage known the issue strip rides it (merge queue → Merge gate lit, hive move). row = stageTrackerRowHtml({ repo: 'acme/console', number: 8, kind: 'issue', stage: 40, linked_prs: [{ number: 102, title: 'Fix it', author_kind: 'human', author: 'bob', stage: 100, stage_since: new Date(now - 7200000).toISOString(), modifiers: ['stalled'], caption: 'Admitted, merging' }] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, D, D, 'active', 'todo cap']); -assert.ok(row.includes('MergingMergingstalled') && row.includes('2h'), 'chips + since come from the covering PR: ' + row); assert.ok(tooltip(row).includes('Admitted, merging') && tooltip(row).includes('Covering PR: #102'), tooltip(row)); assert.ok(prCol(row)[0].includes('ham-author-human') && prCol(row)[0].includes('Fix it'), prCol(row)[0]); @@ -334,7 +336,7 @@ assert.ok(row.includes('Review unknown') && row.includes('CI unknown'), 'legacy // 071 needs-author: the owner wait returns to PR in progress without pretending coding. row = stageTrackerRowHtml({ repo: 'acme/console', number: 109, kind: 'pr', stage: 71, author: 'sam', author_kind: 'human', history: [{number:50,slug:'review-pending'},{number:71,slug:'needs-author',from:50}] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, 'active detoured', T, T, 'todo cap']); -assert.ok(row.includes('aria-label="Next move: human"') && row.includes('Needs @samNeeds @samPR in progressPR in progressPR in progressPR in progressClaimedClaimedClaimed'), 'no claimant known, no icon: ' + row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', stage: 10 }, stages, ctx); assert.ok(!row.includes('ham-actor-ico') && !tooltip(row).includes('Next move'), row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 105, kind: 'pr', stage: 90 }, stages, ctx); -assert.ok(row.includes('aria-label="Next move: human"') && row.includes('Ready for human mergeReady for human mergeFix it'), prCol(sr[0])[0]); assert.deepStrictEqual(segStates(sr[0]), [B, B, B, D, 'active detoured', T, 'todo cap'], 'PR strip starts at PR in progress'); assert.ok(sr[0].includes('Waiting for fixer') && !sr[0].includes('ham-actor-ico') && sr[0].indexOf('1h') > sr[0].indexOf('aria-label="Pipeline progress"') && sr[0].includes('ham-mod-needs-rebase">needs rebase'), 'a rebase label and next mover cannot manufacture observed coding: ' + sr[0]); -assert.ok(/^ data-ham-kind="pr" data-ham-stage="70" data-ham-sub-key="acme\/console\/pr#102">/.test(sr[0]) && /]*title="Fix it · Fixing review findings Rebasing onto main/.test(sr[0]), 'sub-row tooltip rides the PR link, not the container: ' + sr[0].slice(0, 400)); +assert.ok(/^ data-ham-kind="pr" data-ham-stage="70" data-ham-sub-key="acme\/console\/pr#102">/.test(sr[0]) && /]*title="Fix it · Remediating CI or review findings Rebasing onto main/.test(sr[0]), 'sub-row tooltip rides the PR link, not the container: ' + sr[0].slice(0, 400)); assert.ok(prCol(sr[1])[0].includes('ham-author-clanker') && prCol(sr[1])[0].includes('#103')); assert.deepStrictEqual(segStates(sr[1]), [B, B, B, 'active', T, T, 'todo cap'], 'a PR at 030 lights PR in progress on its own sub-row'); assert.ok(!row.slice(0, row.indexOf('
  • '), 'the lineage chip rides the PR cell, not the chip cap: ' + head); + assert.ok(!head.includes('ham-lineage" title') || head.indexOf('ham-lineage') < head.indexOf(''), 'the lineage chip rides the PR cell ahead of the modifier chips, not the chip toolbar: ' + head); assert.strictEqual((head.match(/ham-lineage/g) || []).length, 1, 'the lineage chip is drawn once'); } // The same order on an issue row with a single covering PR: lineage chip @@ -520,7 +522,7 @@ assert.deepStrictEqual(segStates(subs(row)[0]), [B, B, B, D, D, D, 'active cap m // Title line: lead cell (Open..Claimed) and PR cell (PR in progress..Merge gate) each truncate with an ellipsis; the full title is on the element itself. row = stageTrackerRowHtml({ repo: 'acme/console', number: 12, kind: 'issue', title: 'A very long issue title that must not wrap', stage: 10 }, stages, ctx); // No PR to list: the lead cell widens over the empty PR column so a long title has room before it truncates. -assert.ok(/
  • <\/span><\/li>/.test(row), row); +assert.ok(/
  • <\/span><\/li>/.test(row), row); // Sort key: a covered issue counts as far along as its furthest PR. assert.strictEqual(stageTrackerSortKey({ kind: 'issue', stage: 40, linked_prs: [{ number: 1, stage: 30 }, { number: 2, stage: 90 }] }, stages).anchor, 80); // An issue parked on 045 (or a pre-045 085) with no PR sorts at Actionable, not past the merge gate. @@ -555,7 +557,7 @@ for (const [st, word, actor] of [[50, 'CI / Review', 'hive'], [60, 'Review passe assert.ok(r.includes('CI unknown') && r.includes('Review unknown'), 'legacy labels alone cannot supply activity at ' + st); continue; } - const m = /aria-current="step">]*>[\s\S]*?<\/svg>([^<]*)<\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); + const m = /aria-current="step">]*>]*>[\s\S]*?<\/svg>([^<]*)<\/span><\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); assert.ok(m, 'stage ' + st + ' has no active word + actor: ' + r); assert.deepStrictEqual([m[1], m[2]], [word, actor === 'author' ? 'clanker' : actor], 'stage ' + st); prWords[st] = m[1]; @@ -606,12 +608,28 @@ assert.deepStrictEqual(stageTrackerVisible(g, { kind: 'issue', repo: '' }).map(i assert.deepStrictEqual(stageTrackerVisible(g, { kind: 'pr', repo: '' }).map(it => it.number), [21, 31, 32, 40], 'Pull requests filter flattens every PR once'); // Hover text budget per row (owner request): only the #N link, the PR link, -// the item title and the active chevron carry title="…". The row container, +// the item title and the active chevron carry nonempty title="…". The row container, // sub-row container, kind / author / actor icons, chips, since cells and // every non-active chevron carry none; icons expose their label via aria-label. +// Accessible chevron wrappers use title="" only to suppress inherited native +// hover text while the shared portal exposes their full details. const tags = (html) => Array.from(html.matchAll(/<(\w+)\b([^>]*)>/g)).map(m => ({ tag: m[1], attrs: m[2] })); -const titled = (html) => tags(html).filter(t => / title="/.test(t.attrs) && !t.attrs.includes('data-track=')); -const expectTitles = (html, want, what) => assert.deepStrictEqual(titled(html).map(t => t.tag + '.' + ((/class="([^" ]+)/.exec(t.attrs) || [])[1] || '')), want, what + ': ' + html); +const titleAttribute = (tag) => (/(?:^|\s)title="([^"]*)"/.exec(tag.attrs) || [])[1]; +const chevronHelp = (tag) => tag.tag === 'span' && /(?:^|\s)class="ham-chevron-info config-info"/.test(tag.attrs); +const titled = (html) => tags(html).filter(t => titleAttribute(t) !== undefined && !t.attrs.includes('data-track=') && + !(chevronHelp(t) && titleAttribute(t) === '')); +const expectTitles = (html, want, what) => { + for (const tag of tags(html).filter(chevronHelp)) { + assert.strictEqual(titleAttribute(tag), '', what + ': portal wrapper must suppress inherited native hover text'); + assert.match(tag.attrs, /(?:^|\s)tabindex="0"/, what + ': full details remain keyboard reachable'); + assert.match(tag.attrs, /(?:^|\s)aria-label="[^"]+"/, what + ': full accessible caption remains'); + assert.match(tag.attrs, /(?:^|\s)aria-describedby="ham-(?:chevron|track)-tip-[^"]+"/, what + ': shared tooltip stays associated'); + } + assert.deepStrictEqual(titled(html).map(t => t.tag + '.' + ((/class="([^" ]+)/.exec(t.attrs) || [])[1] || '')), want, what + ': ' + html); +}; +assert.strictEqual(titled('').length, 0, 'only the exact empty portal suppressor is exempt'); +assert.strictEqual(titled('').length, 1, 'nonempty wrapper titles still violate the exact hover budget'); +assert.strictEqual(titled('
  • ').length, 2, 'unrelated title-bearing extras are never whitelisted'); assert.ok(!/]*>\s*/.test(golden), 'no svg <title> tooltips anywhere in the tracker'); assert.ok(!/<(div|span)[^>]*class="ham-(row|sub|since|badge|kind-ico)[^>]*title="/.test(golden), 'containers, since cells, chips and kind icons carry no title'); for (const r of golden.split('<div class="ham-row"').slice(1)) { @@ -652,6 +670,141 @@ assert.ok(/<a class="ham-pr-ref"[^>]*title="Standalone PR · Not yet admitted to assert.ok(row.includes('aria-label="human · @cy"') && !row.includes('<title>'), 'author icon label is aria-only: ' + row); // Since cells are untouched: plain text, no title. assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ham-since[^>]*title=/.test(golden), 'since cells unchanged'); +// hive#16509 row: adopted by hive with a finished review (5/5, human +// decision asked). The Review track is done-style and muted — never the amber +// in-progress fill — and reads the verdict, not "awaiting human decision"; +// 11/11 passed CI is done-style too. +{ + const seen = new Date(now - 60000).toISOString(); + const adoptedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16509, kind: 'pr', stage: 74, display_column: 30, head: 'f269349', author: 'thatguywob', author_kind: 'human', + code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive · activity', source: 'adoption', observed_at: seen }, + ci_activity: { head: 'f269349', state: 'passing', caption: 'CI 11/11 passed', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + const review = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="review"[^>]*>[\s\S]*?<\/li>/.exec(adoptedRow); + assert.ok(review, 'review track present: ' + adoptedRow); + assert.strictEqual(review[1], 'done decided', 'a finished review back in PR in progress is settled, not amber: ' + review[0]); + assert.ok(review[0].includes('Review: Review 5/5 · changes requested · ') && !review[0].includes('awaiting human') && !review[0].includes('data-motion=') && review[0].includes('ham-ring-decided'), 'the verdict rides the tooltip; the inactive track is its ring alone: ' + review[0]); + const ci = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="ci"/.exec(adoptedRow); + assert.strictEqual(ci[1], 'done', '11/11 passed is done-style: ' + adoptedRow); + const parkedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16510, kind: 'pr', stage: 85, display_column: 85, head: 'f269349', needs_human: true, author: 'thatguywob', author_kind: 'human', + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*title="Review: Review 5\/5 · needs owner sign-off · /.test(parkedRow), 'genuinely parked on a person names the sign-off in the tooltip, still not amber: ' + parkedRow); +} +// hivecommons/hive#16540 rows. #16509: adopted, CI 7/11 unreported, review +// decided → one lit chevron. #16268: waiting for the contributor, CI 7/11 +// unreported, review approved → exactly one. Three qualifying (fix running, +// CI running, review running) → the tracks win and the stage chevron is +// settled-current. The ≤2 invariant itself runs on every fixture above. +{ + const seen = new Date(now - 60000).toISOString(); + const unreported = { head: 'f269349', state: 'missing', caption: 'CI waiting · required check "test" hasn\'t reported for this head yet', checks_passed: 7, checks_total: 11, blocker: 'test', source: 'checks', observed_at: seen }; + const lit = (html) => litChevrons(strip(html)); + const three = stageTrackerRowHtml({ repo: 'acme/console', number: 16509, kind: 'pr', stage: 74, display_column: 30, head: 'f269349', author: 'thatguywob', author_kind: 'human', + code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive · activity', source: 'adoption', observed_at: seen }, ci_activity: unreported, + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(three), 1, 'adopted + unreported CI + decided review lights one chevron: ' + strip(three)); + assert.ok(/<li class="ham-seg ham-activity-track todo" data-track="ci"[^>]*title="CI: CI 7\/11 · test not reported · /.test(three), 'unreported checks are the neutral icon, words in the tooltip: ' + three); + const owner = stageTrackerRowHtml({ repo: 'acme/console', number: 16268, kind: 'pr', stage: 71, display_column: 30, head: 'f269349', author: 'hanthor', author_kind: 'human', + code_activity: { head: 'f269349', state: 'waiting_owner', caption: 'Waiting for @hanthor · not observed coding', actor: 'hanthor', source: 'native-author-wait', observed_at: seen }, ci_activity: unreported, + review_activity: { head: 'f269349', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(owner), 1, 'with the contributor: only the stage chevron is lit: ' + strip(owner)); + assert.ok(/<li class="ham-seg active detoured"[^>]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); + assert.ok(/<li class="ham-seg ham-activity-track todo" data-track="ci"[^>]*title="CI: CI 7\/11 · test not reported · /.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved · /.test(owner), 'with the contributor both tracks are icons alone, words in the tooltips: ' + owner); + const busy = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', + code_activity: { head: 'f269349', state: 'remediating', caption: 'Remediating · scanner · 4m', actor: 'scanner', active: true, source: 'fix-dispatch', observed_at: seen }, + ci_activity: { head: 'f269349', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'reviewing', active: true, actor: 'reviewer-2', caption: 'Review working', perspectives_done: 2, perspectives_total: 5, source: 'dispatch', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(busy), 2, 'three qualify, two light: ' + strip(busy)); + // #16456: back in PR in progress with changes requested — one filled + // chevron; CI 11/11 is green words (done), the review finding red words + // (failing), neither a fill. + const changes = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', + code_activity: { head: 'f269349', state: 'unassigned', caption: 'Changes requested · unassigned · next: scanner', source: 'no-pickup-evidence', since: seen, observed_at: seen }, + ci_activity: { head: 'f269349', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'changes_requested', caption: 'Review findings · changes requested', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }, stages, ctx); + assert.strictEqual(lit(changes), 1, 'changes requested in PR in progress: one filled chevron: ' + strip(changes)); + assert.ok(/<li class="ham-seg ham-activity-track done" data-track="ci"[^>]*data-verdict="pass"[^>]*>[\s\S]*?CI: CI 11\/11 passed · /.test(changes) && /<li class="ham-seg ham-activity-track failing" data-track="review"[^>]*data-verdict="fail"[^>]*>[\s\S]*?Review: Review 5\/5 · changes requested · /.test(changes), changes); + assert.ok(!/ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg>(?:CI|Review) /.test(changes), 'settled verdicts carry no words beside the glyph: ' + changes); + assert.ok(/<li class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/.test(busy) && busy.includes('Remediating · scanner · 4m'), 'the stage chevron is settled-current with its words: ' + busy); +} +// hivecommons/hive#16524: 085 under hive:unauthorized (a maintainer must +// rerun shared CI on GitHub), CI unknown, review findings open. The ask is +// the person's move ON THE PR, not a merge matter: the chevron lights PR in +// progress with "Waiting for @clubanderson · rerun shared ci on GitHub" +// and the person icon; the Merge queue column stays empty. A merge-ready +// twin (approved + CI green) or a queued one keeps the gate. +{ + const seen = new Date(now - 60000).toISOString(); + const head = '7879a51'; + const ask = { question: "The hive's GitHub App may not rerun shared ci here. A maintainer has to do that step on GitHub.", asked_by: 'GitHub permissions', since: seen, blocker_reason: 'unauthorized:rerun-shared-ci', options: [{ action: 'decide:delegate', label: 'Let hive decide', enabled: false }] }; + const shape = (extra) => Object.assign({ repo: 'hivecommons/hive', number: 16524, kind: 'pr', stage: 85, head, author: 'clubanderson', author_kind: 'human', modifiers: ['unauthorized'], + reason: 'unauthorized:rerun-shared-ci', unauthorized_step: 'rerun shared ci', unauthorized: "The hive's GitHub App lacks the permission to rerun shared ci, so only a person can take that step.", + caption: 'Waiting for a maintainer · rerun shared ci on GitHub — the hive\'s GitHub App is not permitted to rerun shared ci; a maintainer must', decision_needed: ask, + human_attention: { number: 16524, kind: 'pr', head, reason: ask.question, asked_by: 'GitHub permissions' }, + ci_activity: { head, state: 'unknown', caption: 'CI unknown · no check results observed for this head yet', checks_passed: 34, checks_total: 42, checks_failed: 1, source: 'github-graphql-cache+required-branch', observed_at: seen }, + review_activity: { head, state: 'changes_requested', caption: 'Review findings · awaiting author', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }, extra || {}); + const rerun = stageTrackerRowHtml(shape(), stages, ctx); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', shape()), 30, 'the ask is the person\'s move on the PR: PR in progress'); + assert.deepStrictEqual(segStates(rerun), [D, D, D, 'active detoured', T, T, 'todo cap'], 'PR in progress lit, Merge queue empty: ' + strip(rerun)); + assert.ok(rerun.includes('Waiting for @clubanderson · rerun shared ci on GitHub'), 'the chevron names the person and the step: ' + strip(rerun)); + assert.ok(!/<li class="ham-seg active[^"]*"[^>]*>[\s\S]*?Awaiting human/.test(strip(rerun)), 'no "Awaiting human" chevron: ' + strip(rerun)); + const litSeg = /<li class="ham-seg active detoured"[^>]*>([\s\S]*?)<\/li>/.exec(strip(rerun)); + assert.ok(litSeg && litSeg[1].includes('ham-actor-ico'), 'the person icon stays on the lit chevron: ' + strip(rerun)); + const mergeSeg = Array.from(strip(rerun).matchAll(/<li class="ham-seg ([^"]*)"[^>]*>([\s\S]*?)<\/li>/g)).filter(m => !m[1].includes('ham-activity-track') && !m[1].includes('ham-head'))[4]; + assert.ok(mergeSeg && mergeSeg[1] === 'todo' && !/ham-chevron-copy/.test(mergeSeg[2]), 'the merge-queue chevron carries no words: ' + mergeSeg[0]); + assert.strictEqual(litChevrons(strip(rerun)), 1, 'one lit chevron: ' + strip(rerun)); + // Merge-ready (approved + CI green) or queued twins are merge matters: the gate keeps them. + const ready = shape({ ci_activity: { head, state: 'passing', caption: 'CI green', checks_passed: 42, checks_total: 42, source: 'checks', observed_at: seen }, review_activity: { head, state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', ready), 80, 'merge-ready 085 keeps the gate'); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', shape({ merge_train: { id: 'v5#1', state: 'queued-behind', front: 1, position: 2, size: 2 } })), 80, 'a train member keeps the gate'); + // A bare 085 decision (no track evidence, no step) still decides at the gate (#14821). + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', { kind: 'pr', stage: 85, caption: 'decision requested' }), 80); + // A nested PR under its issue follows the same column. + const nested = stageTrackerRowHtml({ repo: 'hivecommons/hive', number: 16500, kind: 'issue', stage: 40, linked_prs: [shape()] }, stages, ctx); + assert.ok(nested.includes('Waiting for @clubanderson · rerun shared ci on GitHub'), 'nested PR carries the word: ' + nested); +} +// hivecommons/hive#16599 rows (canonical: active = amber + words, inactive = +// icon only). #16567 (dependabot, 050, review approved, 10 workflow runs +// behind GitHub's approve-workflows gate): nothing moves, so the CI column +// is the stalled active track with the person icon and the words "1/11 · +// waiting on workflow approval"; Review is the green ring alone. #427 (050, +// swarm queued, CI passed): Review is the stage's own track, active even +// while queued; CI is the green icon only. CI running + swarm adjudicating +// lights both tracks with words, never a third. +{ + const seen = new Date(now - 60000).toISOString(); + const lit = (html) => litChevrons(strip(html)); + const gated = stageTrackerRowHtml({ repo: 'acme/console', number: 16567, kind: 'pr', stage: 50, display_column: 50, head: 'b9cd4ba', author: 'dependabot[bot]', author_kind: 'bot', + ci_activity: { head: 'b9cd4ba', state: 'missing', caption: 'CI waiting · 10 workflow runs need approval on GitHub', checks_passed: 1, checks_total: 11, blocker: 'workflow-approval-required:10', actor: 'dependabot[bot]', source: 'github-check-runs', observed_at: seen, workflow_approval: { pending: 10 } }, + review_activity: { head: 'b9cd4ba', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(gated), 1, 'the stalled CI column is the one active chevron: ' + strip(gated)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-stalled ham-current" data-track="ci" data-stalled="true"(?![^>]*data-motion)[^>]*>[\s\S]*?CI 1\/11 · waiting on workflow approval<\/span><svg class="ham-ico ham-actor-ico"[^>]*aria-label="Needs a maintainer to approve the workflow runs on GitHub[^"]*"/.test(gated), 'stalled CI is amber-muted, still, names the wait and wears the person icon: ' + gated); + assert.ok(/<svg class="ham-ico ham-ring ham-ring-pass" [^>]*aria-label="CI: CI 1\/11 · waiting on workflow approval" data-ring-total="11" data-ring-done="1" data-ring-failed="0">/.test(gated), 'the CI glyph is the 11-step ring with one step done: ' + gated); + assert.ok(/<li class="ham-seg ham-activity-track done ham-current" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="5"[\s\S]*?<\/svg><\/span><span id=/.test(gated), 'approved review is the green ring alone: ' + gated); + assert.ok(gated.includes('10 workflow runs need approval on GitHub'), 'the tooltip keeps the backend sentence: ' + gated); + const queued = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'unassigned', caption: 'Review queued · unassigned', perspectives_done: 0, perspectives_total: 5, source: 'review-dispatch-wait', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(queued), 1, 'the stage\'s own track is active while queued: ' + strip(queued)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-current" data-track="review"(?![^>]*data-motion)[^>]*>[\s\S]*?Review 0\/5 · queued<\/span>/.test(queued), 'Review 0/5 · queued is amber and steady: ' + queued); + assert.ok(/<li class="ham-seg ham-activity-track done ham-current" data-track="ci"[^>]*data-verdict="pass"[^>]*>[\s\S]*?<svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="11"[\s\S]*?<\/svg><\/span><span id=/.test(queued) && queued.includes('CI: CI 11/11 passed · '), 'passed CI is the green ring, words in the tooltip: ' + queued); + const ahead = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'unassigned', caption: 'Review queued · unassigned', perspectives_done: 0, perspectives_total: 5, queue_ahead: 3, source: 'review-dispatch-wait', observed_at: seen } }, stages, ctx); + assert.ok(ahead.includes('Review 0/5 · queued, 3 ahead</span>'), ahead); + const progress = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'missing', caption: 'CI waiting', checks_passed: 7, checks_total: 11, blocker: 'test', source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'reviewing', active: true, caption: 'Review 2/5 · in progress', perspectives_done: 2, perspectives_total: 5, source: 'verified-review-bundle+stage-review-pending', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(progress), 1, 'review in progress lights the Review column only: ' + strip(progress)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-current" data-track="review"[^>]*data-motion="active"[^>]*>[\s\S]*?Review 2\/5 · in progress<\/span>/.test(progress), progress); + assert.ok(/<li class="ham-seg ham-activity-track todo ham-current" data-track="ci"[^>]*>[\s\S]*?<svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="7"[\s\S]*?<\/svg><\/span><span id=/.test(progress) && progress.includes('CI: CI 7/11 · test not reported · '), 'unreported checks are the neutral ring, words in the tooltip: ' + progress); + assert.ok(/<svg class="ham-ico ham-ring ham-ring-live ham-ring-running" [^>]*data-ring-total="5" data-ring-done="2"/.test(progress) && (progress.match(/ham-ring-pulse/g) || []).length === 1, 'the review ring pulses its next step: ' + progress); + const both = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'adjudicating', active: true, caption: 'Review 5/5 · verdicts in · aggregating', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(both), 2, 'CI running + adjudicating: both tracks, no third: ' + strip(both)); + assert.ok(both.includes('CI 4/11 · running</span>') && both.includes('Review 5/5 · adjudicating</span>'), both); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/<li class="ham-seg active cap merged" title="Merged — [^"]*" aria-current="step">/.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/stage_tracker_unauthorized_test.go b/src/pkg/dashboard/stage_tracker_unauthorized_test.go index b44913ccfc..2fd5d63a1f 100644 --- a/src/pkg/dashboard/stage_tracker_unauthorized_test.go +++ b/src/pkg/dashboard/stage_tracker_unauthorized_test.go @@ -66,7 +66,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { if it.Stage != 85 || !hasMod(it, modUnauthorized) || it.UnauthorizedStep != "approve workflow runs" || !strings.Contains(it.Unauthorized, "`actions: write`") { t.Fatalf("row = stage %d mods %v step %q tip %q", it.Stage, it.Modifiers, it.UnauthorizedStep, it.Unauthorized) } - if !strings.Contains(it.Caption, "not permitted to approve workflow runs") || it.Actor != "maintainer" { + if !strings.HasPrefix(it.Caption, "Waiting for a maintainer · approve workflow runs on GitHub") || !strings.Contains(it.Caption, "not permitted to approve workflow runs") || it.Actor != "maintainer" { t.Fatalf("caption %q actor %q", it.Caption, it.Actor) } raw, err := json.Marshal(it) @@ -82,7 +82,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { } // The frontend: the pill is muted and explains itself on hover, it counts -// under Needs attention, and the 085 chevron reads "Awaiting human: <step>". +// under Needs attention, and the 085 chevron reads "Waiting for @who · <step> on GitHub". func TestStageTrackerUnauthorizedJS(t *testing.T) { html := indexHTML(t) for _, want := range []string{ @@ -129,7 +129,9 @@ assert.ok(stageTrackerNeedsAttention(item)); assert.ok(stageTrackerChipsHtml({ stage: 85, modifiers: ['needs-decision', 'unauthorized'] }).includes('>unauthorized +1<')); assert.ok(stageTrackerChipsHtml({ stage: 10, modifiers: ['unauthorized', 'hold'] }).includes('>hold +1<')); // The 085 chevron names the human step owed; without a step the generic word stays. -assert.strictEqual(stageTrackerUnauthorizedWord(item), 'Awaiting human: approve workflow runs'); +assert.strictEqual(stageTrackerUnauthorizedWord(item), 'Waiting for a maintainer · approve workflow runs on GitHub'); +assert.strictEqual(stageTrackerUnauthorizedWord(Object.assign({ author: 'clubanderson', author_kind: 'human' }, item)), 'Waiting for @clubanderson · approve workflow runs on GitHub'); +assert.strictEqual(stageTrackerUnauthorizedWord(Object.assign({ author: 'hive-bot', author_kind: 'hive' }, item)), 'Waiting for a maintainer · approve workflow runs on GitHub'); assert.strictEqual(stageTrackerUnauthorizedWord({ stage: 85, modifiers: ['unauthorized'] }), ''); assert.strictEqual(STAGE_TRACKER_HUMAN_GATED, 85); ` diff --git a/src/pkg/dashboard/stage_tracker_vocabulary.go b/src/pkg/dashboard/stage_tracker_vocabulary.go index fcb22d0d59..0dab37b723 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary.go @@ -88,9 +88,60 @@ func stageTrackerItemColumn(it *StageTrackerItem) int { return trackerColumnMergeGate } } + if stageTrackerPersonActsOnPR(it) { + return trackerColumnPR + } return stageTrackerColumn(st) } +// stageTrackerPersonActsOnPR: a PR parked at 085 because a person has to +// act ON THE PR — rerun CI, approve workflow runs, resolve a permission +// (reason `unauthorized:<step>`), or answer review findings / red checks +// still open on its head — is not queued, merging or merge-ready, so its +// chevron lights PR in progress, never Merge queue. The Merge queue +// column is only for rows actually queued / merging / merged, or a +// merge-ready PR (review approved, CI green) parked on a merge decision. +// A bare 085 with no track evidence keeps the gate: the person decides +// there (hive#14821). Hive's own #16524 read "Awaiting human: rerun +// shared ci" under Merge queue with CI unknown and review findings open. +func stageTrackerPersonActsOnPR(it *StageTrackerItem) bool { + if it == nil || it.Kind != "pr" || stageByNumber(it.Stage) != stagelabels.NeedsDecision { + return false + } + if mg := it.MergeGate; mg != nil && mg.State != "" { + return false + } + if mt := it.MergeTrain; mt != nil && mt.State != "" { + return false + } + if step, _ := stageTrackerUnauthorized(it.Reason); step != "" { + return !stageTrackerMergeReadyEvidence(it) + } + return stageTrackerNotMergeReadyEvidence(it) +} + +func stageTrackerActivityOnHead(it *StageTrackerItem, a *StageTrackerActivity) bool { + return a != nil && (a.Head == "" || it.Head == "" || strings.EqualFold(a.Head, it.Head)) +} + +// stageTrackerMergeReadyEvidence: review approved and CI green on the +// row's current head — the only state in which a human-gated PR may sit +// in the Merge queue column. +func stageTrackerMergeReadyEvidence(it *StageTrackerItem) bool { + return stageTrackerActivityOnHead(it, it.ReviewActivity) && it.ReviewActivity.State == "approved" && + stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State == "passing" +} + +// stageTrackerNotMergeReadyEvidence: a track on the current head says the +// PR is short of merge-ready (review not approved, CI not green). CI that +// is queued or running on the same head is a re-run, not a regression, so +// it does not count. +func stageTrackerNotMergeReadyEvidence(it *StageTrackerItem) bool { + return (stageTrackerActivityOnHead(it, it.ReviewActivity) && it.ReviewActivity.State != "approved") || + (stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State != "passing" && + it.CIActivity.State != "queued" && it.CIActivity.State != "running") +} + // stageTrackerStagePhrase is the stage as a lowercase clause for the // middle of a sentence ("its PR is reviewed · waiting for merge // admission"), from the same words the chevron shows. @@ -115,7 +166,7 @@ func stageTrackerStagePhrase(stage stagelabels.Stage) string { case stagelabels.Reviewed: return "review passed · waiting for merge admission" case stagelabels.Fixing: - return "being fixed by hive" + return "being remediated by hive" case stagelabels.NeedsAuthor: return "waiting for its author" case stagelabels.ReturnedToContributor: diff --git a/src/pkg/dashboard/stage_tracker_vocabulary_test.go b/src/pkg/dashboard/stage_tracker_vocabulary_test.go index 24230aee29..c501e71693 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary_test.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary_test.go @@ -29,7 +29,7 @@ func TestStageTrackerVocabularyTable(t *testing.T) { stagelabels.IssueNeedsDecision: {trackerColumnActionable, "waiting for a human decision"}, stagelabels.ReviewPending: {trackerColumnReview, "in CI / review"}, stagelabels.Reviewed: {trackerColumnReview, "review passed · waiting for merge admission"}, - stagelabels.Fixing: {trackerColumnReview, "being fixed by hive"}, + stagelabels.Fixing: {trackerColumnReview, "being remediated by hive"}, stagelabels.NeedsAuthor: {trackerColumnReview, "waiting for its author"}, stagelabels.ReturnedToContributor: {trackerColumnReview, "returned to the contributor"}, stagelabels.AdoptedByHive: {trackerColumnReview, "adopted by hive"}, diff --git a/src/pkg/dashboard/stage_tracker_webhook_ci_test.go b/src/pkg/dashboard/stage_tracker_webhook_ci_test.go new file mode 100644 index 0000000000..e7f8e6a5b4 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_webhook_ci_test.go @@ -0,0 +1,145 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// TestStageTrackerCICountsFromWebhookEvidence: check deliveries applied to +// the per-head evidence store drive the CI chevron counts for a PR whose +// status snapshot carries no (or stale) CIActivity — including sidelined +// PRs the eval cycle never enriches (hivecommons/hive#16521). +func TestStageTrackerCICountsFromWebhookEvidence(t *testing.T) { + now := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetCIEvidenceForTest(func() time.Time { return now })) + s, store := stageTrackerFixture(t, now) + + appID := int64(15368) + done := now.Add(-time.Minute) + checks := []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success", NodeID: "CR_build", AppID: &appID, Since: &done}, + {Name: "test", State: "in_progress", NodeID: "CR_test", AppID: &appID, Since: &done}, + } + if n := github.RecordCIEvidenceForTest("acme/console", "sha-103", checks); n != 2 { + t.Fatalf("recorded %d checks, want 2", n) + } + if n := github.RecordCIEvidenceForTest("acme/console", "sha-106", checks[:1]); n != 1 { + t.Fatalf("recorded %d checks, want 1", n) + } + + s.statusMu.Lock() + repo := &s.status.Repos[0] + for i, raw := range repo.OpenPrs { + pr, ok := raw.(FrontendPR) + if !ok || pr.Number != 103 { + continue + } + pr.HeadSHA = "sha-103" + // Evidence from a previous head must not win over the new head. + stale := now.Add(-time.Hour) + pr.CIActivity = &github.PRCIActivity{Head: "old-103", Source: "github-check-runs", ObservedAt: &stale, + Checks: []github.PRActivityCheck{{Name: "build", State: "completed", Conclusion: "failure"}}} + repo.OpenPrs[i] = pr + } + repo.NonActionablePrs = []any{ + github.RepoWorkPR{Repo: "acme/console", Number: 106, Title: "WIP draft", Author: "zoe", Draft: true, Bucket: "draft", Reason: "Draft", HeadSHA: "sha-106", CreatedAt: now.Add(-24 * time.Hour)}, + } + s.statusMu.Unlock() + + resp := s.buildStageTracker(s.status, store, now) + pr103 := trackerItem(t, resp, "pr", 103) + if pr103.CIActivity == nil || pr103.CIActivity.Head != "sha-103" || pr103.CIActivity.ChecksTotal != 2 || pr103.CIActivity.ChecksPassed != 1 || pr103.CIActivity.ChecksFailed != 0 { + t.Fatalf("pr103 CI = %+v, want 1/2 on sha-103 from webhook evidence", pr103.CIActivity) + } + pr106 := trackerItem(t, resp, "pr", 106) + if pr106.CIActivity == nil || pr106.CIActivity.ChecksTotal != 1 || pr106.CIActivity.ChecksPassed != 1 { + t.Fatalf("sidelined pr106 CI = %+v, want 1/1 from webhook evidence", pr106.CIActivity) + } +} + +// TestGitHubWebhookCheckRunAppliesCIEvidenceWithoutGitHubCall: a +// `check_run` delivery that names its PR updates the CI evidence from the +// payload alone — no PR re-read is queued, the GitHub test server would +// fail the test on any call — and /api/status.webhooks reports CI event +// health. +func TestGitHubWebhookCheckRunAppliesCIEvidenceWithoutGitHubCall(t *testing.T) { + const secret = "s3cr3t" + t.Setenv(githubWebhookSecretEnvVar, secret) + now := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetWebhookTrackerForTestWithClock(func() time.Time { return now })) + t.Cleanup(github.ResetCIEvidenceForTest(func() time.Time { return now })) + s := newGitHubWebhookTestServer(t) + + // A prior listing exists for the head, so the delivery needs no re-read. + appID := int64(15368) + started := now.Add(-2 * time.Minute) + listedAt := now.Add(-time.Minute) + github.RecordCIListingForTest("webhookorg/webhookrepo", "abc123", &github.PRCIActivity{ + Head: "abc123", Source: "github-check-runs", ObservedAt: &listedAt, + Checks: []github.PRActivityCheck{{Name: "unit", State: "in_progress", NodeID: "CR_unit", AppID: &appID, Since: &started}}, + }) + + body := []byte(`{"action":"completed","repository":{"full_name":"webhookorg/webhookrepo"}, + "check_run":{"id":1,"node_id":"CR_unit","name":"unit","status":"completed","conclusion":"success","head_sha":"abc123", + "started_at":"2026-10-17T08:58:00Z","completed_at":"2026-10-17T08:59:30Z","app":{"id":15368,"name":"GitHub Actions"}, + "pull_requests":[{"number":5}]}}`) + rec := postGitHubWebhook(s, "check_run", signGitHubWebhookForTest(secret, body), body) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (%s)", rec.Code, rec.Body.String()) + } + var got struct { + Status string `json:"status"` + TrackerRefresh *int `json:"tracker_refresh"` + CIEvidence *struct { + HeadSHA string `json:"head_sha"` + Applied int `json:"applied"` + Refetch bool `json:"refetch"` + PRs []int `json:"prs"` + } `json:"ci_evidence"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Status != "ok" || got.CIEvidence == nil || got.CIEvidence.Applied != 1 || got.CIEvidence.Refetch || got.CIEvidence.HeadSHA != "abc123" || len(got.CIEvidence.PRs) != 1 || got.CIEvidence.PRs[0] != 5 { + t.Fatalf("response = %s, want ci_evidence applied 1 on abc123 for PR 5 with no refetch", rec.Body.String()) + } + if got.TrackerRefresh != nil { + t.Fatalf("payload-served check delivery must not queue a PR re-read: %s", rec.Body.String()) + } + completed := now.Add(-30 * time.Second) + merged := github.HeadCIActivity("webhookorg/webhookrepo", "abc123", nil) + if merged == nil || len(merged.Checks) != 1 || merged.Checks[0].Conclusion != "success" || merged.Checks[0].Since == nil || !merged.Checks[0].Since.Equal(completed) { + t.Fatalf("head evidence = %+v, want the completed unit run", merged) + } + pr := github.PullRequest{Number: 5, HeadSHA: "abc123"} + if ci := stageTrackerCIActivity(github.PullRequest{Number: 5, HeadSHA: "abc123", CIActivity: merged}, now); ci.ChecksTotal != 1 || ci.ChecksPassed != 1 { + t.Fatalf("tracker counts for %d = %+v, want 1/1", pr.Number, ci) + } + + s.statusMu.Lock() + s.status = &StatusPayload{HiveID: "webhook-test"} + s.statusMu.Unlock() + statusRec := httptest.NewRecorder() + s.handleStatus(statusRec, httptest.NewRequest(http.MethodGet, "/api/status?fields=webhooks", bytes.NewReader(nil))) + var status struct { + Webhooks struct { + LastCIEventAt *time.Time `json:"last_ci_event_at"` + CIEvents1h int `json:"ci_events_1h"` + CIEventsApplied1h int `json:"ci_events_applied_1h"` + CIRefetches1h int `json:"ci_refetches_1h"` + } `json:"webhooks"` + } + if err := json.Unmarshal(statusRec.Body.Bytes(), &status); err != nil { + t.Fatal(err) + } + w := status.Webhooks + if w.LastCIEventAt == nil || !w.LastCIEventAt.Equal(now) || w.CIEvents1h != 1 || w.CIEventsApplied1h != 1 || w.CIRefetches1h != 0 { + t.Fatalf("/api/status webhooks CI health = %+v, want one event applied at %s", w, now) + } +} diff --git a/src/pkg/dashboard/stage_tracker_workflow_approval_test.go b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go new file mode 100644 index 0000000000..0fbad0e85c --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// A dependabot head whose 10 unreported required checks are workflow runs +// GitHub holds behind its approve-workflows gate reads as waiting on a +// person, not as "hasn't reported" (hivecommons/hive#16599). +func TestStageTrackerCIActivityWorkflowApproval(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + seen := now.Add(-2 * time.Hour) + required := []string{"verify", "build", "lint"} + activity := func(wa *github.PRWorkflowApproval) github.PullRequest { + return github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, Required: required, StatusesKnown: true, + RequiredSource: "protection", + RequiredChecks: []github.PRRequiredCheck{{Name: "verify", AppKnown: true}, {Name: "build", AppKnown: true}, {Name: "lint", AppKnown: true}}, + Checks: []github.PRActivityCheck{{Name: "verify", State: "completed", Conclusion: "success"}}, + WorkflowApproval: wa, + }} + } + for _, tc := range []struct { + name string + wa *github.PRWorkflowApproval + wantBlocker string + wantCaption string + wantActor string + }{ + {"gated", &github.PRWorkflowApproval{Pending: 10, RunIDs: []int64{1}, Actor: "dependabot[bot]", ObservedAt: &seen}, + "workflow-approval-required:10", "CI waiting · 10 workflow runs need approval on GitHub", "dependabot[bot]"}, + {"single gated run", &github.PRWorkflowApproval{Pending: 1}, "workflow-approval-required:1", "CI waiting · 1 workflow run needs approval on GitHub", ""}, + {"no gate", nil, "build", "hasn't reported for this head yet", ""}, + {"empty record", &github.PRWorkflowApproval{}, "build", "hasn't reported for this head yet", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + got := stageTrackerCIActivity(activity(tc.wa), now) + if got.State != "missing" || got.Active { + t.Fatalf("state=%q active=%v", got.State, got.Active) + } + if !strings.HasPrefix(got.Blocker, strings.TrimSuffix(tc.wantBlocker, "build")) || !strings.Contains(got.Caption, tc.wantCaption) { + t.Fatalf("blocker=%q caption=%q", got.Blocker, got.Caption) + } + if got.Actor != tc.wantActor { + t.Fatalf("actor=%q want %q", got.Actor, tc.wantActor) + } + if got.ChecksPassed != 1 || got.ChecksTotal != 3 { + t.Fatalf("counts %d/%d", got.ChecksPassed, got.ChecksTotal) + } + if tc.wa != nil && tc.wa.Pending > 0 { + if !strings.Contains(got.Detail, "approve workflows") { + t.Fatalf("detail=%q", got.Detail) + } + if tc.wa.ObservedAt != nil && (got.Since == nil || !got.Since.Equal(seen)) { + t.Fatalf("since=%v", got.Since) + } + } + }) + } +} + +// A PR at review pending (050) with no settled verdict is under review: +// "reviewing" with the posted-perspective count, never "unknown"; without +// a head bundle nothing has posted (hivecommons/hive#16599). +func TestStageTrackerReviewPendingState(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + in StageTrackerActivity + stage int + wantState, wantCap string + wantDone, wantActive int + }{ + {"no evidence at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "reviewing", "Review 0/5 · in progress", 0, 1}, + {"partial bundle at 050", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 1, PerspectivesTotal: 5}, 50, "reviewing", "Review 1/5 · in progress", 1, 1}, + {"all posted, no aggregate", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "adjudicating", "Review 5/5 · verdicts in · aggregating", 5, 1}, + {"not at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 2, PerspectivesTotal: 5}, 30, "unknown", "", 2, 0}, + {"settled verdict untouched", StageTrackerActivity{State: "approved", Caption: "Review approved", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "approved", "Review approved", 5, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + out := tc.in + stageTrackerReviewPendingState(&out, tc.stage, &now) + if out.State != tc.wantState || out.PerspectivesDone != tc.wantDone || out.Active != (tc.wantActive == 1) { + t.Fatalf("got %+v", out) + } + if tc.wantCap != "" && out.Caption != tc.wantCap { + t.Fatalf("caption=%q want %q", out.Caption, tc.wantCap) + } + if tc.wantActive == 1 && (out.ObservedAt == nil || !out.ObservedAt.Equal(now) && tc.in.ObservedAt == nil || !strings.Contains(out.Source, "stage-review-pending")) { + t.Fatalf("observed=%v source=%q", out.ObservedAt, out.Source) + } + }) + } +} diff --git a/src/pkg/dashboard/static-src/css/base.css b/src/pkg/dashboard/static-src/css/base.css index 2458e913e4..ab696b47f1 100644 --- a/src/pkg/dashboard/static-src/css/base.css +++ b/src/pkg/dashboard/static-src/css/base.css @@ -26,8 +26,11 @@ --font-ui: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace; /* Type ramp — section headers / card titles / labels only; body-copy sizes stay. */ - --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; - --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; + --fs-2xs: .6rem; --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; + --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; --fs-2xl: 1.5rem; --fs-3xl: 2rem; + /* The A6 ends of the ramp (2xs/2xl/3xl) were only ever defined inside + .config-modal, so var(--fs-2xs) elsewhere fell back to the 16px body + size (hivecommons/hive#16601). Same values in light and dark. */ /* Touch floor: iOS Safari zooms the page when a focused control is under 16px. */ --fs-touch: 16px; /* Mobile icon-only buttons (section ?/⚙/grip, topbar chips): a fixed diff --git a/src/pkg/dashboard/static-src/css/config-dialog.css b/src/pkg/dashboard/static-src/css/config-dialog.css index 6ed50fe89b..e3fc78bf03 100644 --- a/src/pkg/dashboard/static-src/css/config-dialog.css +++ b/src/pkg/dashboard/static-src/css/config-dialog.css @@ -430,6 +430,7 @@ .cmp-banner { border: 1px solid color-mix(in srgb, var(--yellow) 45%, transparent); background: color-mix(in srgb, var(--yellow) 8%, transparent); border-radius: var(--r); padding: var(--sp-4) var(--sp-5); margin-bottom: var(--sp-6); font-size: var(--fs-sm); } .cmp-banner strong { color: var(--text); } .cmp-banner-detail { color: var(--muted); margin-top: var(--sp-2); } + ul.cmp-banner-detail { margin: var(--sp-2) 0 0 var(--sp-5); } .cmp-framework { display: flex; gap: var(--sp-4); align-items: flex-start; padding: var(--sp-3) var(--sp-0); cursor: pointer; } .cmp-framework input { width: auto; margin-top: var(--sp-1); } .cmp-framework-name { font-weight: 600; color: var(--text); } diff --git a/src/pkg/dashboard/static-src/css/kiosk.css b/src/pkg/dashboard/static-src/css/kiosk.css index d0f7ec0f63..4808de68e7 100644 --- a/src/pkg/dashboard/static-src/css/kiosk.css +++ b/src/pkg/dashboard/static-src/css/kiosk.css @@ -23,8 +23,8 @@ boot.js set body.kiosk-cta-on (kiosk=1 and not cta=off), so the operator dashboard never shows it. Bottom-right, under the toast stack's corner and above the tracker; sized to read off a 720p Twitch transcode of a - 1920x1080 capture (URL >= 22px). The Matrix view (css/matrix.css) lifts - it above its fixed canvas and dims it. */ + 1920x1080 capture (URL >= 22px). The Code activity view (css/reader.css) + lifts it above its fixed overlay and dims it. */ #kiosk-cta { display: none; } body.kiosk-cta-on #kiosk-cta { display: flex; align-items: center; gap: var(--sp-4); diff --git a/src/pkg/dashboard/static-src/css/matrix.css b/src/pkg/dashboard/static-src/css/matrix.css deleted file mode 100644 index b8c35ee708..0000000000 --- a/src/pkg/dashboard/static-src/css/matrix.css +++ /dev/null @@ -1,17 +0,0 @@ -body.matrix-mode #hive-dashboard-root { display: none !important; } -body.matrix-mode #hive-matrix { - --matrix-bg: #000804; - --matrix-fg: #52ed86; - --matrix-surface: #000000; - --matrix-text: #e8f5eb; - --matrix-muted: #b8ccbb; - position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; -} -body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } -body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } -body.matrix-mode .matrix-list small { color: var(--matrix-muted); } -body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/css/overview.css b/src/pkg/dashboard/static-src/css/overview.css index acec47646b..696ae9d756 100644 --- a/src/pkg/dashboard/static-src/css/overview.css +++ b/src/pkg/dashboard/static-src/css/overview.css @@ -13,23 +13,30 @@ .overview-repo-filter { display: grid; gap: var(--sp-2); max-height: min(16rem, 32vh); overflow: auto; padding: var(--sp-2); border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg); } .overview-settings-links { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .overview-headline { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); } - .overview-kpis { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } + /* No headline child may widen the single auto column: on a phone a nowrap + stale pill otherwise stretches the track and every KPI tile with it + (hivecommons/hive#16601). */ + .overview-headline > * { min-width: 0; max-width: 100%; } + .overview-kpis { display: grid; min-width: 0; grid-template-columns: repeat(7, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } .overview-kpi-operator { display: inline-flex; align-items: center; justify-content: center; align-self: start; padding-top: var(--sp-3); color: var(--muted); font-size: var(--fs-lg); font-weight: 800; line-height: 1; } .overview-kpi-coverage-spacer { width: 1px; min-height: 100%; background: var(--border); opacity: 0.8; } - .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; white-space: nowrap; } + .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; justify-self: start; min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } @media (max-width: 1799px) { .overview-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } .overview-kpi-operator, .overview-kpi-coverage-spacer { display: none; } } @media (max-width: 720px) { .overview-kpis { grid-template-columns: minmax(0, 1fr); } } .overview-kpi-range { display: inline-flex; gap: var(--sp-1); } .overview-kpi-range-btn { min-width: 2rem; height: 1.25rem; border: 1px solid var(--border); border-radius: var(--r-pill); background: var(--bg); color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; cursor: pointer; } .overview-kpi-range-btn.active { border-color: var(--accent); color: var(--accent); } - .overview-kpi { display: grid; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } + .overview-kpi { display: grid; min-width: 0; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } .overview-kpi:hover { border-color: var(--accent); } .overview-kpi-value { font-size: var(--fs-lg); font-weight: 800; font-variant-numeric: tabular-nums; } .overview-kpi-label { color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; } - .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; } - .overview-kpi-spark { min-height: 24px; display: flex; align-items: end; margin-top: var(--sp-1); } - .overview-kpi-spark .sparkline { width: 100%; } - .overview-kpi-spark svg { width: 100%; height: 24px; } + .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; min-width: 0; overflow-wrap: anywhere; } + .overview-kpi-spark { min-height: 24px; min-width: 0; display: flex; align-items: end; margin-top: var(--sp-1); } + .overview-kpi-spark .sparkline { width: 100%; max-width: 100%; min-width: 0; } + .overview-kpi-spark svg { width: 100%; max-width: 100%; height: 24px; } + /* Phone: keep the tile label/subline at the compact body sizes the tiles + shipped with rather than the 2xs helper size. */ + @media (max-width: 720px) { .overview-kpi-label { font-size: var(--fs-base); } .overview-kpi-subline { font-size: var(--fs-md); } } .overview-kpi-coverage[data-coverage-state="success"] { --overview-coverage-color: var(--green); } .overview-kpi-coverage[data-coverage-state="warn"] { --overview-coverage-color: var(--yellow); } .overview-kpi-coverage[data-coverage-state="danger"] { --overview-coverage-color: var(--red); } diff --git a/src/pkg/dashboard/static-src/css/reader.css b/src/pkg/dashboard/static-src/css/reader.css new file mode 100644 index 0000000000..c12e6dc01c --- /dev/null +++ b/src/pkg/dashboard/static-src/css/reader.css @@ -0,0 +1,26 @@ +body.reader-mode #hive-dashboard-root { display: none !important; } +body.reader-mode #hive-reader { + --reader-bg: #0b0f0c; + --reader-surface: #121a14; + --reader-text: #e8f5eb; + --reader-muted: #b8ccbb; + --reader-add: #7ee2a0; + --reader-del: #ff8f8f; + --reader-tail: 10rem; + position: fixed; inset: 0; z-index: 100000; display: flex; flex-direction: column; + background: var(--reader-bg); color: var(--reader-text); font: 20px/1.5 monospace; +} +body.reader-mode .reader-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-5); padding: var(--sp-3) var(--sp-5); color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-status { flex: 1 1 auto; color: var(--reader-text); } +body.reader-mode .reader-pause { font: inherit; color: var(--reader-text); background: var(--reader-surface); border: 1px solid var(--reader-muted); border-radius: var(--radius-sm); padding: var(--sp-2) var(--sp-6); cursor: pointer; } +body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-0) var(--sp-5) var(--reader-tail); } +body.reader-mode .reader-card { max-width: 80rem; margin: 0 auto 1.5rem; padding: var(--sp-3) var(--sp-5); background: var(--reader-surface); border-radius: var(--radius); } +body.reader-mode .reader-meta { display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-repo { color: var(--reader-text); font-weight: 600; } +body.reader-mode a.reader-repo { text-decoration: underline; } +body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } +body.reader-mode .reader-add { color: var(--reader-add); } +body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode .reader-context { color: var(--reader-text); } +body.reader-mode #hive-reader [hidden] { display: none !important; } +body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 929ce26008..170584d39d 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -85,7 +85,7 @@ grid, the slot takes the Merge gate column plus the ✓ cap and right-aligns the chip over the gate. It never wraps with the filter bar, so the chip stays put whatever the toolbar does. */ - .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-5) var(--sp-2); } + .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-4) var(--sp-2); } /* Each entry is fenced by a hairline above it and lights up as a whole on hover, so a tall row (wrapped title, ↳ PR line) still reads as one block: its chip and age can only belong to the strip they sit beside. */ @@ -93,40 +93,44 @@ .ham-row:hover { background: color-mix(in srgb, var(--text) 4%, transparent); border-radius: var(--r-sm); } /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a - PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - the cap column is kept for the modifier chip and the since column is - an empty spacer (the time on step rides the strip row's since cell, in - line with the chevrons). Both cells wrap rather than collide; the lead - keeps a clear gap before the PR column. The spanning cells' flex-basis - absorbs the gaps they cover so the PR cell starts exactly at the PR in - progress chevron. */ + PR cell spanning PR in progress..Merge gate carries "[icon] #N title" + with the modifier chips / action buttons right-anchored on that same + line (margin-left: auto), wrapping under the PR metadata only when + there is no room. No separate toolbar line: the chevrons sit directly + under the title line. The since column is an empty spacer (the time on + step rides the strip row's since cell). + Explicit grid spans share the chevrons' tracks, including the two + concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } .ham-head-cols { flex: 1 1 auto; min-width: 0; min-height: 1.3em; align-items: flex-start; } .ham-head-cols .ham-strip { height: auto; } .ham-head-cols .ham-seg { background: transparent; clip-path: none; align-items: flex-start; justify-content: flex-start; padding: 0 var(--sp-2) 0 var(--sp-4); white-space: normal; } - /* Lead = exactly three of the six equal chevrons (half of the strip - minus the fixed 4em cap and the six gaps) plus the two gaps between - them, so the PR cell starts at the PR in progress chevron; the PR cell takes what - is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } - .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } - /* The PR cell is one line: connector, author icon + #N + title, lineage - chip and base pill sit side by side; the lineage chip gives way first - (flex-shrink 2), then the title (1), the pills and the connector never shrink - (hivecommons/hive "consolidate from 3 lines of text to 1"). */ - .ham-head-cols .ham-seg.ham-head-pr { flex: 1 1 0; flex-direction: row; flex-wrap: nowrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: hidden; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico, .ham-head-cols .ham-seg.ham-head-pr > .ham-badge { flex: 0 0 auto; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { display: block; flex: 0 2 auto; min-width: 7em; overflow: hidden; text-overflow: ellipsis; } + .ham-head-cols .ham-seg.ham-head-lead { grid-column: 1 / var(--ham-pr-start); grid-row: 1; padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-pr { grid-column: var(--ham-pr-start) / -2; grid-row: 1; flex-direction: row; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: visible; padding: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } - .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - /* The chip hugs the bottom of the title block (align-items: flex-end - inside the stretched cap cell): on a two-line title it sits on the - second line, directly over the strip it describes, never up at the - previous entry's edge. */ - .ham-head-cols .ham-seg.cap { flex: 0 0 auto; min-width: 4em; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; } - .ham-head-main { display: flex; flex: 1; align-items: center; gap: var(--sp-3); min-width: 0; overflow: hidden; } - .ham-head-main > .ham-badge { flex: 0 0 auto; } + /* The PR ref shares the first line with the right-anchored pills: it + grows into the free space but keeps a readable floor, so pills wrap + under it only when the line is genuinely full. */ + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 1 1 0; min-width: min(100%, 20em); } + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line > .ham-pr-ref { flex: 1 1 0; min-width: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges { position: static; flex: 0 1 auto; flex-wrap: wrap; justify-content: flex-end; margin-left: auto; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges:empty { display: none; } + .ham-head-cols .ham-seg.ham-head-tools { align-items: flex-start; } + .ham-head-cols .ham-seg.ham-head-tools:has(> .ham-badges:empty) { display: none; } + .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } + .ham-head-main > .ham-badge { flex: 0 1 auto; } + /* The title fills whatever is left of the first line beside its chips + (flex-basis 0) and only wraps its own words when there is no room; + with a max-content basis (flex: 0 1 auto) a wrapping flex container + drops the whole title onto a second line as soon as it cannot fit + entirely, even with half the row free (hivecommons/hive#16454). */ + .ham-head-main > .ham-title { flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-title { flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } .ham-linked-ico { color: var(--text-faint); font-size: var(--fs-xs); margin-right: var(--sp-1); } @@ -221,8 +225,8 @@ .ham-preparation-node:focus-visible { outline: var(--focus-ring-width) solid var(--ham-train-accent); outline-offset: var(--sp-1); } .ham-row.ham-preparation-gap::before, .ham-sub.ham-preparation-member.ham-preparation-gap::before { border-left-style: dashed; } .ham-preparation-unverified > .ham-strip-row > .ham-preparation-node::after { background: var(--bg); box-shadow: 0 0 0 var(--line-width) var(--ham-train-accent); } - .ham-preparation-comment { animation: none; } - .ham-human-context { animation: none; } + .cue-event.ham-preparation-comment { animation: none; } + .cue-event.ham-human-context { animation: none; } /* Mixed issue trees keep their existing children; only actual prep PRs receive a rail, at the original gutter offset minus the parent inset. */ .ham-row > .ham-preparation-head { margin-left: calc(-1 * var(--sp-2)); } @@ -328,22 +332,14 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } - /* The chevron strips (and the column header) are a grid; the title - line's strip is not — its lead / PR / cap cells size by flex. The - ham-head-cols class sits on the strip's row, not on the strip, so - the exclusion is spelled on the row: on the strip itself it matched - every strip and put the title line's cap chips in one chevron-wide - column, where wide chips spilled left over the PR title. */ - .ham-strip-row:not(.ham-head-cols) > .ham-strip { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 1; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } - .ham-track-name { font-weight: var(--fw-semibold); } - .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + /* The concurrent CI / Review lanes are chevrons like every other stage + (same clip-path, padding and height — the boxed card opt-out of + #16384 is gone); their lane state reads through fill, tint and text + colour exactly as done / todo / active do, never a border or ring, + which the notched polygon would clip anyway. */ .ham-track-state a { color: inherit; } - .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } - .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } - .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -353,17 +349,23 @@ /* The holder's offline / not-registered state is muted: a flag, not an alarm. */ .ham-holder-presence { margin-right: 0; color: var(--text-faint); font-weight: normal; } .ham-holder-presence.ham-presence-offline { --ham-presence-color: var(--text-faint); } - /* A word with a holder ("PR in progress · @bob's clanker") stays on one - line: the stage word keeps its width and the name gives way with an - ellipsis before anything wraps (hivecommons/hive#15541). */ - .ham-seg-t.ham-has-holder, .ham-detour.ham-has-holder { display: inline-flex; align-items: baseline; min-width: 0; max-width: 100%; white-space: nowrap; } - .ham-has-holder > .ham-holder { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: pre; } .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } + /* Evidence-based remediation on the PR in progress chevron: a red PR + nobody has picked up is bright and still; a pushed fix head is a + done-style step that keeps its word (stage_tracker_remediation.go). */ + .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } + .ham-seg.done.ham-fix-pushed { color: var(--green); } +/* A done decision column that still names the blocker a person must + clear while a covering PR drives the strip (hivecommons/docs#612). */ +.ham-seg.done.ham-blocker-note { color: var(--amber); opacity: 1; } +/* The "needs human" pill is a button: click scrolls to the Needs human line. */ +.ham-needs-human-pill { cursor: pointer; font: inherit; } +.ham-needs-human-pill:hover, .ham-needs-human-pill:focus-visible { text-decoration: underline; } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } - .ham-sub { display: grid; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } + .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } /* Only the two moving buckets animate (see stageTrackerMotion): the hive acting = gentle pulse; waiting on a person = slower amber→red breathe. A lit step with no data-motion (Open, Open · hold, Claimed, …) is a @@ -373,6 +375,65 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } + /* A CI / Review track wears its own state on the current head + (hivecommons/hive#16484): in progress = the full .active fill, done = + .done, a finding (red CI, changes requested) = .failing in the error + colour, not started = .todo with the glyph alone. No muted + "current-phase" tint: the operator reads the words, not the shade. + Only fresh observed work earns the pulse. */ + .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } + /* A FILLED chevron means "this is where the item is / what moves now" + (hivecommons/hive#16540). A CI / Review track is filled only while it + runs (.active, amber). Every other state is words on the muted field + with the semantic colour on text and glyph only: green for passed / + approved, red for a finding, muted for pending, decided or not started. */ + .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* A not-yet-run track in the current phase (CI unknown on a 050 row, + Review queued beside running CI) keeps the same muted field as its + done / failing neighbours — the glyph alone, neutral — so the current + phase stays a visibly filled location (hivecommons/hive#16599). */ + .ham-seg.ham-activity-track.todo.ham-current { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; } + /* Words without motion (checks not reported, unknown evidence, a row + parked on a person): current-phase text on a muted field, never amber. */ + .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* The stage chevron while both tracks run: bright words, no amber, no pulse. */ + .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } + .ham-seg.active.ham-settled-current::before { display: none; } + .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve — done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } + /* The count words stay on one line and ellipsize instead of wrapping. */ + .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } + /* A settled verdict is the glyph alone (green passed / approved, red + failed / changes requested — the .done / .failing colours above); + the words live in the tooltip. Same box, same height: only the + trailing gap goes and the stroke firms up so the colour reads. */ + .ham-chevron-copy.ham-track-verdict .ham-ico { margin-right: 0; stroke-width: 2; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -402,10 +463,32 @@ after the word ("next sweep in 42s", "7m left") is muted. */ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } - /* The detail is a fixed short phrase; should a long one ever reach it - (hivecommons/docs#512 drew a raw GitHub URL across the column) it is - clipped with an ellipsis rather than overflowing the chip. */ - .ham-gate-detail { font-weight: normal; opacity: 0.85; white-space: nowrap; font-variant-numeric: tabular-nums; display: inline-block; vertical-align: bottom; max-width: 12em; overflow: hidden; text-overflow: ellipsis; } + .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } + /* Every physical chevron is one caption line tall (--ham-chevron-text-lines: + 1, the clamp below ellipsises the rest): the strip rides directly under + the title line as a ~20px band, the density the tracker had before + hivecommons/hive#16454 doubled it with a two-line budget and sp-2 + vertical padding. The grid row sizes to content with that one-line + floor so icon-only cells and siblings share the row's height, never a + fixed box. The portal tooltip is outside the clipped polygon; keyboard + focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } + /* min-height: 0 and no ::before ring: on phones / coarse pointers + responsive.css turns every .config-info into a --tap-target (40px) + square with a drawn ring; the chevron's info wrapper is not that + icon, and its 40px floor made every chevron a 44px box. */ + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; min-height: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info::before { content: none; } + .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } + .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } + /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with + their icons, sit centred in the chevron as before; a wrapped second + line is centred under the first rather than ragged-left. */ + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } + .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { min-height: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ Owner request: a viewer must always read where an item stands, @@ -502,7 +585,7 @@ page text: ≥ 15:1 in both themes, see the contrast test) above the stripes and the pulse overlay, on one line with an ellipsis. */ .cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; } - .ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .ham-seg.active > .cue-acting-cap > .cue-acting-spin { vertical-align: -1px; margin-right: var(--sp-2); } .cue-event { display: flex; align-items: baseline; gap: var(--sp-2); margin: 0; padding-left: var(--sp-5); font-size: var(--fs-xs); color: var(--muted); overflow-wrap: anywhere; animation: cue-event-in 0.4s ease-out; } .cue-event-who { font-weight: var(--fw-medium); color: var(--text); } @@ -668,7 +751,7 @@ .ham-row { position: relative; } .ham-row:focus-visible { outline: var(--focus-ring-width) solid var(--accent); outline-offset: calc(-1 * var(--focus-ring-width)); border-radius: var(--r-sm); } .ham-row.ham-selected { background: color-mix(in srgb, var(--accent) 10%, transparent); box-shadow: inset var(--sp-1) 0 0 var(--accent); border-radius: var(--r-sm); } - .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-5); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } + .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-4); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } /* A nested PR sub-row carries its own gutter (checkbox + ⋯), so each PR under an issue is selected and acted on by itself (two PRs under one issue, one decision each — the owner's 2026-10-28 report). The @@ -741,15 +824,21 @@ .ham-decision-act[aria-disabled="true"] { color: var(--text-faint); border-style: dashed; cursor: default; opacity: 0.6; } .ham-decision-act[aria-disabled="true"]:hover { background: transparent; border-color: var(--line-subtle); } .ham-decision-act.ham-decision-more { color: var(--text-muted); } - /* The row's inline lead action (the ⋯ menu's lead entry, in sight): a - small primary pill in the chip slot, the popover lead's recipe, the - row's cue colour; dashed and faint with its reason when the viewer - may not take it. */ - .ham-lead-act { padding: 0 var(--sp-3); border: var(--line-width) solid var(--cue-state, var(--accent)); border-radius: var(--r-pill); background: color-mix(in srgb, var(--cue-state, var(--accent)) 10%, transparent); color: var(--cue-state, var(--accent)); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.4; cursor: pointer; white-space: nowrap; } - .ham-lead-act:hover, .ham-lead-act:focus-visible { background: color-mix(in srgb, var(--cue-state, var(--accent)) 22%, transparent); outline: none; } - .ham-lead-act:focus-visible { box-shadow: 0 0 0 var(--line-width) var(--accent); } - .ham-lead-act.ham-menu-danger { color: var(--red); border-color: var(--red); background: color-mix(in srgb, var(--red) 10%, transparent); } - .ham-lead-act[aria-disabled="true"] { color: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; } + /* The row's inline action pills (the ⋯ menu's lead entry, and "Let hive + decide" beside it on a row parked on a human decision): real buttons + that must not pass for the record pills in the same slot ("adopted + from #N", the base branch — muted outlines, no hover). So: a filled + chip, a trailing ▸ glyph, pointer cursor, hover lift and focus ring. + Primary (the lead) fills amber; secondary (delegate) fills neutral; + danger (a server-led close) fills red. Dashed, faint and glyph-less + with its reason when the viewer may not take it. */ + .ham-lead-act { --ham-act-fill: var(--amber); --ham-act-ink: var(--bg); display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-3); border: var(--line-width) solid var(--ham-act-fill); border-radius: var(--r-pill); background: var(--ham-act-fill); color: var(--ham-act-ink); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.5; cursor: pointer; white-space: nowrap; transition: filter 120ms ease, box-shadow 120ms ease; } + .ham-lead-act::after { content: '▸'; opacity: 0.85; } + .ham-lead-act.ham-act-secondary { --ham-act-fill: var(--panel-strong); --ham-act-ink: var(--text); border-color: var(--line-strong); } + .ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red); --ham-act-ink: var(--bg); } + .ham-lead-act:hover, .ham-lead-act:focus-visible { filter: brightness(1.12); outline: none; box-shadow: 0 0 0 var(--line-width) var(--bg), 0 0 0 calc(var(--line-width) * 3) var(--ham-act-fill); } + .ham-lead-act[aria-disabled="true"] { --ham-act-fill: transparent; --ham-act-ink: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; filter: none; box-shadow: none; } + .ham-lead-act[aria-disabled="true"]::after { content: none; } /* Busy (Let hive decide gathering its preview) also sets aria-disabled, so this compound rule sits after the disabled one and wins: the working colour, not faint/dashed. */ .ham-lead-act[aria-busy="true"][aria-disabled="true"] { cursor: progress; opacity: 1; border-style: solid; border-color: var(--cue-work); background: color-mix(in srgb, var(--cue-work) 10%, transparent); color: var(--cue-work); } @@ -766,21 +855,16 @@ a needs-human step keeps a steady red tint so it still stands out. */ @media (prefers-reduced-motion: reduce) { .ham-seg.active { animation: none; box-shadow: inset 0 0 0 2px var(--surface-0); } .ham-seg.active[data-motion]::before { display: none; } .ham-seg.active[data-motion="needs-human"] { background: color-mix(in srgb, var(--amber) 45%, var(--red)); } } @media (max-width: 1100px) { - /* Keep the aligned progress strip compact; put its active step in a - wrapping caption instead of squeezing actionable words into a chevron. */ - .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + /* Stack headers, but keep the same two-line progress text budget. */ + .ham-cols .ham-seg-t { display: none; } .ham-cols .ham-track-head .ham-seg-t { display: inline; } - .ham-track-state { display: none; } - .ham-track-code-note, .ham-track-context { display: none; } - .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } .ham-head-cols { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2) var(--sp-3); } .ham-head-cols > .ham-strip { display: contents; } - .ham-head-cols .ham-seg.ham-head-lead, .ham-head-cols .ham-seg.ham-head-pr { grid-column: 1 / -1; padding: 0; } + .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-start; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } @@ -788,6 +872,11 @@ .ham-cols .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-cols .ham-seg.cap { flex-basis: 2em; } } + @media (max-width: 640px) { + #activity-monitor-panel { --ham-compact-min-width: 60em; } + .ham-row > .ham-strip-row, .ham-sub > .ham-strip-row, .ham-cols > .ham-strip-row { overflow-x: auto; } + .ham-row > .ham-strip-row > .ham-strip, .ham-sub > .ham-strip-row > .ham-strip, .ham-cols > .ham-strip-row > .ham-strip { min-width: var(--ham-compact-min-width); } + } /* Movement animation: when an item's lit chevron changes column between two refreshes, the chosen effect (settings gear → Movement animation) plays once on that row. Overlays live in .ham-anim-layer, an absolute diff --git a/src/pkg/dashboard/static-src/html/faq.html b/src/pkg/dashboard/static-src/html/faq.html index 9586cb3fba..6075f22dea 100644 --- a/src/pkg/dashboard/static-src/html/faq.html +++ b/src/pkg/dashboard/static-src/html/faq.html @@ -267,7 +267,7 @@ <h3 class="faq-group-title">Where to get help</h3> </div><!-- /#hive-dashboard-root --> <!-- Kiosk call-to-action badge (#16236). The server replaces this comment with pkg/webassets/kioskcta markup at start-up; it sits outside - #hive-dashboard-root because the Matrix view hides the root. Visible + #hive-dashboard-root because the Matrix and reader views hide the root. Visible only with body.kiosk-cta-on (kiosk=1 and not cta=off, see js/boot.js). --> <!-- hive-kiosk-cta --> diff --git a/src/pkg/dashboard/static-src/html/topbar.html b/src/pkg/dashboard/static-src/html/topbar.html index 210b601c42..579f6885af 100644 --- a/src/pkg/dashboard/static-src/html/topbar.html +++ b/src/pkg/dashboard/static-src/html/topbar.html @@ -30,7 +30,7 @@ <div class="oc-topbar-right"> <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">🐛</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> - <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display — opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> + <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=reader" target="_blank" rel="noopener" title="Code activity — published pushed changes as readable paragraphs (opens in a new tab)" aria-label="Code activity" hidden><span class="nav-chip__label">Code activity</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings — governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">⚙</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> diff --git a/src/pkg/dashboard/static-src/js/agent-detail.js b/src/pkg/dashboard/static-src/js/agent-detail.js index dbb9a10649..1ae393da2a 100644 --- a/src/pkg/dashboard/static-src/js/agent-detail.js +++ b/src/pkg/dashboard/static-src/js/agent-detail.js @@ -134,6 +134,7 @@ document.querySelectorAll('.oc-nav-item').forEach(i => i.classList.remove('active')); const active = document.querySelector(`.oc-nav-item[data-agent-nav="${(window.CSS && CSS.escape) ? CSS.escape(name) : String(name).replace(/["\\]/g, '\\$&')}"]`); if (active) active.classList.add('active'); + if (typeof dashboardProgressiveWake === 'function') dashboardProgressiveWake(); navPeekRestore('agents-section', { instant: true }); const expanded = navPeekExpand('agents-section'); if (!expanded && isSectionCollapsed('agents-section')) toggleSection('agents-section', { collapsed: false, persist: false, navPeek: true }); @@ -939,4 +940,3 @@ // Agent descriptions now come from the JSON status payload (agent.description field). // This empty map serves as a fallback for agents without a description in config. const AGENT_DESCRIPTIONS = {}; - diff --git a/src/pkg/dashboard/static-src/js/approvals.js b/src/pkg/dashboard/static-src/js/approvals.js index c998fc504c..17afa0ea5a 100644 --- a/src/pkg/dashboard/static-src/js/approvals.js +++ b/src/pkg/dashboard/static-src/js/approvals.js @@ -337,7 +337,13 @@ // Prime both panels and poll them on a modest independent interval. Do not // block initial paint: these run after the main poll is already wired. - function v4RefreshPanels() { fetchHiveAdvice(); fetchACMMReco(); fetchLifecycle(); fetchPRThroughput(); fetchApprovals(); } + function v4RefreshPanels() { + [['hive-advice', fetchHiveAdvice], ['acmm-reco', fetchACMMReco], + ['lifecycle', fetchLifecycle], ['pr-throughput', fetchPRThroughput], + ['approvals', fetchApprovals]].forEach(function([key, fn]) { + dashboardScheduleWork(key, fn).catch(console.error); + }); + } v4RefreshPanels(); searchPaneProbe(); dashboardSetInterval('v4-panels', v4RefreshPanels, V4_PANELS_POLL_MS); @@ -379,7 +385,7 @@ } } catch (_) { /* dashboard unreachable — different problem */ } } - checkGhAuth(); + dashboardScheduleWork('gh-auth-banner', checkGhAuth).catch(console.error); dashboardSetInterval('gh-auth-banner', checkGhAuth, GH_AUTH_POLL_MS); function renderGhRateLimits(ghRateLimits) { @@ -491,4 +497,3 @@ function setIfChanged(el, html) { if (el.innerHTML !== html) el.innerHTML = html; } - diff --git a/src/pkg/dashboard/static-src/js/backends-tokens.js b/src/pkg/dashboard/static-src/js/backends-tokens.js index 73d56eb3a9..79ae0a1252 100644 --- a/src/pkg/dashboard/static-src/js/backends-tokens.js +++ b/src/pkg/dashboard/static-src/js/backends-tokens.js @@ -392,11 +392,11 @@ return INFERENCE_MODELS[backend] || []; } } - function refreshBackendDiscovery(force) { - INFERENCE_BACKENDS.forEach(b => fetchInferenceModels(b, force)); + async function refreshBackendDiscovery(force) { + for (const backend of INFERENCE_BACKENDS) await fetchInferenceModels(backend, force); // Load configured gateway names so the backend/method pickers list them // (e.g. openrouter) alongside KNOWN_BACKENDS after the first paint. - fetchConfiguredGateways(); + await fetchConfiguredGateways(); } const CLI_MODEL_CACHE_TTL_MS = 30000; diff --git a/src/pkg/dashboard/static-src/js/boot.js b/src/pkg/dashboard/static-src/js/boot.js index f7e024e434..ecb48044f2 100644 --- a/src/pkg/dashboard/static-src/js/boot.js +++ b/src/pkg/dashboard/static-src/js/boot.js @@ -1,4 +1,4 @@ -// Apply layout immediately and hide content until first data render. +// Apply layout immediately; keep the shell visible while live data loads. // NOTE: only body classes are set here — the .layout-toggle buttons do NOT // exist in the DOM yet at this point, so any label write here is a no-op. // applyLayout() (defined in the main script) is the single source of truth @@ -36,10 +36,12 @@ (function(){ var kiosk=false, popout=false, display=false, view='', sound=true, density='', shift=false; try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; view=u.searchParams.get('view'); popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} - window.HIVE_MATRIX = kiosk && view === 'matrix'; - if(window.HIVE_MATRIX){ - document.body.classList.add('matrix-mode'); - document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); + // Code activity is the sole opt-in code display (#16477); view=matrix is a + // deprecated alias so saved Matrix display URLs open the reader. + window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix'); + if(window.HIVE_READER){ + document.body.classList.add('reader-mode'); + document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); } window.HIVE_KIOSK=kiosk; window.HIVE_POPOUT=popout&&!kiosk; @@ -84,9 +86,6 @@ if(window.HIVE_KIOSK){ var kt=null; try { kt=new URL(window.location.href).searchParams.get('theme'); } catch(e) {} m=(kt==='light')?'light':'dark'; } if(!m)m='light'; if(m==='light'){document.body.classList.add('light-mode')} - document.body.style.opacity='0'; - document.body.style.transition='opacity 0.15s ease-in'; - setTimeout(function(){ document.body.style.opacity='1'; }, 3000); document.addEventListener('DOMContentLoaded', function(){ if (typeof applyLayout === 'function' && typeof getLayout === 'function') { applyLayout(getLayout()); @@ -171,4 +170,3 @@ document.addEventListener('DOMContentLoaded', renderStyleState); } })(); - diff --git a/src/pkg/dashboard/static-src/js/chat.js b/src/pkg/dashboard/static-src/js/chat.js index 46fa9433bc..d625115364 100644 --- a/src/pkg/dashboard/static-src/js/chat.js +++ b/src/pkg/dashboard/static-src/js/chat.js @@ -503,8 +503,8 @@ chatInput.value = localStorage.getItem(CHAT_DRAFT_KEY) || ''; renderChatCheatsheet(); renderChatSuggestions(); - detectChatCapabilities(); - refreshChatPresence(); + dashboardScheduleWork('chat-capabilities', detectChatCapabilities).catch(console.error); + dashboardScheduleWork('chat-presence', refreshChatPresence).catch(console.error); dashboardSetInterval('chat-presence', refreshChatPresence, 30000); chatFab.onclick = () => { diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index f7c0568e9b..2604329fd1 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -784,6 +784,14 @@ <label>Fixer agent ${yamlHint('review.fixer_agent')} ${settingHelpMark('review-swarm', 'configuration', 'Fixer agent', `The agent kicked to address reviewer findings before re-review. Use the agent ID (the key in the roster, not its display name). Blank falls back to the PR's authoring agent, then scanner.`)}</label> <input type="text" value="${esc(rv.fixer_agent || '')}" placeholder="scanner (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"> </div> + <div class="config-field mt-3"> + <label>Fallback fixer agents (comma-separated) ${yamlHint('review.fixer_fallback_agents[]')} ${settingHelpMark('review-swarm', 'configuration', 'Fallback fixer agents', `Ordered agent IDs to try when the primary fixer cannot accept kicks. The first available fallback receives the repair without interrupting another turn. An empty list disables fallback routing.`)}</label> + <input type="text" value="${esc((rv.fixer_fallback_agents || []).join(', '))}" placeholder="e.g. fixer, scanner-2" spellcheck="false" data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"> + </div> + <div class="config-field mt-3"> + <label>Undeliverable kicks before fallback ${yamlHint('review.fixer_fallback_after_undeliverable')} ${settingHelpMark('review-swarm', 'configuration', 'Undeliverable kicks before fallback', `Consecutive undeliverable kicks before trying a fallback. 0 uses the default of 3. After at least one refusal, a fixer whose transcript exceeds its busy_no_activity_threshold can yield earlier. Requires a non-empty fallback agent list.`)}</label> + <input type="number" min="0" step="1" value="${esc(String(rv.fixer_fallback_after_undeliverable || ''))}" placeholder="3 (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"> + </div> <div class="config-field" style="margin-top:10px"> <label>Human decision label ${yamlHint('review.human_decision_label')} ${settingHelpMark('review-swarm', 'configuration', 'Human decision label', `An EXISTING repo label applied when the review swarm holds a PR for a human, so those PRs can be filtered from the list. There is no fleet-wide default and no standard name — use whatever the governed repos already maintain (this fleet's bluefin spoke uses 3-human-queue). The label is never created: if it is blank, misspelled, or absent from a repo, labeling is skipped there and the review comment's in-body marker still carries the signal.`)}</label> <input type="text" value="${esc(rv.human_decision_label || '')}" placeholder="(none) — must already exist in the repo" data-change-action="markDirty" data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"> diff --git a/src/pkg/dashboard/static-src/js/config-governor.js b/src/pkg/dashboard/static-src/js/config-governor.js index 77bc18abcb..3e0d568e5a 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -1880,7 +1880,7 @@ } return _statSources; } - ensureStatSources(); + dashboardScheduleWork('stat-sources', ensureStatSources).catch(console.error); /* statSourcesForDialog returns the source catalogue for the agent the config dialog is showing. The agent config response carries a catalogue @@ -2092,4 +2092,3 @@ <span style="opacity:0.8">— fixed progression; the last step is the cap.</span> </div>`; } - diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index 9feef53979..de4df6b709 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -59,6 +59,10 @@ markDirty('review', 'require_labels', parseReviewRequireLabels(text)); } + function markDirtyReviewFixerFallbackAgents(text) { + markDirty('review', 'fixer_fallback_agents', String(text || '').split(',').map(s => s.trim()).filter(Boolean)); + } + // Reviewer agents pick-list (Settings → Features → Review Gate → // Reviewers, #13460). The checked rows become review.reviewer_agents; an // empty selection means "keyword scan", mirroring the server. diff --git a/src/pkg/dashboard/static-src/js/config-tabs.js b/src/pkg/dashboard/static-src/js/config-tabs.js index 161d19f0c0..9b9608e828 100644 --- a/src/pkg/dashboard/static-src/js/config-tabs.js +++ b/src/pkg/dashboard/static-src/js/config-tabs.js @@ -35,7 +35,7 @@ // agent's kick history over the selected time window. if (tabId === AGENT_PROMPTS_TAB) initAgentPromptHistory(); } else { - body.innerHTML = renderGovernorTab(tabId); + body.innerHTML = renderGateRegressionBanner() + renderGovernorTab(tabId); settingsAnnotateRows(body); if (tabId === 'Hub') { fetchQueueCount(); fetchAutoUpdateStatus(); } // The escalation breaker lives at the top level of hive.yaml, so the @@ -75,6 +75,18 @@ if (typeof syncRepoSaveGuard === 'function') syncRepoSaveGuard(); } + // Safety-gate regression banner (#16438): /api/status config.gate_regressions + // lists the gates (review.require_labels, project.paused_repos, …) a + // previous runtime overlay carried that this boot's config dropped or + // loosened. Shown at the top of every Settings tab until the operator + // restores the gate (or removes it on purpose) and the hive restarts. + function renderGateRegressionBanner() { + const regs = ((window._lastStatus || {}).config || {}).gate_regressions || []; + if (!regs.length) return ''; + const items = regs.map(g => `<li><code>${esc(g.gate || '')}</code> was <code>${esc(g.previous || '')}</code>, now ${esc(g.effective || '')}${g.source ? ` <span class="text-muted">(from ${esc(g.source)})</span>` : ''}</li>`).join(''); + return `<div class="cmp-banner" id="gate-regression-banner" role="alert"><strong>Safety gate dropped at boot.</strong> This hive booted without ${regs.length === 1 ? 'a gate' : regs.length + ' gates'} its previous runtime config enforced; agents may now act on items it used to leave alone. Restore the setting here and save, or set <code>config.refuse_gate_regression: true</code> to make this fatal.<ul class="cmp-banner-detail">${items}</ul></div>`; + } + function renderAgentImport() { var exampleURL = 'https://github.com/hivecommons/hive/blob/HEAD/src/examples/agents/customized-agent.yaml'; var rawURL = 'https://raw.githubusercontent.com/hivecommons/hive/HEAD/src/examples/agents/customized-agent.yaml'; diff --git a/src/pkg/dashboard/static-src/js/cost.js b/src/pkg/dashboard/static-src/js/cost.js index 0154d206ed..9a95b83edb 100644 --- a/src/pkg/dashboard/static-src/js/cost.js +++ b/src/pkg/dashboard/static-src/js/cost.js @@ -707,6 +707,5 @@ renderCost(cost); } catch (e) { /* transient — leave last render in place */ } } - fetchCost(); + dashboardScheduleWork('cost', fetchCost).catch(console.error); dashboardSetInterval('cost', fetchCost, COST_POLL_MS); - diff --git a/src/pkg/dashboard/static-src/js/history-sparklines.js b/src/pkg/dashboard/static-src/js/history-sparklines.js index a57b031e7f..8cc169cb99 100644 --- a/src/pkg/dashboard/static-src/js/history-sparklines.js +++ b/src/pkg/dashboard/static-src/js/history-sparklines.js @@ -20,19 +20,28 @@ } function dashboardSetInterval(key, fn, ms) { dashboardClearInterval(key); - const entry = { fn, ms, timer: null }; + const entry = { key, fn, ms, timer: null }; DASHBOARD_INTERVALS[key] = entry; if (!document.hidden) dashboardStartInterval(entry); return entry; } function dashboardStartInterval(entry) { - entry.timer = setInterval(entry.fn, entry.ms); + entry.timer = setInterval(function() { + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } + }, entry.ms); } function dashboardClearInterval(key) { if (!DASHBOARD_INTERVALS[key]) return; clearInterval(DASHBOARD_INTERVALS[key].timer); delete DASHBOARD_INTERVALS[key]; } + function dashboardRunInterval(entry) { + if (typeof dashboardScheduleWork === 'function' && + Object.prototype.hasOwnProperty.call(DASHBOARD_TASK_SECTIONS, entry.key)) { + return dashboardScheduleWork(entry.key, entry.fn); + } + return entry.fn(); + } document.addEventListener('visibilitychange', () => { for (const [key, entry] of Object.entries(DASHBOARD_INTERVALS)) { if (DASHBOARD_INTERVALS[key] !== entry) continue; @@ -43,7 +52,7 @@ // A refresh failure must not prevent the other panels from resuming. // Snapshot iteration also permits a callback to clear/replace itself. if (DASHBOARD_INTERVALS[key] === entry) { - try { Promise.resolve(entry.fn()).catch(console.error); } catch (err) { console.error(err); } + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } } } }); @@ -493,4 +502,3 @@ capHistory(historyData); } } - diff --git a/src/pkg/dashboard/static-src/js/layout.js b/src/pkg/dashboard/static-src/js/layout.js index 084e68dbef..b93f6f532b 100644 --- a/src/pkg/dashboard/static-src/js/layout.js +++ b/src/pkg/dashboard/static-src/js/layout.js @@ -348,7 +348,7 @@ } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', start); - } else { start(); } + } else { queueMicrotask(start); } })(); const OC_TOPBAR_HEIGHT = 64; diff --git a/src/pkg/dashboard/static-src/js/matrix.js b/src/pkg/dashboard/static-src/js/matrix.js deleted file mode 100644 index 0b1a0137b7..0000000000 --- a/src/pkg/dashboard/static-src/js/matrix.js +++ /dev/null @@ -1,343 +0,0 @@ -// Matrix is an opt-in display only. Content always comes from the authorized -// pull endpoint; the shared SSE stream carries a content-free nudge. -(function(){ - 'use strict'; - var pull = function(){}; - window.hiveMatrixAttach = function(source){ - if (!window.HIVE_MATRIX) return; - source.addEventListener('code-lines', function(){ pull(); }); - source.addEventListener('open', function(){ pull(); }); - }; - window.hiveMatrixStart = function(){ - if (!window.HIVE_MATRIX || document.getElementById('hive-matrix')) return; - var params = new URL(window.location.href).searchParams; - function option(name, fallback){ - var value = params.get('mx.' + name); - try { - if (value === null) value = localStorage.getItem('hive.matrix.' + name); - else localStorage.setItem('hive.matrix.' + name, value); - } catch(e) {} - return value === null ? fallback : value; - } - function number(name, fallback, min, max){ - var value = Number(option(name, String(fallback))); - return Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback; - } - var effect = option('effect', 'rain'); - if (['rain', 'cascade', 'ghost', 'terminal'].indexOf(effect) < 0) effect = 'rain'; - var captions = option('captions', 'on') !== 'off'; - var speed = number('speed', 1, 0.1, 5), fps = number('fps', 30, 1, 60); - var palette = option('palette', 'green'); - var colors = {green: '#52ed86', amber: '#ffb347', gold: '#ffd700'}; - var color = colors[palette] || colors.green; - var root = document.createElement('main'); - root.id = 'hive-matrix'; - root.style.setProperty('--matrix-color', color); - document.body.appendChild(root); - function element(tag, className, text){ - var el = document.createElement(tag); - el.className = className; - if (text) el.textContent = text; - root.appendChild(el); - return el; - } - var canvas = element('canvas', 'matrix-canvas'); - canvas.setAttribute('aria-label', 'Pushed code lines · Matrix ' + effect); - var list = element('div', 'matrix-list'); - var notice = element('p', 'matrix-notice', 'Waiting for pushed lines…'); - notice.setAttribute('role', 'status'); - var labels = element('div', 'matrix-labels'); - var source = document.createElement('div'); - source.textContent = 'Source: lines pushed by hive · public allowlisted repos'; - var freshness = document.createElement('div'); - var pausedLabel = document.createElement('div'); - labels.append(source, freshness, pausedLabel); - var ctx = canvas.getContext('2d'); - var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); - var lines = [], lastSeq = 0, lastAt = 0, lastIngestAt = 0, startedAt = Date.now(); - var enabled = false, manualPause = false, loading = false, pending = false; - var frame = 0, previous = 0, page = 0, pageTimer = 0, drops = []; - var atlas = document.createElement('canvas'), glyphs = new Map(); - var width = 0, height = 0, cell = 20, rowH = 20, charW = 10; - // Ghost coder and Terminal type the delivered lines in order; once the - // queue runs dry they replay the bounded latest-line window. - var queue = [], tabs = [], typing = null, termRows = [], termHead = '', termClock = 0; - var muted = '#6f8f78', syntaxColors = {keyword: '#7fd4ff', string: '#ffd27f', comment: muted, number: '#ff9cf0'}; - var languages = { - go: {comment: '//', words: 'package import func return if else for range var const type struct interface map chan go defer select case switch default break continue nil true false'}, - js: {comment: '//', words: 'function var let const return if else for while do new class extends import export from default async await this null undefined true false typeof instanceof switch case break continue try catch finally throw of in'}, - py: {comment: '#', words: 'def class import from return if elif else for while in not and or is None True False with as lambda yield pass raise try except finally async await'}, - sh: {comment: '#', words: 'if then else elif fi for while do done case esac function local export return in'}, - rs: {comment: '//', words: 'fn let mut pub use mod struct enum impl trait match if else for while loop return self Self true false const static where async await'}, - c: {comment: '//', words: 'if else for while do return break continue switch case default new class public private protected static const struct enum typedef sizeof void int char long double float unsigned true false null this import package'} - }; - var extensions = {go: 'go', js: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', jsx: 'js', py: 'py', sh: 'sh', bash: 'sh', - rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; - Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); - function paused(){ return manualPause || document.hidden; } - function resize(){ - width = window.innerWidth; height = window.innerHeight; - canvas.width = width; canvas.height = height; - drops = []; - ctx.font = '16px monospace'; - charW = (ctx.measureText && ctx.measureText('M').width) || 10; - } - function resetText(){ queue = []; tabs = []; typing = null; termRows = []; termHead = ''; termClock = 0; } - function clearContent(message){ - enabled = false; lines = []; drops = []; glyphs.clear(); resetText(); - lastSeq = 0; lastAt = 0; lastIngestAt = 0; - list.replaceChildren(); ctx.clearRect(0, 0, width, height); - notice.textContent = message; - sync(); - } - function updateLabels(){ - var minutes = Math.floor(Math.max(0, Date.now() - (lastAt || startedAt)) / 60000); - var text = minutes >= 10 ? 'stale · no new lines for ' + minutes + 'm' : - (lastAt ? 'last line ' + (minutes ? minutes + 'm ago' : 'just now') : 'waiting for first line'); - // When stale, say whether the hive is still looking: a recent ingest - // means nothing was pushed, an old one means the feed itself is behind. - if (minutes >= 10 && lastIngestAt) { - var ingestMinutes = Math.floor(Math.max(0, Date.now() - lastIngestAt) / 60000); - text += ' · last ingest ' + (ingestMinutes ? ingestMinutes + 'm ago' : 'just now'); - } - freshness.textContent = text; - pausedLabel.textContent = paused() ? 'paused' : 'p / Space to pause'; - } - function caption(line){ return line.repo + '#' + line.pr + ' · ' + line.path; } - function prKey(line){ return line.repo + '#' + line.pr; } - function nextLine(key){ - if (!queue.length) queue = lines.slice(); - var at = 0; - for (var i = 0; key && i < queue.length; i++) if (prKey(queue[i]) === key) { at = i; break; } - return queue.splice(at, 1)[0] || null; - } - // Minimal keyword/string/comment/number colouring keyed on the extension; - // unknown extensions render in the palette colour. - function tokens(path, text){ - var ext = (/\.([^.\/]+)$/.exec(path || '') || [])[1]; - var lang = languages[extensions[ext ? ext.toLowerCase() : '']]; - if (!lang) return [{text: text, color: color}]; - var out = [], last = 0, match; - var pattern = /("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`[^`]*`?)|(\b\d[\w.]*)|([A-Za-z_$][\w$]*)|(\/\/|#)/g; - function push(t, c){ if (t) out.push({text: t, color: c}); } - while ((match = pattern.exec(text))) { - push(text.slice(last, match.index), color); - last = pattern.lastIndex; - if (match[4] === lang.comment) { push(text.slice(match.index), syntaxColors.comment); last = text.length; break; } - push(match[0], match[1] ? syntaxColors.string : match[2] ? syntaxColors.number : - match[3] && lang.words.has(match[0]) ? syntaxColors.keyword : color); - } - push(text.slice(last), color); - return out; - } - function openTab(line){ - var key = prKey(line), tab = null; - tabs.forEach(function(t){ if (t.key === key) tab = t; }); - if (!tab) { - tab = {key: key, rows: [], count: 0}; tabs.push(tab); - if (tabs.length > 6) tabs.shift(); - } - tab.path = line.path; - return tab; - } - function startTyping(line){ - typing = line ? {tab: openTab(line), line: line, chars: Array.from(line.line), typed: 0} : null; - } - function drawGhost(dt, now){ - if (!typing) startTyping(nextLine('')); - if (!typing) return; - typing.typed += dt * 40; - // A short beat at the end of each line before the next one starts. - if (typing.typed >= typing.chars.length + 4) { - var done = typing.tab; - done.count++; - done.rows.push({n: done.count, path: typing.line.path, text: typing.line.line}); - if (done.rows.length > 200) done.rows.shift(); - startTyping(nextLine(done.key)); - if (!typing) return; - } - var tab = typing.tab, top = 34, tabW = Math.min(240, width / Math.max(1, tabs.length)); - ctx.font = '13px monospace'; - tabs.forEach(function(t, i){ - ctx.fillStyle = t === tab ? '#0b2a16' : '#02140a'; - ctx.fillRect(i * tabW, 0, tabW - 2, 28); - ctx.fillStyle = t === tab ? color : muted; - ctx.fillText(t.path, i * tabW + 10, 19, tabW - 20); - }); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(typing.line), 10, 48, width - 20); - top = 56; - } - ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - 100) / rowH)); - var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; - tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ - var y = top + (i + 1) * rowH, col = 0; - ctx.fillStyle = muted; ctx.fillText(String(row.n), 10, y); - tokens(row.path, row.text).forEach(function(token){ - ctx.fillStyle = token.color; ctx.fillText(token.text, 60 + col * charW, y); - col += Array.from(token.text).length; - }); - if (row.current && Math.floor(now / 530) % 2 === 0) { ctx.fillStyle = color; ctx.fillRect(60 + col * charW, y - 14, 2, 18); } - }); - } - function emitTerminal(){ - var line = nextLine(''); - if (!line) return; - if (caption(line) !== termHead) { - termHead = caption(line); - if (captions) { - if (termRows.length) termRows.push({text: '', color: color}); - termRows.push({text: termHead, color: '#b8ccbb'}); - } - } - termRows.push({text: '+ ' + line.line, color: color}); - var keep = Math.ceil(height / rowH) + 4; - if (termRows.length > keep) termRows = termRows.slice(-keep); - } - function drawTerminal(dt){ - if (!termRows.length) emitTerminal(); - termClock += dt * 4; - while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - 100; - ctx.font = '16px monospace'; - termRows.forEach(function(row, i){ - var y = bottom - (termRows.length - 1 - i + termClock) * rowH; - if (y < -rowH || !row.text) return; - ctx.fillStyle = row.color; ctx.fillText(row.text, 10, y, width - 20); - }); - } - function staticPage(){ - list.replaceChildren(); - var latest = lines.slice(-60).reverse(); - if (page * 8 >= latest.length) page = 0; - latest.slice(page * 8, page * 8 + 8).forEach(function(line){ - var row = document.createElement('div'); - var label = document.createElement('small'); - label.textContent = caption(line); - var text = document.createElement('pre'); - text.textContent = line.line; - row.append(label, text); list.appendChild(row); - }); - } - function buildAtlas(){ - // Bounded by the same latest-line window as the renderer. No synthetic - // characters: every glyph in a column belongs to an incoming line. - glyphs.clear(); - lines.forEach(function(line){ Array.from(line.line).forEach(function(g){ - if (!glyphs.has(g)) glyphs.set(g, glyphs.size); - }); }); - atlas.width = 64 * cell; - atlas.height = Math.max(cell, Math.ceil(glyphs.size / 64) * cell); - var ac = atlas.getContext('2d'); - ac.font = '16px monospace'; ac.fillStyle = color; - glyphs.forEach(function(i, g){ ac.fillText(g, (i % 64) * cell, Math.floor(i / 64) * cell + 16); }); - } - function spawn(x){ - var line = lines[Math.floor(Math.random() * lines.length)]; - return {x: x, y: -Math.random() * height, speed: 25 + Math.random() * 65, - line: line, chars: Array.from(line.line)}; - } - function draw(now){ - frame = 0; - if (paused() || motion.matches || !enabled) return; - if (!previous) previous = now; - var elapsed = now - previous; - if (elapsed >= 1000 / fps) { - previous = now; - var dt = Math.min(elapsed, 100) / 1000 * speed; - ctx.fillStyle = effect === 'rain' ? 'rgba(0, 8, 4, 0.18)' : '#000804'; - ctx.fillRect(0, 0, width, height); - ctx.font = '16px monospace'; - if (lines.length && effect === 'ghost') drawGhost(dt, now); - else if (lines.length && effect === 'terminal') drawTerminal(dt); - else if (lines.length) { - var count = effect === 'rain' ? Math.ceil(width / cell) : 12; - while (drops.length < count) drops.push(spawn(effect === 'rain' ? drops.length * cell : Math.random() * width * 0.5)); - drops.forEach(function(drop, i){ - drop.y += drop.speed * dt; - if (drop.y > height + 40) { drops[i] = spawn(drop.x); return; } - if (effect === 'cascade') { - ctx.fillStyle = color; ctx.fillText(drop.line.line, drop.x, drop.y, width - drop.x); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(drop.line), drop.x, drop.y + 18, width - drop.x); - ctx.font = '16px monospace'; - } - } else if (drop.chars.length) { - var g = drop.chars[Math.floor(drop.y / cell + drop.chars.length * 100) % drop.chars.length]; - var index = glyphs.get(g); - if (index !== undefined) ctx.drawImage(atlas, (index % 64) * cell, Math.floor(index / 64) * cell, cell, cell, drop.x, drop.y, cell, cell); - ctx.fillStyle = '#effff2'; ctx.fillText(g, drop.x, drop.y + 16); - } - }); - } - } - frame = requestAnimationFrame(draw); - } - function sync(){ - if (frame) cancelAnimationFrame(frame); - frame = 0; previous = 0; - clearTimeout(pageTimer); pageTimer = 0; - updateLabels(); - canvas.hidden = motion.matches || !enabled; - list.hidden = !motion.matches || !enabled; - if (!enabled || paused()) return; - if (motion.matches) { - staticPage(); - pageTimer = setTimeout(function(){ page++; sync(); }, 15000); - } else frame = requestAnimationFrame(draw); - } - pull = function(){ - if (loading) { pending = true; return; } - loading = true; pending = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) - .then(function(response){ - if (response.status === 404) { clearContent('Matrix mode is not enabled on this hive'); return null; } - if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read Matrix lines'); return null; } - if (!response.ok) throw new Error('Matrix pull failed'); - return response.json(); - }).then(function(data){ - if (!data) return; - var incoming = (Array.isArray(data.lines) ? data.lines : []).filter(function(line){ return typeof line.line === 'string'; }); - var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; replace the old backlog. - if (seq < lastSeq) { lines = []; drops = []; resetText(); } - if (seq !== lastSeq && incoming.length) { - var at = Date.parse(incoming[incoming.length - 1].at); - lastAt = Number.isFinite(at) ? at : Date.now(); - } - lastSeq = seq; - var ingestAt = Date.parse(data.last_ingest_at); - lastIngestAt = Number.isFinite(ingestAt) ? ingestAt : 0; - lines = lines.concat(incoming).slice(-120); - queue = queue.concat(incoming).slice(-120); - enabled = true; - notice.textContent = lines.length ? '' : 'Waiting for pushed lines…'; - if (!motion.matches) buildAtlas(); - sync(); - }).catch(function(){ clearContent('Matrix lines unavailable · retrying'); }) - .finally(function(){ loading = false; if (pending) pull(); }); - }; - document.addEventListener('visibilitychange', function(){ sync(); if (!document.hidden) pull(); }); - document.addEventListener('keydown', function(event){ - if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || - /INPUT|TEXTAREA|SELECT/.test(event.target.tagName) || event.target.isContentEditable) return; - if (event.key === 'p' || event.key === 'P' || event.code === 'Space') { - event.preventDefault(); manualPause = !manualPause; sync(); - } - }); - motion.addEventListener('change', function(){ - ctx.clearRect(0, 0, width, height); - if (!motion.matches) buildAtlas(); - sync(); - }); - window.addEventListener('resize', resize); - resize(); sync(); pull(); - // Recover from missed nudges, endpoint activation and transient failures. - if (typeof dashboardSetInterval === 'function') { - dashboardSetInterval('matrix-poll', function(){ updateLabels(); if (!document.hidden) pull(); }, 30000); - } - }; -})(); diff --git a/src/pkg/dashboard/static-src/js/progressive.js b/src/pkg/dashboard/static-src/js/progressive.js new file mode 100644 index 0000000000..e2e25eb330 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/progressive.js @@ -0,0 +1,159 @@ + const DASHBOARD_BACKGROUND_CONCURRENCY = 2; + const DASHBOARD_IDLE_TIMEOUT_MS = 1000; + const DASHBOARD_YIELD_MS = 32; + const DASHBOARD_BACKGROUND_DELAY_MS = 350; + const DASHBOARD_TASK_SECTIONS = Object.freeze({ + 'backend-discovery': ['debug-section'], + 'stat-sources': ['agents-section'], + 'cost': ['cost-panel'], + 'hive-advice': ['advisory-section'], + 'acmm-reco': ['advisory-section'], + 'lifecycle': ['advisory-section'], + 'pr-throughput': ['pr-throughput-section'], + 'approvals': ['approvals-section'], + 'fact-history': ['knowledge-section'], + 'overview-kpi-history': ['overview-section'], + 'history': ['overview-section', 'repos-section'], + 'budget-ignore': ['repos-section'], + 'budget-history': ['governor'], + 'nous-status': ['nous-section'], + 'public-knowledge': ['knowledge-section'], + 'knowledge-stats': ['knowledge-section'], + 'audit-log': ['audit-section'], + 'review-queue': ['review-queue-section'], + 'review-pipeline': ['review-queue-section'], + 'stage-tracker': ['activity-monitor-section'], + 'contributors': ['contributors-section'], + 'leaderboard': ['contributors-section'], + 'git-version': ['debug-section'], + 'acmm-evaluation': ['acmm-eval-section'], + 'version-check': ['debug-section'], + 'version-reload-check': ['debug-section'], + 'weekly-trends': ['overview-section'], + 'timeline': ['governor'], + 'agent-logs': ['logs-section'], + 'debug-section': ['debug-section'], + 'chat-capabilities': [], + 'chat-presence': [], + 'welcome-gh-auth': [], + 'welcome-claude-auth': [], + 'gh-auth-banner': [], + }); + const _dashboardBackgroundJobs = new Map(); + const _dashboardRenderJobs = new Map(); + let _dashboardBackgroundRunning = 0; + let _dashboardBackgroundScheduled = false; + let _dashboardRenderScheduled = false; + let _dashboardBackgroundReady = false; + + function dashboardWorkPriority(sections) { + let priority = 2; + for (const id of sections || []) { + if (window.location.hash === '#section-' + id) return 0; + const el = document.getElementById(id); + if (!el || !el.getClientRects().length) continue; + const rect = el.getBoundingClientRect(); + if (rect.bottom >= 0 && rect.top <= window.innerHeight) priority = 1; + } + return priority; + } + function dashboardNextWork(jobs) { + let next; + let priority = Infinity; + for (const job of jobs.values()) { + if (job.running) continue; + const rank = dashboardWorkPriority(job.sections); + if (rank < priority) { next = job; priority = rank; } + } + return next; + } + function dashboardIdle(callback) { + if (typeof window.requestIdleCallback === 'function') { + window.requestIdleCallback(callback, { timeout: DASHBOARD_IDLE_TIMEOUT_MS }); + } else { + setTimeout(callback, DASHBOARD_YIELD_MS); + } + } + function dashboardWakeBackground() { + if (!_dashboardBackgroundReady || document.hidden || _dashboardBackgroundScheduled || + _dashboardBackgroundRunning >= DASHBOARD_BACKGROUND_CONCURRENCY || + !dashboardNextWork(_dashboardBackgroundJobs)) return; + _dashboardBackgroundScheduled = true; + dashboardIdle(function() { + _dashboardBackgroundScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardBackgroundJobs); + if (!job) return; + job.running = true; + _dashboardBackgroundRunning++; + function finished() { + _dashboardBackgroundJobs.delete(job.key); + _dashboardBackgroundRunning--; + dashboardWakeBackground(); + } + Promise.resolve().then(job.fn).then(function(value) { + finished(); job.resolve(value); + }, function(err) { + finished(); job.reject(err); + }); + dashboardWakeBackground(); + }); + } + // Keep a slot through JSON decoding and rendering, not just response headers. + // Repeated timer ticks share the same flight rather than adding stale work. + function dashboardScheduleWork(key, fn) { + const existing = _dashboardBackgroundJobs.get(key); + if (existing) return existing.promise; + let resolve, reject; + const promise = new Promise(function(ok, fail) { resolve = ok; reject = fail; }); + _dashboardBackgroundJobs.set(key, { + key, fn, promise, resolve, reject, running: false, + sections: DASHBOARD_TASK_SECTIONS[key] || [], + }); + dashboardWakeBackground(); + return promise; + } + function dashboardWakeRender() { + if (document.hidden || _dashboardRenderScheduled || !_dashboardRenderJobs.size) return; + _dashboardRenderScheduled = true; + dashboardIdle(function() { + _dashboardRenderScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardRenderJobs); + if (!job) return; + _dashboardRenderJobs.delete(job.key); + if (job.snapshot && !dashboardStatusCanRender(job.snapshot)) { + dashboardWakeRender(); + return; + } + const anchor = typeof captureScrollAnchor === 'function' ? captureScrollAnchor() : null; + try { + job.fn(); + job.sections.forEach(function(id) { + if (typeof applySectionCollapse === 'function') applySectionCollapse(id); + }); + if (typeof refreshDashboardSectionSummaries === 'function') refreshDashboardSectionSummaries(); + } catch (err) { + console.error('dashboard render ' + job.key + ' failed', err); + } finally { + if (anchor && typeof restoreScrollAnchor === 'function' && + (typeof _hashScrollPending === 'undefined' || !_hashScrollPending)) restoreScrollAnchor(anchor); + dashboardWakeRender(); + } + }); + } + // Latest snapshot wins. Paint one section per idle turn so input and + // navigation can run between large cards, even when SSE arrives in a burst. + function dashboardRenderSection(key, sections, fn, snapshot) { + _dashboardRenderJobs.set(key, { key, sections, fn, snapshot }); + dashboardWakeRender(); + } + function dashboardProgressiveWake() { + dashboardWakeBackground(); + dashboardWakeRender(); + } + document.addEventListener('visibilitychange', dashboardProgressiveWake); + setTimeout(function() { + _dashboardBackgroundReady = true; + dashboardWakeBackground(); + }, DASHBOARD_BACKGROUND_DELAY_MS); diff --git a/src/pkg/dashboard/static-src/js/reader.js b/src/pkg/dashboard/static-src/js/reader.js new file mode 100644 index 0000000000..fc03ec7729 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/reader.js @@ -0,0 +1,248 @@ +// Code activity reader (#16475): changed regions as readable paragraphs on +// the kiosk. Opt-in like Matrix and fed by the same authorized pull endpoint +// (the shared SSE stream only nudges). Code is always set with textContent. +(function(){ + 'use strict'; + var pull = function(){}; + window.hiveReaderAttach = function(source){ + if (!window.HIVE_READER) return; + source.addEventListener('code-lines', function(){ pull(); }); + source.addEventListener('open', function(){ pull(); }); + }; + window.hiveReaderStart = function(){ + if (!window.HIVE_READER || document.getElementById('hive-reader')) return; + // Cards kept on screen, regions waiting to be read, and how long one + // paragraph stays in focus before the next arrives. + var MAX_CARDS = 32, MAX_LINES = 1200, MAX_BYTES = 256 * 1024, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; + var root = document.createElement('main'); + root.id = 'hive-reader'; + root.setAttribute('aria-label', 'Code activity reader'); + document.body.appendChild(root); + function element(tag, className, text, parent){ + var el = document.createElement(tag); + el.className = className; + if (text) el.textContent = text; + (parent || root).appendChild(el); + return el; + } + var bar = element('div', 'reader-bar'); + element('span', 'reader-source', 'Source: changes pushed by hive · public allowlisted repos', bar); + var status = element('span', 'reader-status', 'Waiting for pushed changes…', bar); + status.setAttribute('role', 'status'); + var button = element('button', 'reader-pause', 'Pause', bar); + button.setAttribute('type', 'button'); + button.setAttribute('aria-pressed', 'false'); + button.setAttribute('title', 'Pause or resume (P / Space)'); + var replay = element('button', 'reader-pause reader-replay', 'Replay buffered snapshot', bar); + replay.setAttribute('type', 'button'); + replay.setAttribute('title', 'Explicit replay of retained changes; off by default'); + var freshness = element('span', 'reader-freshness', 'Source has not completed an ingest pass', bar); + var scroller = element('div', 'reader-scroll'); + scroller.setAttribute('tabindex', '0'); + var feed = element('div', 'reader-feed', '', scroller); + var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); + var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var retained = [], retainedLines = 0, retainedBytes = 0, epoch = '', snapshotThrough = null, contentGeneration = 0; + var enabled = false, manualPause = false, loading = false, again = false, problem = ''; + function paused(){ return manualPause || document.hidden; } + // The source supplies indivisible regions. Never infer a paragraph from + // neighbouring sequence numbers or merge across context/page boundaries. + function group(regions){ + regions.forEach(function(region){ + if (!region || !Array.isArray(region.lines) || !region.lines.length) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-' || line.op === ' '); })) return; + var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); + if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; + var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, + stage: 'Pushed PR', at: region.at, lines: region.lines, size: size, + delivery: Number(region.seq) <= snapshotThrough ? 'Buffered snapshot' : 'Newly received checkpoint'}; + retained.push(item); pending.push(item); + retainedLines += item.lines.length; retainedBytes += size; + while (retainedLines > MAX_LINES || retainedBytes > MAX_BYTES) { + var victim = retained.findIndex(function(r){ return r !== current; }); + var old = retained.splice(victim, 1)[0]; + retainedLines -= old.lines.length; retainedBytes -= old.size; + pending = pending.filter(function(r){ return r !== old; }); + if (old.node) { feed.removeChild(old.node); old.node = null; } + if (current === old) current = null; + } + }); + } + function prLink(region){ + var url = typeof region.prURL === 'string' ? region.prURL : ''; + if (/^https:\/\/[^\s"'<>]+\/pull\/\d+$/.test(url)) return url; + if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { + return 'https://github.com/' + region.repo + '/pull/' + region.pr; + } + return ''; + } + function observed(at){ + var ms = Date.parse(at); + if (!Number.isFinite(ms)) return {iso: '', text: 'observed time unknown'}; + var d = new Date(ms); + // The shared helper honours the dashboard time-zone preference. + var shown = typeof formatDashboardDateTime === 'function' ? formatDashboardDateTime(d) : d.toISOString(); + return {iso: d.toISOString(), text: 'observed ' + shown}; + } + function card(region){ + var article = document.createElement('article'); + article.className = 'reader-card'; + var meta = element('header', 'reader-meta', '', article); + var href = prLink(region); + var repo = element(href ? 'a' : 'span', 'reader-repo', region.repo + (region.pr > 0 ? ' #' + region.pr : ''), meta); + if (href) { + repo.href = href; + repo.setAttribute('target', '_blank'); + repo.setAttribute('rel', 'noopener noreferrer'); + } + element('span', 'reader-file', region.path, meta); + element('span', 'reader-stage', region.stage, meta); + element('span', 'reader-delivery', region.delivery, meta); + var when = observed(region.at); + var time = element('time', 'reader-time', when.text, meta); + if (when.iso) time.setAttribute('datetime', when.iso); + var diff = element('pre', 'reader-diff', '', article); + region.lines.forEach(function(line){ + var removed = line.op === '-', context = line.op === ' '; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : context ? 'reader-context' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : context ? ' ' : '+ ') + line.line + '\n'; + }); + return article; + } + function dwell(region){ return Math.min(MAX_DWELL, BASE_DWELL + region.lines.length * LINE_DWELL); } + // Drop the oldest cards and keep the visible text where it was. + function trim(){ + while (feed.children.length > MAX_CARDS) { + var first = feed.children[0], height = first.offsetHeight || 0; + feed.removeChild(first); + retained.forEach(function(r){ if (r.node === first) r.node = null; }); + scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); + } + } + function reveal(region, scroll){ + region.node = card(region); + feed.appendChild(region.node); + trim(); + current = region; + readUntil = Date.now() + dwell(region); + if (scroll && region.node.scrollIntoView) region.node.scrollIntoView({block: 'start', behavior: motion.matches ? 'auto' : 'smooth'}); + } + function updateStatus(){ + var text = problem; + if (!text && enabled) { + if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; + else text = current ? 'Caught up with available checkpoints · holding' : 'No buffered checkpoints · source may still be warming or filtering'; + } + if (paused()) text = 'paused' + (text ? ' · ' + text : ''); + status.textContent = text; + button.textContent = manualPause ? 'Resume' : 'Pause'; + button.setAttribute('aria-pressed', manualPause ? 'true' : 'false'); + } + function stop(){ clearTimeout(timer); timer = 0; } + function advance(){ + timer = 0; + if (!enabled || paused() || motion.matches) return; + // Quiet hold when caught up: no replay, no filler, nothing scheduled. + if (pending.length) { + reveal(pending.shift(), true); + timer = setTimeout(advance, dwell(current)); + } + updateStatus(); + } + // Starts the next reveal once the current paragraph's dwell ends; never + // restarts a running dwell, so incoming work cannot interrupt reading. + function schedule(fresh){ + if (timer || !enabled || paused()) { updateStatus(); return; } + if (motion.matches) { + // Static and scrollable: everything is shown, nothing scrolls by itself. + while (pending.length) reveal(pending.shift(), false); + updateStatus(); + return; + } + if (fresh && current) { + readUntil = Date.now() + dwell(current); + if (current.node && current.node.scrollIntoView) current.node.scrollIntoView({block: 'start', behavior: 'smooth'}); + } + var wait = readUntil - Date.now(); + if (pending.length && wait <= 0) { advance(); return; } + if (pending.length) timer = setTimeout(advance, wait); + updateStatus(); + } + function setPaused(value){ + if (manualPause === value) return; + manualPause = value; + stop(); + if (!manualPause) schedule(true); + updateStatus(); + } + function inspect(){ setPaused(true); } + function clearContent(message){ + contentGeneration++; + stop(); + enabled = false; pending = []; retained = []; retainedLines = 0; retainedBytes = 0; + current = null; lastSeq = 0; snapshotThrough = null; problem = message; + feed.replaceChildren(); + updateStatus(); + } + pull = function(){ + if (document.hidden) return; + if (loading) { again = true; return; } + loading = true; again = false; + var requestGeneration = contentGeneration; + fetch('/api/matrix/lines?since=' + lastSeq + '&format=regions', {cache: 'no-store', credentials: 'same-origin'}) + .then(function(response){ + if (requestGeneration !== contentGeneration || document.hidden) return null; + if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } + if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } + if (!response.ok) throw new Error('reader pull failed'); + return response.json(); + }).then(function(data){ + if (!data || requestGeneration !== contentGeneration || document.hidden) return; + var seq = Number(data.seq) || 0; + if (data.epoch !== epoch || seq < lastSeq) { + clearContent(''); epoch = data.epoch; + } + if (snapshotThrough === null) snapshotThrough = Number(data.latest) || 0; + group(Array.isArray(data.regions) ? data.regions : []); + freshness.textContent = data.last_ingest_at + ? 'Last source pass: ' + data.last_ingest_at + ' · next expected in ' + (data.next_ingest_in_s || 0) + 's' + : 'Source has not completed an ingest pass · empty does not mean no work'; + if (seq < Number(data.latest)) again = true; + lastSeq = seq; + enabled = true; problem = ''; + schedule(false); + }).catch(function(){ clearContent('Code activity unavailable · retrying'); }) + .finally(function(){ loading = false; if (again) pull(); }); + }; + replay.addEventListener('click', function(){ + if (!enabled || !retained.length) return; + stop(); feed.replaceChildren(); current = null; readUntil = 0; + retained.forEach(function(r){ r.node = null; r.delivery = 'Replay · buffered snapshot'; }); + pending = retained.slice(); schedule(false); + }); + button.addEventListener('click', function(){ setPaused(!manualPause); }); + scroller.addEventListener('wheel', inspect, {passive: true}); + scroller.addEventListener('touchstart', inspect, {passive: true}); + document.addEventListener('visibilitychange', function(){ + if (document.hidden) { clearContent('Hidden · buffered code cleared'); return; } + pull(); + }); + document.addEventListener('keydown', function(event){ + var target = event.target || {}; + if (event.ctrlKey || event.metaKey || event.altKey || + /INPUT|TEXTAREA|SELECT/.test(target.tagName) || target.isContentEditable) return; + if (NAV_KEYS.indexOf(event.key) >= 0) { inspect(); return; } + if (event.repeat) return; + if (event.key === 'p' || event.key === 'P' || (event.code === 'Space' && target.tagName !== 'BUTTON')) { + event.preventDefault(); setPaused(!manualPause); + } + }); + motion.addEventListener('change', function(){ stop(); schedule(false); }); + updateStatus(); pull(); + // Recover from missed nudges, endpoint activation and transient failures. + if (typeof dashboardSetInterval === 'function') { + dashboardSetInterval('reader-poll', function(){ if (!document.hidden) pull(); }, 30000); + } + }; +})(); diff --git a/src/pkg/dashboard/static-src/js/refresh.js b/src/pkg/dashboard/static-src/js/refresh.js index fb3a0c7b52..63be5f3573 100644 --- a/src/pkg/dashboard/static-src/js/refresh.js +++ b/src/pkg/dashboard/static-src/js/refresh.js @@ -140,27 +140,22 @@ const n = Number(minSeq); if (Number.isFinite(n) && n > _statusSeqFloor) _statusSeqFloor = n; } + // A snapshot accepted before a mutation can become stale while queued. + function dashboardStatusCanRender(data) { + return data.statusSeq == null || + (data.statusSeq >= _statusSeqFloor && data.statusSeq >= _lastStatusSeq && + (!data.statusInstance || !_statusInstance || data.statusInstance === _statusInstance)); + } var SCROLL_SETTLE_DELAY_MS = 500; var _deferredLoadPromise = null; function _afterPaint(callback) { _hashScrollPending = true; - if (_deferredLoadPromise) { - _deferredLoadPromise.then(function() { - requestAnimationFrame(function() { - requestAnimationFrame(function() { - callback(); - setTimeout(function() { _hashScrollPending = false; }, 200); - }); - }); - }); - } else { + requestAnimationFrame(function() { requestAnimationFrame(function() { - requestAnimationFrame(function() { - setTimeout(callback, SCROLL_SETTLE_DELAY_MS); - setTimeout(function() { _hashScrollPending = false; }, 500); - }); + setTimeout(callback, SCROLL_SETTLE_DELAY_MS); + setTimeout(function() { _hashScrollPending = false; }, SCROLL_SETTLE_DELAY_MS); }); - } + }); } const NAVBAR_CLOCK_TICK_MS = 1000; @@ -485,8 +480,8 @@ _lastStatusSeq = data.statusSeq; } if (typeof data.matrixEnabled === 'boolean') { - const matrixTab = document.getElementById('oc-matrix-tab'); - if (matrixTab) matrixTab.hidden = !data.matrixEnabled; + const codeActivityTab = document.getElementById('oc-matrix-tab'); + if (codeActivityTab) codeActivityTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); @@ -505,7 +500,9 @@ applyDashboardFeatureVisibility(); // The tracker's hop cue reads which agent is on which item from this // payload; redraw the rows when that set changes (no extra fetch). - if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') renderStageTracker(); + if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') { + dashboardRenderSection('tracker-workers', ['activity-monitor-section'], () => renderStageTracker()); + } if (typeof refreshThroughputSLA === 'function') refreshThroughputSLA(); if (window._acmmOverride) { if (data.acmmLevel === window._acmmOverride.level) { @@ -543,26 +540,30 @@ renderSystemAlerts(data.systemAlerts || []); if (!_dropdownOpen && !_configModalOpen) { applyPinOverrides(data.agents || []); - renderAgents(data.agents || []); - renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(data.agents || []); + }, data); + dashboardRenderSection('governor', ['governor'], () => { + if (!_dropdownOpen && !_configModalOpen) renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + }, data); // Keep the focused agent detail in sync with fresh payloads — its // fast path only rebuilds when the config fingerprint changes. if (_ocSelectedAgent) ocRenderAgentDetail(); } - renderTokens(data.tokens || {}); - renderAdvisoryDigest(data.advisoryDigest || null); - renderRepos(data.repos || []); - renderRuns(dashboardRunsFromStatus(data)); - renderSwarm(data.swarm || {}); + dashboardRenderSection('tokens', ['token-panel'], () => renderTokens(data.tokens || {}), data); + dashboardRenderSection('advisory', ['advisory-section'], () => renderAdvisoryDigest(data.advisoryDigest || null), data); + dashboardRenderSection('repos', ['repos-section', 'overview-section'], () => renderRepos(data.repos || []), data); + dashboardRenderSection('runs', ['runs-section'], () => renderRuns(dashboardRunsFromStatus(data)), data); + dashboardRenderSection('swarm', ['repos-section'], () => renderSwarm(data.swarm || {}), data); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); renderPlatform(data.platform || null); - renderHiveAdvice(data.hiveAdvice || null); - renderFleetReport(data.fleetReport || null); - renderSystemGauges(data.systemResources || null); + dashboardRenderSection('hive-advice', ['advisory-section'], () => renderHiveAdvice(data.hiveAdvice || null), data); + dashboardRenderSection('fleet-report', ['advisory-section'], () => renderFleetReport(data.fleetReport || null), data); + dashboardRenderSection('system-gauges', ['debug-section'], () => renderSystemGauges(data.systemResources || null), data); ocUpdateSidebarAgents(); - renderDebugSection(); - renderFAQ(); + dashboardRenderSection('debug', ['debug-section'], () => renderDebugSection(), data); + dashboardRenderSection('faq', ['faq-section'], () => renderFAQ(), data); initializeDashboardSectionCards(); // Restore persisted collapsed state for all collapsible sections const COLLAPSIBLE_SECTION_IDS = [ diff --git a/src/pkg/dashboard/static-src/js/review-queue.js b/src/pkg/dashboard/static-src/js/review-queue.js index b9629db787..65a9f63bf5 100644 --- a/src/pkg/dashboard/static-src/js/review-queue.js +++ b/src/pkg/dashboard/static-src/js/review-queue.js @@ -32,6 +32,14 @@ return Math.floor(h / 24) + 'd'; } + function fixerQueueHint(e) { + var position = Number(e && e.fixer_queue_position); + if (!Number.isInteger(position) || position < 1) return ''; + var ahead = Number(e.fixer_queue_ahead); + if (!Number.isInteger(ahead) || ahead < 0) ahead = position - 1; + return 'fixer queued, ' + ahead + ' ahead'; + } + function renderReviewQueueEntry(e) { var meta = reviewQueuePriorityMeta(e.priority); var title = String(e.title || ''); @@ -47,6 +55,8 @@ if (e.confidence_band) metaBits.push(esc(String(e.confidence_band))); metaBits.push(reviewQueueAgeLabel(e.age_hours) + ' old'); if (e.held) metaBits.push('held'); + var fixerHint = fixerQueueHint(e); + if (fixerHint) metaBits.push('<span class="hf-label hf-label-hold">' + esc(fixerHint) + '</span>'); // Hive-owned stage/author labels (#12429) tell at a glance where the // PR sits in the pipeline; other labels stay out of the meta line. // stage/stalled means "no activity by anyone but the hive for the diff --git a/src/pkg/dashboard/static-src/js/shimmy-handlers.js b/src/pkg/dashboard/static-src/js/shimmy-handlers.js index b8dfb38f3c..ebd8dbb5b7 100644 --- a/src/pkg/dashboard/static-src/js/shimmy-handlers.js +++ b/src/pkg/dashboard/static-src/js/shimmy-handlers.js @@ -29,7 +29,7 @@ } triggerAttentionShimmy(); - checkClaudeAuth(); + dashboardScheduleWork('welcome-claude-auth', checkClaudeAuth).catch(console.error); var CLAUDE_AUTH_CHECK_INTERVAL_MS = 60000; dashboardSetInterval('welcome-claude-auth', checkClaudeAuth, CLAUDE_AUTH_CHECK_INTERVAL_MS); @@ -87,59 +87,38 @@ sendPresencePing(); })(); - // Deferred initialization — non-critical fetches staggered after first paint. - // Each entry returns a promise so anchor scrolling can wait for layout to settle. - const DEFERRED_INIT_DELAY_MS = 1500; - const DEFERRED_STAGGER_MS = 200; + // Visible sections win; slow background panels cannot delay navigation. + const DEFERRED_INIT_DELAY_MS = DASHBOARD_BACKGROUND_DELAY_MS; _deferredLoadPromise = new Promise(function(resolveAll) { setTimeout(() => { const deferred = [ - () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig()), - () => fetchFactHistory(), - () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); }), - () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); }), - () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(() => {}), - () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); }), - () => ensureNousPolling(), - () => fetchPublicKnowledgeSetting(), - () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); }), - () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); }), - () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }), - () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); }), - () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); }), - () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); }), - () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); }), - () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); }), - () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); }), - () => Promise.resolve(startVersionCheck()), - () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}).then(() => { dashboardSetInterval('weekly-trends', () => { fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}); }, TREND_REFRESH_MS); }), - () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); }), - () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); }), + ['backend-discovery', () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig())], + ['fact-history', () => fetchFactHistory()], + ['overview-kpi-history', () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); })], + ['history', () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); })], + ['budget-ignore', () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(console.error)], + ['budget-history', () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); })], + ['nous-status', () => ensureNousPolling()], + ['public-knowledge', () => fetchPublicKnowledgeSetting()], + ['knowledge-stats', () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); })], + ['audit-log', () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); })], + ['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })], + ['review-pipeline', () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); })], + ['stage-tracker', () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); })], + ['contributors', () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); })], + ['leaderboard', () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); })], + ['git-version', () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); })], + ['acmm-evaluation', () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); })], + ['version-check', () => Promise.resolve(startVersionCheck())], + ['weekly-trends', () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error).then(() => { dashboardSetInterval('weekly-trends', () => { return fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error); }, TREND_REFRESH_MS); })], + ['timeline', () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); })], + ['agent-logs', () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); })], ]; - // `Promise.resolve().then(fn)` rather than `fn()`, so ONE bad entry - // cannot strand the whole chain (#6581). `fn()` was called bare inside - // the setTimeout callback, so an entry that threw synchronously — or - // returned undefined and had `.then` called on it, which is what - // fetchTimeline did — threw out of the callback with nothing to catch - // it. That entry's promise then never settled, so Promise.all never - // settled, so resolveAll never ran and _deferredLoadPromise stayed - // pending for the life of the page. _afterPaint awaits it, so first- - // load view restoration (making #oc-agent-detail active, navigating to - // a saved section) silently never happened. - // - // Wrapping turns a synchronous throw into a rejection, which - // `.then(resolve, resolve)` already handles: the entry is recorded as - // finished-badly instead of never finishing, and the other twelve - // entries still complete. The throw is still reported below rather - // than swallowed — the point is that one broken entry degrades to one - // broken feature, not to a dashboard that never finishes initialising. - const allDone = deferred.map((fn, i) => - new Promise(resolve => setTimeout(() => { - Promise.resolve().then(fn).then(resolve, err => { - console.error('deferred init entry ' + i + ' failed', err); - resolve(); - }); - }, i * DEFERRED_STAGGER_MS)) + // A synchronous throw must not strand the other panels (#6581). + const allDone = deferred.map(([key, fn]) => + dashboardScheduleWork(key, () => Promise.resolve().then(fn)).catch(err => { + console.error('deferred init ' + key + ' failed', err); + }) ); Promise.all(allDone).then(resolveAll); }, DEFERRED_INIT_DELAY_MS); @@ -353,4 +332,3 @@ gh84: function (event, A) { markSentinelDirty('exemptLogins', parseSecurityList(this.value)); }, gh85: function (event, A) { markSentinelDirty('repos', parseSecurityList(this.value)); }, }; - diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 48c6349609..92f1037d29 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -28,7 +28,7 @@ if (_eventSource) { _eventSource.onerror = null; _eventSource.onmessage = null; _eventSource.close(); _eventSource = null; } const source = new EventSource('/api/events'); _eventSource = source; - if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); + if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; const conn = document.getElementById('conn'); @@ -113,10 +113,14 @@ const lastData = window._lastStatus || {}; if (lastData.agents) { applyPinOverrides(lastData.agents); - renderAgents(lastData.agents); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(lastData.agents); + }); // Keep the cost table's "running agents" column live as agents // switch models or pause/resume between cost polls. - if (_lastCost) renderCost(_lastCost); + if (_lastCost) dashboardRenderSection('cost', ['cost-panel'], () => { + if (_lastCost) renderCost(_lastCost); + }); } ocUpdateFocusedState(); const _lvl = (lastData.acmmLevel != null) ? lastData.acmmLevel : 0; diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 07d9e0a5b0..7752bc80bb 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -21,15 +21,15 @@ } // Pure: the DCO caveat the merge confirmations print BEFORE acting // when the stage record counted unsigned commits on the head (#15136): - // merging as-is then fails where DCO is required; re-authoring is the - // separate choice. + // merging as-is then fails where DCO is required; adopting as a hive + // PR is the separate choice. function stageTrackerDCOCaveat(items) { const rows = (Array.isArray(items) ? items : [items]).filter(it => it && Number(it.dco_unsigned) > 0); if (!rows.length) return ''; const it = rows[0]; const total = Number(it.dco_total) || 0; const of = total > 0 ? ' of ' + total + ' commit' + (total === 1 ? '' : 's') : ' commit' + (Number(it.dco_unsigned) === 1 ? '' : 's'); - return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Re-author as hive PR" is the separate choice for that; approving does not re-author.'; + return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Adopt as hive PR" is the separate choice for that; approving does not adopt.'; } const STAGE_TRACKER_ACTION_LABELS = { 'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide — all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', @@ -38,7 +38,6 @@ 'decide:close-issue': 'Close issue', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', - 'decide:re-author': 'Re-author as hive PR', 'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', @@ -51,8 +50,11 @@ // merger or owner only, like POST .../queue-automerge. const STAGE_TRACKER_MERGE_ACTIONS = ['decide:queue-merge', 'decide:merge-now']; // Generic items every row has; a server-named decision option with one - // of these ids is not repeated at the top of the menu. - const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt', 'decide:close-issue']; + // of these ids is not repeated at the top of the menu. `decide:adopt` + // is not generic: a row offers it either from the nudge (`adoption`) + // or as a server decision option (a contributor PR's DCO / fixer + // exhaustion, where it replaced "re-author"), never both. + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:close-issue']; const _stageTrackerCloseIssueBusy = new Set(); // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / @@ -259,7 +261,11 @@ const out = []; // First: the hive decides as the owner's delegate (policy + rails on // the server; recorded as a human decision with an audit marker). - out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled, why }); + // The server may rule delegation out for this row (a capability gap + // no decision closes — hivecommons/docs#612); its reason wins. + const served = stageTrackerServerDelegate(item); + const delegateOff = !!served && served.enabled === false; + out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled: enabled && !delegateOff, why: delegateOff ? (served.reason_if_disabled || 'The hive cannot decide this one') : why }); if (item.kind === 'pr') { out.push({ id: 'decide:approve', label: 'Approve (/lgtm + /approve)', enabled, why }); out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); @@ -273,6 +279,11 @@ out.push({ id: 'decide:close-wontfix', label: "Close as won't-fix…", enabled, why, danger: true }); return out; } + // Pure: the server's decide:delegate option on the row, or null. + function stageTrackerServerDelegate(item) { + const opts = item && item.decision_needed && Array.isArray(item.decision_needed.options) ? item.decision_needed.options : []; + return opts.find(o => o && o.action === 'decide:delegate') || null; + } // Pure: the operator note for labels the row's stage has outrun // (stale_labels: a needs-triage still on a claimed issue, which the // reconciler removes on its next pass — hivecommons/hive#14586). '' when none. @@ -455,7 +466,7 @@ // A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). if (typeof stageTrackerBlockerActions === 'function') for (const a of stageTrackerBlockerActions(item, ctx)) out.push(a); - if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item)) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); + if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item) && !out.some(a => a.id === 'decide:adopt')) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); // A PR waiting on a contributor's clanker offers Adopt now and Reroute // (hivecommons/hive#15038); each disabled with the server's reason. if (typeof stageTrackerTakeoverActions === 'function') for (const a of stageTrackerTakeoverActions(item, ctx, ctx.nowMs)) out.push(a); @@ -485,6 +496,15 @@ if (lead) return lead; const decide = actions.find(a => a.id === 'decide'); const safe = decide && Array.isArray(decide.submenu) ? decide.submenu.filter(x => x && !x.danger) : []; + // The server ruled delegation out (a capability gap): the first + // enabled, non-destructive blocker option leads instead — the + // person's actual move (open App settings, re-check permissions), + // not a greyed "Let hive decide" (hivecommons/docs#612). + const served = stageTrackerServerDelegate(item); + if (served && served.enabled === false) { + const b = stageTrackerBlockerActions(item, ctx).find(x => x.enabled && !x.danger); + if (b) return Object.assign({}, b, { target: (decide && decide.target) || { kind: item.kind, number: item.number, repo: item.repo } }); + } if (safe.length) { const o = safe.find(x => x.enabled) || safe[0]; const enabled = !!decide.enabled && !!o.enabled; @@ -557,12 +577,50 @@ const sub = typeof stageTrackerLinkedPRItem === 'function' ? stageTrackerLinkedPRItem(item, lp) : null; return sub && stageTrackerLeadAction(sub, ctx) ? null : a; } - // The inline lead button for a row: a real <button> carrying the same - // id, hint and enable/disable reason as the ⋯ menu entry it mirrors; + // Pure: the second inline pill of a row parked on a human decision — + // the Decide… submenu's "Let hive decide" (decide:delegate), carrying + // the decide target and enable reason the way stageTrackerLeadAction's + // fallback does — when the server's lead is another verb (Re-author, + // Merge now…). A row saw only "Re-author" and asked where "Let hive + // decide" went (hivecommons/hive#16265 / #16456): the ⋯ menu is + // invisible, so both stand on the row. null when the lead already is + // delegate, the row has no human decision, or the lead is a passive chip. + function stageTrackerLeadCompanion(item, ctx, lead) { + if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; + const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const human = !!(dec && dec.item && dec.item.decision_needed) || !!item.decision_needed || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + if (!human) return null; + const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); + const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; + if (!o) return null; + const enabled = !!decide.enabled && !!o.enabled; + return Object.assign({}, o, { target: decide.target, enabled, why: enabled ? '' : (decide.enabled ? o.why : decide.why), hint: STAGE_TRACKER_ACTION_CONSEQUENCES['decide:delegate'], companion: true }); + } + // Pure: the inline pills a row renders — its lead, then (a row parked + // on a human decision whose lead is not delegate) "Let hive decide". + function stageTrackerLeadActionsOnRow(item, ctx, subRows) { + const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!a) return []; + const companion = stageTrackerLeadCompanion(item, ctx, a); + return companion ? [a, companion] : [a]; + } + // The inline lead button(s) for a row: real <button>s carrying the same + // id, hint and enable/disable reason as the ⋯ menu entries they mirror; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. function stageTrackerLeadActionHtml(item, ctx, subRows) { - const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + return stageTrackerLeadActionsOnRow(item, ctx, subRows).map(a => stageTrackerLeadPillHtml(item, a)).join(''); + } + // The hover text of an inline pill when the server sent no + // `consequence`: what happens when it is pressed, in one clause. + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + // A row's inline pills are buttons and must read as buttons beside the + // record pills they share a slot with ("adopted from #N", the base + // branch): a filled chip — ham-act-primary (the lead), ham-act-secondary + // ("Let hive decide" beside it) or ham-menu-danger — with a trailing + // glyph (tracker.css ::after). Owner on #16456: "Re-author" in the + // outlined pill read as a record of what happened, not a verb. + function stageTrackerLeadPillHtml(item, a) { if (!a) return ''; // The covering PR has its own row (or is drawn under another listed // issue): the decision — whatever its lead (Let hive decide, Merge @@ -577,10 +635,11 @@ return `<button type="button" class="ham-badge ham-decision-pending" data-ham-scroll-to="${esc(to)}"${via} title="${esc('The decision is on PR #' + a.passive + ' — ' + String(a.label || a.id) + ' lives on ' + where + '. Click to go there.')}">decision pending on #${Number(a.passive) || 0}</button>`; } const label = String(a.label || a.id); - const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); + const tip = a.enabled ? String(a.hint || a.note || a.consequence || STAGE_TRACKER_ACTION_CONSEQUENCES[a.id] || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; const state = a.enabled ? (tip ? ` title="${esc(tip)}"` : '') : ` aria-disabled="true" title="${esc(tip)}"`; - return `<button type="button" class="ham-lead-act${a.danger ? ' ham-menu-danger' : ''}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' — ' + ref : ''))}">${esc(label)}</button>`; + const tone = a.danger ? ' ham-menu-danger' : (a.companion ? ' ham-act-secondary' : ' ham-act-primary'); + return `<button type="button" class="ham-lead-act${tone}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' — ' + ref : ''))}">${esc(label)}</button>`; } // Pure: the actions for a row parked on a blocker (hivecommons/hive#15099): // the server lists them in decision_needed.options (a capability gap @@ -906,6 +965,13 @@ const pr = stageTrackerLinkedPRItem(item, asking[0]); return { key: stageTrackerItemKey(pr), item: pr }; } + // Pure: whether the row's decision card (its own or its one parked + // PR's) offers the server option `action`. + function stageTrackerServerOption(item, action) { + const dec = stageTrackerDecisionOf(item); + const d = dec && dec.item && dec.item.decision_needed; + return !!(d && Array.isArray(d.options) && d.options.some(o => o && o.action === action)); + } // Pure: the trigger — the chevron word or the pill, as a button that // owns the popover. No native title: the popover is the hover text. function stageTrackerDecisionTriggerHtml(decision, innerHtml, tip, cls) { @@ -1027,9 +1093,14 @@ function stageTrackerOpenDecisionPop(trigger, pin) { const key = trigger && trigger.dataset ? trigger.dataset.hamDecision : ''; if (!key) return; + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); if (_stageTrackerDecisionPop && _stageTrackerDecisionPop.key === key) { if (pin) _stageTrackerDecisionPop.pinned = true; clearTimeout(_stageTrackerDecisionPop.timer); + if (pin && pin.focus) { + const first = _stageTrackerDecisionPop.el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); + (first || _stageTrackerDecisionPop.el).focus({ preventScroll: true }); + } return; } stageTrackerCloseDecisionPop(false); @@ -1082,7 +1153,7 @@ window.addEventListener('resize', p.onAway); window.addEventListener('scroll', p.onAway, true); _stageTrackerDecisionPop = p; - if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus(); } + if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus({ preventScroll: true }); } } // The pointer left the trigger or the popover: close after a beat unless // it is pinned or the pointer is back over either (rows re-render, so @@ -1922,10 +1993,6 @@ } case 'decide:queue-merge': return (await stageTrackerAsk(id, 'confirm', { title: 'Approve and let hive merge', message: preface + 'Approve ' + refs + ' as ' + who + '? Your approval stands in for the author\'s trust on this version: hive merges it as-is through its own App on the next tick once CI is green, and will not adopt or re-author it.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve' })) ? {} : null; - case 'decide:re-author': { - const caveat = stageTrackerDCOCaveat(items); - return (await stageTrackerAsk(id, 'confirm', { title: 'Re-author as hive PR', message: preface + 'Have the hive re-author ' + refs + ' as ' + who + '?' + (caveat || ' Its head cannot merge as-is.') + ' The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. Nothing is merged as-is, and the author\'s commits stay attributed.', confirmLabel: 'Re-author', danger: true })) ? {} : null; - } case 'decide:adopt': { const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; @@ -2033,7 +2100,7 @@ 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-issue': 'Closing…', - 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:re-author': 'Queuing re-authoring…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; const STAGE_TRACKER_ACTION_WORDS = { @@ -2052,7 +2119,7 @@ } // The ledger name of a row action id (the inverse of the badge's // STAGE_TRACKER_ACTED_OPTION_ID), for a failure noted on the client. - const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; + const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; // A failed or refused action is noted on the row at once, so the // history badge turns red and its hover's first line names the reason // — the server's ledger only sees 5xx and refused answers, and a @@ -2324,7 +2391,7 @@ n.classList.add('cue-acting'); if (capEl && capEl.parentNode !== host) { capEl.remove(); capEl = null; } if (host && !capEl) { capEl = document.createElement('span'); capEl.className = 'cue-acting-cap'; capEl.setAttribute('role', 'status'); const sp = document.createElement('span'); sp.className = 'toast-spinner cue-acting-spin'; capEl.appendChild(sp); capEl.appendChild(document.createTextNode('')); host.appendChild(capEl); } - if (capEl) capEl.lastChild.nodeValue = cap; + if (capEl) { capEl.lastChild.nodeValue = cap; capEl.title = cap; capEl.setAttribute('aria-label', cap); capEl.setAttribute('tabindex', '0'); } } else { n.classList.remove('cue-acting'); if (capEl) capEl.remove(); @@ -2398,8 +2465,9 @@ return { toasts: [], pending: [] }; } if (id === 'decide:adopt') { - // Adopt acts on the nudged PR row itself (072, not a decision park). - items = items.filter(stageTrackerAdoptOffered); + // Adopt acts on the nudged PR row itself (072, not a decision park) + // or on the row whose decision card offers it. + items = items.filter(it => stageTrackerAdoptOffered(it) || stageTrackerServerOption(it, 'decide:adopt')); if (!items.length) return { toasts: [], pending: [] }; } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. diff --git a/src/pkg/dashboard/static-src/js/tracker-human-attention.js b/src/pkg/dashboard/static-src/js/tracker-human-attention.js index 9b9fbd84d5..576cfa52d3 100644 --- a/src/pkg/dashboard/static-src/js/tracker-human-attention.js +++ b/src/pkg/dashboard/static-src/js/tracker-human-attention.js @@ -11,28 +11,99 @@ if (a.kind === 'pr' && String(a.head || '') !== String(item.head || '')) return null; return a; } - function stageTrackerHumanAttentionLine(item) { - const a = stageTrackerHumanAttentionOf(item); + // Pure: the decision a row carries itself when the server supplies no + // human_attention — a 045 issue or 085 PR with decision_needed, or a + // needs-human flag with a blocker (hivecommons/docs#612, rationguard#480). + // Same shape as human_attention ({reason, asked_by, question, synthetic}) + // so the note line reads the same either way. null when the row is not + // parked on a person, or when human_attention already says it. + function stageTrackerNeedsHumanAsk(item) { + if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL + || item.superseded_by || item.adopted_by) return null; + const mods = Array.isArray(item.modifiers) ? item.modifiers : []; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged')) return null; + if (stageTrackerHumanAttentionOf(item)) return null; + const n = Number(item.stage) || 0; + const flagged = item.needs_human === true || mods.indexOf('needs-human') >= 0 || mods.indexOf('needs-decision') >= 0 + || n === (typeof STAGE_TRACKER_NEEDS_DECISION === 'number' ? STAGE_TRACKER_NEEDS_DECISION : 85) + || n === (typeof STAGE_TRACKER_ISSUE_NEEDS_DECISION === 'number' ? STAGE_TRACKER_ISSUE_NEEDS_DECISION : 45); + if (!flagged) return null; + const d = item.decision_needed || {}; + const b = item.blocker || {}; + const actor = item.stage_actor || {}; + const question = String(d.question || '').trim(); + const why = String(actor.why || '').trim(); + const whyClause = why.indexOf(' — ') >= 0 ? why.slice(why.indexOf(' — ') + 3).trim() : ''; + // Only evidence the server put on the row counts — a parked stage + // alone synthesizes nothing (the row may be mid-refresh or hive-owned). + const reason = question || String(b.detail || '').trim() || String(d.blocker || '').trim() || String(b.short || '').trim() || (actor.kind === 'human' ? whyClause : ''); + if (!reason) return null; + return { kind: item.kind, number: Number(item.number) || 0, reason, question, asked_by: String(d.asked_by || actor.login && actor.kind === 'hive' && 'the hive' || '').trim() || 'the hive', synthetic: true }; + } + // Pure: "Needs human: <short> — <first sentence of the reason>", the + // short reason first so the row names the blocker before explaining it. + // A reason that already starts with the short form is not repeated. + // whole: keep the whole reason (a decision question is the ask itself). + function stageTrackerNeedsHumanReasonText(item, reason, whole) { + const full = String(reason || '').trim(); + const short = typeof stageTrackerNeedsHumanShort === 'function' ? stageTrackerNeedsHumanShort(item) : ''; + if (!short || full.toLowerCase().indexOf(short.toLowerCase()) === 0) return full; + const m = whole ? null : full.match(/^[\s\S]*?[.!?](?=\s|$)/); + const first = m ? m[0].trim() : full; + return first ? short + ' — ' + first : short; + } + // Pure: the label of the row's lead action, when a lifted copy has one + // (tracker-actions). '' without one, or when the lead is the optional + // delegation itself — that is not what the person is asked to do. + function stageTrackerNeedsHumanLeadLabel(item, subRows) { + if (typeof stageTrackerLeadActionOnRow !== 'function' || typeof stageTrackerActionCtx !== 'function') return ''; + const ctx = stageTrackerActionCtx(item.repo); + if (!ctx) return ''; + ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; + const action = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!action || !action.label || action.id === 'decide:delegate' || action.id === 'decide:delegate-all') return ''; + return String(action.label).replace(/\s*[▸›]\s*$/, ''); + } + // Pure: the one open covering PR a person other than the hive is pushing + // for this issue, when exactly one covers it. null otherwise. + function stageTrackerNeedsHumanPusher(item) { + if (!item || item.kind !== 'issue') return null; + if (typeof stageTrackerLinkedPROpen !== 'function') return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && stageTrackerLinkedPROpen(lp, item)); + if (open.length !== 1) return null; + const lp = open[0]; + const human = (lp.author_kind || '') === 'human' || (lp.author_kind || '') === 'maintainer'; + return human && lp.author ? lp : null; + } + function stageTrackerHumanAttentionLine(item, subRows) { + const a = stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item); if (!a) return ''; - const reason = String(a.reason || '').trim() || 'Human decision required; reason unavailable'; + const reason = stageTrackerNeedsHumanReasonText(item, String(a.reason || '').trim() || 'Human decision required; reason unavailable', !!(a.synthetic && a.question)); const parts = ['Needs human: ' + reason]; if (a.owner) parts.push('next move: @' + a.owner); - if (a.asked_by) parts.push('requested by ' + a.asked_by); + if (a.asked_by) parts.push((a.synthetic ? 'asked by ' : 'requested by ') + a.asked_by); + const lead = stageTrackerNeedsHumanLeadLabel(item, subRows); + if (lead) parts.push('lead: ' + lead + ' ▸'); + const pusher = stageTrackerNeedsHumanPusher(item); + if (pusher) parts.push('@' + pusher.author + ' is pushing it in #' + Number(pusher.number)); return parts.join(' · '); } - function stageTrackerHumanRequirementText(item) { + function stageTrackerHumanRequirementText(item, subRows) { if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL || item.superseded_by || item.adopted_by || (item.modifiers || []).some(m => m === 'draft' || m === 'hold' || m === 'merged')) return ''; - const human = stageTrackerHumanAttentionLine(item); + const human = stageTrackerHumanAttentionLine(item, subRows); const d = item && item.decided; const review = d && d.current_blocker && String(d.head || '') === String(item.head || '') ? 'Current blocker: ' + d.current_blocker + ' · operator approval recorded separately, not review approval or merge readiness' : ''; return [human, review].filter(Boolean).join(' · '); } - function stageTrackerHumanContextOf(item, stages) { + function stageTrackerHumanContextOf(item, stages, subRows) { if (!item) return []; - const own = stageTrackerHumanRequirementText(item); - const out = own ? [{ item, text: own }] : []; + const own = stageTrackerHumanRequirementText(item, subRows); + // An issue's own ask is prefixed with its number, like a PR's line, + // so a row whose strip a covering PR drives still names the asker. + const asks = item.kind === 'issue' && !!(stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item)); + const out = own ? [{ item, text: (asks ? '#' + Number(item.number) + ' — ' : '') + own }] : []; if (item.kind !== 'issue') return out; // Include external drawn_under references, but never walk RFC ancestry // or assign one child's requirement to the issue / its other PRs. @@ -49,26 +120,65 @@ } return out; } - function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { - const required = stageTrackerHumanContextOf(item, stages); - const lines = required.map(entry => { - const it = entry.item; + // A human-requirement line is a hive note: it opens, then tucks into + // its ⬡ icon like the "Hive: …" line (stageTrackerHumanNoteHtml, + // tracker-motion). Lifted copies without tracker-motion (tests, + // previews) render the plain row instead. + function stageTrackerHumanContextLine(item, bodyHtml, text, nowMs) { + if (typeof stageTrackerHumanNoteHtml === 'function' && typeof stageTrackerItemKey === 'function') { + return stageTrackerHumanNoteHtml(stageTrackerItemKey(item), bodyHtml, text, nowMs); + } + return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; + } + /* ---- One note line per row ----------------------------------------- + Owner (2026-11-05): "we don't need 2 hive comments — there should + always be only one." A row used to stack its "Needs human: …" line + over the "Hive: moved to …" stage note. Now every candidate is + ranked — needs-human / decision (0) > blocker (1) > next move / + claim (2) > optional delegation (3) > stage-transition note (4) — + and the row renders the winner alone. Same-rank human asks (an + issue's and its PR's) share the line, " · " apart, each with its + View link. A lower line's facts ride along as a trailing clause + only when they say something the row does not already: a stage + note that merely restates the lit chevron ("moved to Needs human + decision" under a strip lit at Needs human decision) is dropped. */ + const STAGE_TRACKER_NOTE_RANK_HUMAN = 0; + const STAGE_TRACKER_NOTE_RANK_BLOCKER = 1; + const STAGE_TRACKER_NOTE_RANK_NEXT = 2; + const STAGE_TRACKER_NOTE_RANK_OPTIONAL = 3; + // Mod-change words (tracker-motion) a "Needs human:" line already says. + const STAGE_TRACKER_NOTE_HUMAN_RESTATES = ['waiting on a person', 'waiting on a decision']; + function stageTrackerNoteRankOf(text) { + const t = String(text || ''); + if (/(^|— )Needs human:|decision context unavailable/.test(t)) return STAGE_TRACKER_NOTE_RANK_HUMAN; + if (/Current blocker:/.test(t)) return STAGE_TRACKER_NOTE_RANK_BLOCKER; + if (/^Optional delegation:/.test(t)) return STAGE_TRACKER_NOTE_RANK_OPTIONAL; + return STAGE_TRACKER_NOTE_RANK_NEXT; + } + // Pure: the candidate human lines for the row, each { body, text, rank }. + function stageTrackerHumanContextEntries(item, stages, nowMs, subRows) { + const required = stageTrackerHumanContextOf(item, stages, subRows); + const entry = (body, text) => ({ body, text, rank: stageTrackerNoteRankOf(text) }); + const lines = required.map(e => { + const it = e.item; const href = it.url || item.url; - return `<div class="cue-event ham-human-context"><span>${esc(entry.text)}${href ? ` <a href="${esc(href)}" target="_blank" rel="noopener">View ${it.kind === 'pr' ? 'PR' : 'issue'} #${Number(it.number)}</a>` : ''}</span></div>`; + const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; + return entry(esc(e.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''), e.text + (view ? ' · ' + view : '')); }); - if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); + if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines; const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); const staleLinks = item.kind === 'issue' ? (item.linked_prs || []).filter(lp => stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; - return `<div class="cue-event ham-human-context"><span>${esc(refs)} · decision context unavailable for the displayed identity/head${item.url ? ` · <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''}</span></div>`; + const text = refs + ' · decision context unavailable for the displayed identity/head'; + return [entry(esc(text) + (item.url ? ` · <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text)]; } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => - stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return ''; + stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return []; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; - if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return ''; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return []; const actor = item.stage_actor; const actorHuman = actor && (actor.kind === 'human' || actor.kind === 'maintainer'); const claimant = item.claimant; @@ -78,9 +188,11 @@ const who = actor.login ? '@' + actor.login : 'a person'; const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; - lines.push(`<div class="cue-event ham-human-context"><span>Next move: ${esc(who + target)}${actor.why ? ' — ' + esc(actor.why) : ' · action reason unavailable'}</span></div>`); + const text = 'Next move: ' + who + target + (actor.why ? ' — ' + actor.why : ' · action reason unavailable'); + lines.push(entry(esc(text), text)); } else if (claimant && claimant.kind === 'person' && claimant.login) { - lines.push(`<div class="cue-event ham-human-context"><span>Claimed by @${esc(claimant.login)} · claim ownership, not a human decision request</span></div>`); + const text = 'Claimed by @' + claimant.login + ' · claim ownership, not a human decision request'; + lines.push(entry(esc(text), text)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -89,9 +201,61 @@ ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { - lines.push('<div class="cue-event ham-human-context"><span>Optional delegation: Let hive decide is available; it does not itself mean human input is required.</span></div>'); + const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; + lines.push(entry(esc(text), text)); } } } - return lines.join(''); + return lines; + } + // Pure: the row's current stage as the chevron names it ('' unknown). + function stageTrackerNoteStageName(item, stages) { + if (!item) return ''; + const sg = (Array.isArray(stages) ? stages : []).find(x => Number(x.number) === (Number(item.stage) || 0)); + if (typeof stageTrackerStageName === 'function') return stageTrackerStageName(sg) || stageTrackerStageName({ label: item.stage_label || '', short: '' }); + return sg ? String(sg.short || sg.label || '') : String(item.stage_label || ''); + } + // Pure: the stage note's words worth keeping under a human line, or + // '' when the line (or the lit chevron) already says it. + function stageTrackerNoteFoldText(evText, lineText, item, stages) { + const t = String(evText || '').trim(); + if (!t) return ''; + const line = String(lineText || '').toLowerCase(); + if (line.indexOf(t.toLowerCase()) >= 0) return ''; + if (/needs human:/i.test(line) && STAGE_TRACKER_NOTE_HUMAN_RESTATES.indexOf(t) >= 0) return ''; + const m = /^(?:moved to|fell back to) (.+)$/.exec(t); + if (m) { + const name = stageTrackerNoteStageName(item, stages).toLowerCase(); + const said = m[1].split(' — ')[0].trim().toLowerCase(); + if (name && said === name && m[1].indexOf(' — ') < 0) return ''; + } + return t; + } + // ctx / key (the row's events map and its key) let the human line + // absorb the row's stage note so the row shows one line, not two. + function stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, key) { + let entries = stageTrackerHumanContextEntries(item, stages, nowMs, subRows); + if (!entries.length) return ''; + const best = Math.min.apply(null, entries.map(e => e.rank)); + // "Let hive decide is available" is a control the row shows anyway; + // it only earns the line when nothing else wants it. + if (best < STAGE_TRACKER_NOTE_RANK_OPTIONAL) entries = entries.filter(e => e.rank < STAGE_TRACKER_NOTE_RANK_OPTIONAL); + entries.sort((a, b) => a.rank - b.rank); + let body = entries.map(e => e.body).join(' · '); + let text = entries.map(e => e.text).join(' · '); + const ev = ctx && ctx.events && key ? ctx.events[key] : null; + const fold = ev ? stageTrackerNoteFoldText(ev.text, text, item, stages) : ''; + if (fold) { + const who = ev.who === 'you' ? 'You: ' : ev.who === 'merge' ? 'Merge: ' : ''; + body += ' · ' + esc(who + fold); text += ' · ' + who + fold; + } + return stageTrackerHumanContextLine(item, body, text, nowMs); + } + // Pure: ctx without the row's stage note once the human line has + // taken it (folded or dropped), so the event slot stays empty. + function stageTrackerNoteTakenCtx(ctx, key) { + if (!ctx || !ctx.events || !key || !ctx.events[key]) return ctx; + const events = Object.assign({}, ctx.events); + delete events[key]; + return Object.assign({}, ctx, { events }); } diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index 4d0dfcd7e0..e0f2e36b4e 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -183,6 +183,7 @@ const next = stageTrackerStateMap(d && d.items); const ttl = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting() ? Infinity : STAGE_TRACKER_EVENT_MS; _stageTrackerEvents = stageTrackerEventsNext(_stageTrackerEvents, _stageTrackerStates, next, d && d.stages, nowMs, ttl); + _stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, next); _stageTrackerStates = next; } /* ---- Hive notes: show, then tuck --------------------------------------- @@ -254,6 +255,7 @@ function stageTrackerNoteTitle(ev, nowMs) { if (!ev) return ''; const age = stageTrackerAgoText(ev.at, nowMs); + if (ev.who === 'human') return ev.text + (age ? ' · ' + age : ''); return (ev.who === 'you' ? 'You' : 'Hive') + ': ' + ev.text + (age ? ' · ' + age : ''); } let _stageTrackerNoteTimer = 0; @@ -268,7 +270,7 @@ // it went hidden (the age keeps counting). const openNow = _stageTrackerNoteHiddenAt || nowMs; for (const p of Array.from(el.querySelectorAll('.cue-event[data-cue-key]'))) { - const ev = _stageTrackerEvents[p.getAttribute('data-cue-key')]; + const ev = stageTrackerNoteEventOf(p.getAttribute('data-cue-key')); const open = !ev || stageTrackerNoteOpen(ev, openNow, auto); if (open) p.classList.remove('cue-event-tucked'); else p.classList.add('cue-event-tucked'); const btn = p.querySelector('.cue-event-ico'); @@ -279,18 +281,32 @@ function stageTrackerNoteSchedule(nowMs) { if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } if (document.hidden) return; - const due = stageTrackerNoteNextDue(_stageTrackerEvents, nowMs, stageTrackerNoteTuckSetting()); + const due = stageTrackerNoteNextDue(stageTrackerNoteEventsAll(), nowMs, stageTrackerNoteTuckSetting()); if (due === Infinity) return; _stageTrackerNoteTimer = setTimeout(() => { _stageTrackerNoteTimer = 0; stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), Date.now()); }, due); } // The icon's click (and Enter / Space, it is a button). function stageTrackerNoteToggle(key) { - const ev = _stageTrackerEvents[key]; + const ev = stageTrackerNoteEventOf(key); if (!ev) return; const nowMs = Date.now(); - _stageTrackerEvents[key] = stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting()); + stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } + // The row's "needs human" pill: bring its "Needs human: …" line into + // view, untucked. rowKey: the row's data-ham-key. + function stageTrackerNeedsHumanReveal(rowKey) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel || !rowKey) return; + const rows = panel.querySelectorAll('.ham-row[data-ham-key]'); + let row = null; + for (const r of rows) if (r.getAttribute('data-ham-key') === String(rowKey)) { row = r; break; } + if (!row) return; + const line = row.querySelector('.ham-human-context[data-cue-key]'); + if (!line) return; + if (line.classList.contains('cue-event-tucked')) stageTrackerNoteToggle(line.getAttribute('data-cue-key')); + if (typeof line.scrollIntoView === 'function') line.scrollIntoView({ block: 'nearest' }); + } // Hidden tab: stop the clock on every open line; visible again: give // back the hidden time and re-arm. function stageTrackerNoteVisibility(hidden, nowMs) { @@ -300,7 +316,11 @@ if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } return; } - if (_stageTrackerNoteHiddenAt) { _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); _stageTrackerNoteHiddenAt = 0; } + if (_stageTrackerNoteHiddenAt) { + _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerHumanNotes = stageTrackerNoteShift(_stageTrackerHumanNotes, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerNoteHiddenAt = 0; + } stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // The owner's own action writes the row's line at once ("you: approved"). @@ -317,15 +337,71 @@ function stageTrackerEventHtml(key, ctx) { const ev = ctx && ctx.events ? ctx.events[key] : null; if (!ev) return ''; + const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; + const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; + return stageTrackerNoteLineHtml(key, ev, ctx, body, ''); + } + // Pure: one note line — the shared shape behind the hive line and the + // human-requirement line, so both open, tuck and re-open the same way. + function stageTrackerNoteLineHtml(key, ev, ctx, body, extraClass) { const nowMs = ctx && typeof ctx.nowMs === 'number' ? ctx.nowMs : Date.now(); const auto = ctx && typeof ctx.noteTuck === 'boolean' ? ctx.noteTuck : (typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting()); const fading = !auto && nowMs - stageTrackerEventShownAt(ev) > STAGE_TRACKER_EVENT_MS * 2 / 3; const open = !auto || stageTrackerNoteOpen(ev, nowMs, auto); - const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; - const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; - if (!auto) return `<p class="cue-event${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; + const cls = extraClass ? ' ' + extraClass : ''; + if (!auto) return `<p class="cue-event${cls}${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; const ico = `<button type="button" class="cue-event-ico" aria-label="${STAGE_TRACKER_NOTE_LABEL}" aria-expanded="${open ? 'true' : 'false'}" title="${esc(stageTrackerNoteTitle(ev, nowMs))}" data-action="stageTrackerNoteToggle" data-arg0="${esc(key)}" data-stop="1">${STAGE_TRACKER_NOTE_ICON}</button>`; - return `<p class="cue-event cue-event-tuckable${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + return `<p class="cue-event cue-event-tuckable${cls}${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + } + /* ---- Human-requirement notes ------------------------------------- + "Needs human: …" / "Current blocker: …" (tracker-human-attention) + are hive comments too. #16011 drew them as a static row under the + item so the ask stayed readable; the owner (2026-11-04): "these + things should be hive comments and they should hide (slide-left) + as they used to." They now ride the same show-then-tuck line as the + hive note — the row's Let hive decide / Sentinel alert controls keep + the decision state in view after the words tuck. Their own map, + keyed by row and words, remembers when this tab first showed each + line so a re-render never re-opens one already seen; a row leaving + the payload (or its words changing) drops the entry. */ + let _stageTrackerHumanNotes = {}; + function stageTrackerTextHash(text) { + let h = 5381; + for (let i = 0; i < text.length; i++) h = (h * 33 + text.charCodeAt(i)) >>> 0; + return h.toString(36); + } + function stageTrackerHumanNote(rowKey, text, nowMs) { + const key = 'human:' + rowKey + ':' + stageTrackerTextHash(text); + let ev = _stageTrackerHumanNotes[key]; + if (!ev) { ev = { who: 'human', row: rowKey, text, at: nowMs }; _stageTrackerHumanNotes[key] = ev; } + return { key, ev }; + } + // Pure: the human notes still backed by a row in nextStates. + function stageTrackerHumanNotesNext(notes, nextStates) { + const out = {}; + for (const k of Object.keys(notes || {})) if (!nextStates || nextStates[notes[k].row]) out[k] = notes[k]; + return out; + } + // bodyHtml is the line's already-escaped words (with its View link); + // text is the plain words the icon's tooltip and the key use. + function stageTrackerHumanNoteHtml(rowKey, bodyHtml, text, nowMs) { + nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); + const { key, ev } = stageTrackerHumanNote(rowKey, text, nowMs); + const auto = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting(); + // Auto-collapse off: the old two-minute life and fade, like a hive line. + if (!auto && nowMs - stageTrackerEventShownAt(ev) >= STAGE_TRACKER_EVENT_MS) return ''; + return stageTrackerNoteLineHtml(key, ev, { nowMs, noteTuck: auto }, `<span class="cue-event-text">${bodyHtml}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`, 'ham-human-context'); + } + // A note by key from either map; a toggle writes back to the map it + // came from. + function stageTrackerNoteEventOf(key) { + return _stageTrackerEvents[key] || _stageTrackerHumanNotes[key] || null; + } + function stageTrackerNoteEventSet(key, ev) { + if (_stageTrackerEvents[key]) _stageTrackerEvents[key] = ev; else _stageTrackerHumanNotes[key] = ev; + } + function stageTrackerNoteEventsAll() { + return Object.assign({}, _stageTrackerHumanNotes, _stageTrackerEvents); } const STAGE_TRACKER_CUE_TICK_MS = 15000; function stageTrackerCueAgeSync(el, nowMs) { @@ -645,7 +721,7 @@ // The hive note's open / tucked state is applied in place // (stageTrackerNoteSync), so it is not a reason to swap the node either. function stageTrackerRowSrcKey(html) { - return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="(?:You|Hive): [^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); + return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="[^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); } // Pure: whether the stamped move attributes name this strip. function stageTrackerRowHasMove(html) { return / data-ham-prev-col="\d+"/.test(String(html || '')); } @@ -657,6 +733,12 @@ tpl.innerHTML = html; const node = tpl.content.firstElementChild; node.dataset.hamKey = key; + // Bind canonical lane geometry when materializing root and nested rows. + if (typeof node.querySelectorAll === 'function') { + for (const header of node.querySelectorAll('.ham-head-cols[data-ham-pr-start]')) { + header.style.setProperty('--ham-pr-start', header.dataset.hamPrStart); + } + } if (_stageTrackerRowSrc) _stageTrackerRowSrc.set(node, stageTrackerRowSrcKey(html)); return node; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-acted.js b/src/pkg/dashboard/static-src/js/tracker-row-acted.js index 4e1152e25c..fe51617565 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-acted.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-acted.js @@ -94,7 +94,7 @@ } // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:adopt', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js index 807d3c153e..f91cfd897b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js @@ -44,6 +44,10 @@ // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 76ec4653a7..2e8f1fb7e3 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -1,14 +1,21 @@ // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs, and the cap cell the modifier chip, bottom-aligned so - // it sits on the last title line, directly over the strip's right end. + // the given refs followed by the modifier chips / action buttons, + // right-anchored on that same line (margin-left: auto). The chips ride + // the title line rather than a second full-width toolbar line, so the + // chevrons sit directly under the title (hivecommons/hive#16454 left a + // one-line band between them); when the PR metadata leaves no room the + // chips wrap under it, content-driven, never a fixed row. A row without + // PR refs still gets the PR cell (ham-head-tools) so its chips sit on + // the title line in the PR span, not on a line of their own. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); - return `<div class="ham-strip-row ham-head-cols"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li><li class="ham-seg ham-head-pr${wide ? ' ham-head-tools' : ''}"${!wide && prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${wide ? '' : prRefs.join('')}<span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { @@ -66,7 +73,7 @@ ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0, @@ -122,13 +129,17 @@ if (l.kind === 'superseded') return Number(l.to_number) > 0 ? 'superseded by #' + Number(l.to_number) + tail : ''; if (!(Number(l.from_number) > 0)) return ''; const whose = l.from_author ? '@' + l.from_author + "'s " : ''; - return (l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : 'adopted from ') + whose + '#' + Number(l.from_number) + tail; + // "re-authored from #N" is the hive rewriting its OWN exhausted PR; + // "adopted from" is a contributor's PR the hive took over. + const verb = l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : l.kind === 're-authored' ? 're-authored from ' : 'adopted from '; + return verb + whose + '#' + Number(l.from_number) + tail; } // Pure: the hover — why the hive took it over, in plain words. function stageTrackerLineageTip(item) { const l = item && item.lineage; if (!l || !l.kind) return ''; if (l.kind === 'superseded') return 'Hive took this PR over as #' + Number(l.to_number) + '; this original is closed when that merges.'; + if (l.kind === 're-authored') return "Hive's fixer gave up on its own #" + Number(l.from_number) + ', so the hive closed it as superseded and opened this fresh PR from the current base.' + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); const who = l.from_author ? '@' + l.from_author : 'the contributor'; const tip = STAGE_TRACKER_LINEAGE_REASON_TIP[l.reason] || STAGE_TRACKER_LINEAGE_REASON_TIP['ci-red-contributor-offline']; return tip.split('@AUTHOR').join(who) + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); @@ -159,7 +170,7 @@ let l = item && item.lineage; if (!l && item && item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length === 1) l = item.linked_prs[0].lineage; if (!l || !(Number(l.from_number) > 0) || l.kind === 'superseded') return ''; - return ' (adopted from #' + Number(l.from_number) + ')'; + return (l.kind === 're-authored' ? ' (re-authored from #' : ' (adopted from #') + Number(l.from_number) + ')'; } // Pure: the "↳ adopted from #N · you let hive decide 17:51" chip on the // hive's copy of an adopted PR (hivecommons/hive#15126). @@ -218,12 +229,10 @@ if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(pr); const superseded = typeof stageTrackerLinkedSupersededText === 'function' ? stageTrackerLinkedSupersededText(lp, issue) : ''; let ref = stageTrackerPRRef(pr.number, pr.url, pr.author_kind, pr.author, pr.title, (pr.title ? pr.title + ' · ' : '') + (superseded ? superseded + ' · ' + stageTrackerLinkedSupersededTip(lp) : stageTrackerTooltip(pr, nowMs)) + ' · ' + stageTrackerLinkedTip(issue, pr.number, ctx)); - // One line (hivecommons/hive: "consolidate from 3 lines of text to - // 1"): connector, repo chip, author icon + #N + title, the lineage / - // adopted-from chip, then the base pill — all siblings of the flex-row - // PR cell; the title ellipsizes, the pills never shrink. A superseded - // original wears neither pill — it closes as superseded, not as the - // closer of anything. + // Connector, repo chip, author icon + #N + title, lineage / + // adopted-from chip and base pill share the wrapping PR-side cell. + // A superseded original wears neither pill — it closes as superseded, + // not as the closer of anything. const lineage = superseded ? '' : ((typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(pr, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(pr, nowMs) : '')); const chip = ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : ''; if (chip) ref = `<span class="ham-pr-line">${chip}${ref}</span>`; @@ -232,7 +241,7 @@ if (superseded) { // The adopted original: one muted line, no chevron track, no row // tools, no needs-human styling — the copy carries the chevron. The - // trailing note never wraps; the title ellipsizes first (owner, + // trailing note stays distinct from the wrapping title (owner, // hivecommons/hive#15511: "superseded · hive adopted → #15574"). return `<div class="ham-sub ham-sub-superseded" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}" data-ham-superseded-by="${Number(lp.superseded_by || lp.adopted_by) || 0}"> <div class="ham-row-head"> @@ -240,6 +249,9 @@ </div> </div>`; } + const subKey = stageTrackerItemKey(pr); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs, undefined, ctx, subKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, subKey) : ctx; return `<div class="ham-sub${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(pr, ctx) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(pr, stages, ctx) : ''}" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}"> ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''} <div class="ham-row-head"> @@ -250,7 +262,7 @@ <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(pr), ctx)}>${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(pr, nowMs)} </div> - ${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs) : ''}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, ctx, stageTrackerItemKey(pr)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(pr), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} </div>`; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-render.js b/src/pkg/dashboard/static-src/js/tracker-row-render.js index 95b3bfbb27..f555fcc5e2 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -108,7 +108,7 @@ shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, finisher: fin.finisher || '', finisher_verb: fin.finisher_verb || '', finisher_reason: fin.finisher_reason || '' }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed @@ -161,6 +161,11 @@ const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(shown); + // One note line per row: the human line takes the stage note (folded + // or dropped), so the event slot below the caption renders nothing. + const rowKey = stageTrackerItemKey(item); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; return `<div class="ham-row${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(shown, ctx) : ''}${typeof stageTrackerTrainRowClass === 'function' ? stageTrackerTrainRowClass(item, ctx.prevRow || null, ctx.nextRow || null, ctx.trainIndex && trainKey ? ctx.trainIndex[trainKey] : undefined) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(item, stages, ctx) : ''}" tabindex="0" data-ham-kind="${esc(item.kind)}" data-ham-repo="${esc(item.repo || '')}" data-ham-stage="${Number(item.stage) || 0}"${prs ? ` data-ham-prs="${esc(prs)}"` : ''}${trainKey ? ` data-ham-train="${esc(trainKey)}"` : ''}> ${stageTrackerRowToolsHtml(item)} <div class="ham-row-head"> @@ -170,7 +175,7 @@ ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(item), ctx)}>${stageTrackerStripItems(shown, stages, range, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(shown, nowMs)} - </div>${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows) : ''}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, ctx, stageTrackerItemKey(item)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(item), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} + </div>${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} </div>`; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-strip.js b/src/pkg/dashboard/static-src/js/tracker-row-strip.js index b1c79c2be8..bed5934905 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -15,9 +15,227 @@ return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History — decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Pure: which of the two column-50 tracks the hive is waiting on when + // both share the current phase (hivecommons/hive#16484). Review + // findings and red CI are the fixer's turn ("the fix"); otherwise CI + // leads until it is green, then review. newHead: the head was just + // pushed, so CI is (re)running on it and the review is a re-review. + function stageTrackerTrackLead(item) { + if (!item || !item.head) return null; + const stateOf = k => { const a = item[k + '_activity']; return a && a.head === item.head && a.state ? a.state : 'unknown'; }; + const ci = stateOf('ci'); + const review = stateOf('review'); + const done = s => s === 'passing' || s === 'approved'; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + if (review === 'changes_requested') return { track: 'review', waitingOn: 'the fix', newHead: false }; + if (ci === 'failing') return { track: 'ci', waitingOn: 'the fix', newHead: false }; + if (done(ci) && done(review)) return null; + if (done(ci)) return { track: 'review', waitingOn: 'review', newHead }; + return { track: 'ci', waitingOn: 'CI', newHead }; + } + + // Pure: the chevron's primary words — the count grammar the operator + // asked for (hivecommons/hive#16484): "CI 12/14 passed", "CI 11/14 · 1 + // failing (lint)", "CI 0/14 · queued", "CI ?/? · no checks reported + // yet"; "Review 3/5 perspectives", "Review 5/5 approved", "Review 0/5 · + // re-review pending (new head)", "Review 2/5 · awaiting human + // decision". '' means the track has not started on this head (the + // chevron shows its glyph alone). current: column 50 is the row's + // active phase, so even absent evidence is "in progress" there. + function stageTrackerTrackWord(item, kind, current) { + const a = item && item[kind + '_activity']; + const matches = !!(a && item.head && a.head === item.head); + const state = matches ? a.state || 'unknown' : 'unknown'; + if (state === 'unknown' && !current) return ''; + const n = k => matches ? Number(a[k]) || 0 : 0; + if (kind === 'ci') { + const total = n('checks_total'); + const passed = n('checks_passed'); + const failed = n('checks_failed'); + const names = matches && Array.isArray(a.checks_failing) ? a.checks_failing : []; + const count = 'CI ' + (total ? passed + '/' + total : '?/?'); + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; + const blocker = matches && a.blocker ? String(a.blocker) : ''; + switch (state) { + case 'passing': return count + ' passed'; + case 'failing': return count + ' · ' + (failing || 'failing' + (blocker ? ' (' + blocker + ')' : '')); + case 'running': return count + ' · running' + (failing ? ' · ' + failing : ''); + case 'queued': return count + ' · queued' + (failing ? ' · ' + failing : ''); + case 'skipped': return count + ' · ' + (blocker ? blocker + ' skipped' : 'skipped'); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' · waiting on workflow approval' + (failing ? ' · ' + failing : ''); + return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } + default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); + } + } + const total = n('perspectives_total'); + const done = n('perspectives_done'); + const count = 'Review' + (total ? ' ' + done + '/' + total : ''); + const actor = matches && a.actor ? String(a.actor) : ''; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + switch (state) { + case 'approved': return count + ' approved'; + case 'changes_requested': return count + ' · changes requested'; + // The hive on the repair (adopted / remediating) is not a human + // decision: the findings are the changes requested. Otherwise the + // reviews are done and a person's sign-off is what is left — the + // viewer's when the ask names them, else the owner's. Never + // "awaiting human" to the human it waits on (hivecommons/hive#16572: + // "why does review say awaiting humans if 5/5 reviews are good?"). + case 'human_decision': { + if (stageTrackerHiveOwnsRepair(item)) return count + ' · changes requested'; + const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; + const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; + const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); + return count + (mine ? ' · needs your sign-off' : ' · needs owner sign-off'); + } + case 'reviewing': return count + ' · ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' · ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' · queued' + stageTrackerQueueAheadWord(a); + default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:<n>" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve — done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return `<circle class="${cls}" cx="${c}" cy="${c}" r="${r}"/>`; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return `<path class="${cls}" d="M${pt(from)} A${r} ${r} 0 ${large} 1 ${pt(to)}"/>`; + }; + const open = `<svg class="ham-ico ham-ring ham-ring-${tone}${running ? ' ham-ring-running' : ''}" viewBox="0 0 16 16" fill="none" stroke-width="2.2" stroke-linecap="butt" role="img" aria-label="${esc(a11y)}" data-ring-total="${t}" data-ring-done="${d}" data-ring-failed="${f}">`; + if (!t) return open + `<circle class="ham-ring-track" cx="${c}" cy="${c}" r="${r}"/></svg>`; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); + } + return open + segs.join('') + '</svg>'; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled — CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled — + // queued, in progress, adjudicating alike — because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; + } + + function stageTrackerHiveOwnsRepair(item) { + if (!item || item.needs_human || item.on_hold || item.hold) return false; + const code = item.code_activity; + const hive = code && code.head === item.head && ['adopted', 'remediating', 'unassigned', 'fix_pushed', 'fixing'].includes(code.state); + return !!(hive || item.stage === 74 || item.adopted_by); + } + + // A row parked on a person: the contributor's move (071/072 or a + // waiting_owner code word), a hold, or a human decision. Nothing of + // the hive's is in motion on it, so no CI / Review track is amber. + function stageTrackerWaitingOnPerson(item) { + if (!item) return false; + if (item.needs_human || item.on_hold || item.hold) return true; + const stage = Number(item.stage); + // A freshly pushed head is in motion: checks run on it, matching + // tracker-row-anchor's column-50 anchor (hivecommons/hive#16552). + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state))) return true; + const code = item.code_activity; + return !!(code && code.head === item.head && code.state === 'waiting_owner'); + } + + // A CI / Review track is in motion only on concrete evidence on the + // current head: a check-run in_progress / queued, or a reviewer + // running / queued (or the backend's own active flag). Checks that + // have not reported, unknown evidence and settled verdicts are not + // motion (hivecommons/hive#16540). + function stageTrackerTrackRunning(item, kind) { + const a = item && item[kind + '_activity']; + if (!a || !item.head || a.head !== item.head) return false; + if (stageTrackerWaitingOnPerson(item)) return false; + const moving = kind === 'ci' ? ['running', 'queued'] : ['reviewing', 'adjudicating', 'assigned']; + return !!(a.active || moving.includes(a.state)); + } + // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + // The chevron wears its glyph plus the count words from + // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the + // track's own state on the current head: running = the full active + // fill (both tracks may be lit at once; the words disambiguate); done, + // a finding, pending and decided are words in their colour on the muted + // field — only a running track is filled (hivecommons/hive#16540); not + // started = the empty chevron with the glyph alone. Freshness gates only + // the pulse. + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -27,16 +245,45 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); - const active = matches && a.active && Number.isFinite(observed) && !stale; + const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown · last observed ' + state; - const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; + const active = known && a.active; + if (matches && !known && state !== 'unknown') caption = name + ' activity unknown · last observed ' + state + ' · ' + caption; + const ownsPR = item.kind === 'pr' || item.via_pr; + const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); + const finished = matches && (state === 'passing' || state === 'approved'); + const finding = matches && (state === 'failing' || state === 'changes_requested'); + // A complete verdict parked on a person is settled (muted icon). + const settled = matches && state === 'human_decision' && (!known || !a.active); + // ACTIVE = filled amber with its words; 1 ≤ active ≤ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone — green for + // a pass, red for a finding, neutral when not run or decided — with + // its count words in the tooltip (hivecommons/hive#16599). + const running = stageTrackerTrackRunning(item, kind); + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; - const blocker = matches && a.blocker ? ' · ' + a.blocker : ''; - let tip = caption + blocker + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; - const ownsPR = item.kind === 'pr' || item.via_pr; + let blocker = matches && a.blocker ? ' · ' + a.blocker : ''; + // A sign-off ask: the tooltip carries the question itself (who should + // decide what, and why — "workflow change from a fork") when the + // review evidence did not already quote it. + const ask = matches && state === 'human_decision' && item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question) : ''; + if (ask && blocker.indexOf(ask) < 0) blocker += ' · ' + ask; + // The backend's plain-language sentence behind the caption rides in + // the tooltip only; the chevron clamps the caption. + const detail = matches && a.detail ? ' · ' + a.detail : ''; + let tip = caption + blocker + detail + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; const code = item.code_activity; const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && ((kind === 'review' && code.state === 'waiting_fixer') || (kind === 'ci' && code.state === 'waiting_ci')) ? code.caption : ''; @@ -45,12 +292,32 @@ let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); - const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); + const sha7 = item.head ? String(item.head).slice(0, 7) : ''; + const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. + const verdict = finished ? 'pass' : finding ? 'fail' : ''; + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); - return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' · ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' · ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + const hold = item.hold; + const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + (text ? text + ' · ' : '') + tip + + (matches && a.actor ? ' · actor ' + a.actor : '') + + (codeNote || contextWord ? ' · ' + (codeNote || contextWord) : '') + + (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + + (lead ? ' · hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); + const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); + const copy = `<span class="ham-chevron-copy ham-track-state${lit ? '' : ' ham-track-verdict'}">${evidenceLink}</span>${personIco}`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}"${stalled ? ' data-stalled="true"' : ''} data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -66,7 +333,10 @@ const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); const humanIcon = actorKind === 'human' || actorKind === 'maintainer'; - const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item); + // A current requirement from the server (human_attention), or a + // decision the row carries itself (045 / 085 with decision_needed, + // which the server leaves out of human_attention past the gate). + const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item) || (typeof stageTrackerNeedsHumanAsk === 'function' && !!stageTrackerNeedsHumanAsk(item)); const actorIco = actorKind && (!humanIcon || humanRequired) ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; const actorTip = stageTrackerActorTip(item); // Guarded: test harnesses lift this function by name without stageTrackerHumanReason. @@ -99,15 +369,35 @@ if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + // Evidence-based remediation (stage_tracker_remediation.go): the PR in + // progress chevron pulses only while somebody is KNOWN to be on a red + // PR (kick / claim); "unassigned" is bright but still; a fix head + // pushed after the red signal is done-style with its word. + const codeOnHead = code && String(code.head || '') === String(item.head || ''); + const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; + if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; + // Both tracks running: the PR waits on them, nobody works it. The + // stage chevron is settled-current (bright words, no amber, no pulse) + // so the row never lights three chevrons (hivecommons/hive#16540). + const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; + const waitingOnTracks = tracksRunning === 2; + if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; + const blockerNote = sg.state === 'done' && sg.blockerNote ? String(sg.blockerNote) : ''; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', blockerNote ? 'ham-blocker-note' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; + let gateCaption = ''; if (active) { tip = sg.label + (sg.description ? ' — ' + sg.description : ''); if (sg.blocked) tip += ' — ' + stageTrackerBlockedTip(item); @@ -119,7 +409,10 @@ // With merge_gate in the payload the sentence is the gate's own // (what holds it, next sweep, soak left — #15073). const gateInfo = !sg.detour && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs, trains) : null; - if (gateInfo) tip = sg.label + ' — ' + gateInfo.tip; + if (gateInfo) { + tip = sg.label + ' — ' + gateInfo.tip; + gateCaption = [gateInfo.word, gateInfo.detail].filter(Boolean).join(' · '); + } else if (!sg.detour && (curStage === 60 || curStage === 80)) tip = sg.label + ' — not yet admitted' + (item.caption || item.reason ? ' — ' + (item.caption || item.reason) : ''); else if (curStage === STAGE_TRACKER_PRE_MERGE_SOAK) tip = sg.label + ' — admitted, soaking' + stageTrackerSoakLeft(item); else if (curStage === 100) tip = sg.label + ' — admitted, merging'; @@ -141,9 +434,12 @@ if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' · head ' + (item.head || 'unknown') + ' · ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown'); + if (code.detail) tip += ' · ' + code.detail; + if (evidence) tip += ' · ' + evidence; if (code.blocker) tip += ' · ' + code.blocker; if (claimant) tip += ' · ' + stageTrackerClaimantLine(claimant, nowMs); } + if (waitingOnTracks && !sg.cap) tip = 'Waiting on CI and review, both running — ' + tip; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -170,9 +466,32 @@ // The cap chevron is the ✓ only once the PR is merged; until then // the column is the row's history and wears the history mark. if (sg.cap) inner = sg.terminal ? stageTrackerIcon(sg.number, 'ham-ico') : stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — no decisions or actions recorded yet'); - else if (active) inner = gateCue + workIco + (decision ? stageTrackerDecisionTriggerHtml(decision, word, tip) : word) + (actorIco || holderIco); - else inner = stageTrackerIcon(sg.number, 'ham-ico'); - return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' — ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' — ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; + else if (active) { + const fullTip = [tip, gateCaption || (sg.detour ? sg.detour.text : sg.short), item.caption, item.reason, + item.head ? 'head ' + item.head : '', + item.hold ? (item.hold.pill || 'Held by @' + item.hold.by) + (item.hold.reason ? ' · ' + item.hold.reason : '') : ''].filter(Boolean).join(' · '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + const caption = gateWord || word; + const text = decision ? stageTrackerDecisionTriggerHtml(decision, caption, fullTip) : caption; + const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; + // A decision's dialog is its sole hover/focus detail surface. + inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else if (fixPushed) { + const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' · '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + } else if (blockerNote) { + // The issue's own column keeps the blocker in view while the + // covering PR's strip runs (hivecommons/docs#612): the word, the + // person glyph, and the blocker's detail as the hover. + const b = item.blocker || {}; + const noteTip = [blockerNote, b.detail, item.human_attention && item.human_attention.reason].filter(Boolean).join(' — '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(noteTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(blockerNote)}</span></span>${stageTrackerIcon('human', 'ham-ico ham-actor-ico', 'Next move: human')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(noteTip)}</span></span>`; + } else inner = stageTrackerIcon(sg.number, 'ham-ico'); + return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' — ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' — ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } @@ -195,7 +514,7 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + const word = !working && ['Fixing', 'Remediating'].includes(decidedInfo.word) ? 'Fix requested' : decidedInfo.word; text = word + (decidedInfo.detail ? ' · ' + decidedInfo.detail : '') + (regressed ? ' · ' + regressed : ''); } const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { @@ -386,6 +705,23 @@ return lines.join('\n'); } + // Pure: the one open covering PR an issue's `blocked` pill stands for + // when nothing else blocks the issue — no structured blocker, no + // blocked_on dependencies, no blocked-on-PR marker, no re-check + // deadline — and that PR is parked on a human decision (085). The + // pill then reads "decision on #N" rather than a bare "blocked" + // (rationguard#431 under #480). null otherwise. + function stageTrackerBlockedForDecisionPR(item) { + if (!item || item.kind !== 'issue' || item.blocker) return null; + if (Array.isArray(item.blocked_on) && item.blocked_on.length) return null; + if (typeof stageTrackerBlockedOnPR === 'function' && stageTrackerBlockedOnPR(item)) return null; + if (/^blocked until /i.test(String(item.bucket_reason || ''))) return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && (typeof stageTrackerLinkedPROpen !== 'function' || stageTrackerLinkedPROpen(lp, item))); + if (open.length !== 1) return null; + const lp = open[0]; + const parked = Number(lp.stage) === STAGE_TRACKER_NEEDS_DECISION || (Array.isArray(lp.modifiers) && lp.modifiers.indexOf('needs-decision') >= 0) || !!(lp.decision_needed && lp.decision_needed.question); + return parked ? lp : null; + } function stageTrackerChipsHtml(item) { // A row Hive cannot finish on its own: the server's your-turn decision // (item.finisher, from the status refresh rather than the current step) @@ -419,8 +755,10 @@ // A row the scheduler withholds for open GitHub "blocked by" dependencies names them (hivecommons/hive#14765); // one blocked on a PR (hive:blocked-on marker) names it and links to it (hivecommons/hive#14952). const blockedPR = mods[0] === 'blocked' ? stageTrackerBlockedOnPR(item) : null; + const decisionPR = mods[0] === 'blocked' && !blockedPR ? stageTrackerBlockedForDecisionPR(item) : null; if (mods[0] === 'blocked' && Array.isArray(item.blocked_on) && item.blocked_on.length) text = stageTrackerBlockedTip(item); else if (blockedPR) text = 'blocked on ' + blockedPR.short; + else if (decisionPR) text = 'decision on #' + Number(decisionPR.number); // A blocked row with a hive:recheck-after deadline ("blocked until <RFC3339>") names when the sweep re-checks it. const recheck = mods[0] === 'blocked' ? /^blocked until (\S+)/i.exec(String(item.bucket_reason || '')) : null; const recheckMs = recheck ? Date.parse(recheck[1]) : NaN; @@ -432,7 +770,14 @@ // the regressed pill explains itself; a blocked pill names what it waits on; // failing all three, a draft pill does. const anyBlockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; + // A needs-human pill's hover is the full ask (hivecommons/docs#612 + // showed a bare muted "needs human" with no reason anywhere on the row). + const askable = mods[0] === 'needs-human' || mods[0] === 'needs-decision'; + const ask = (askable && typeof stageTrackerHumanAttentionOf === 'function' && stageTrackerHumanAttentionOf(item)) + || (askable && typeof stageTrackerNeedsHumanAsk === 'function' && stageTrackerNeedsHumanAsk(item)) || null; const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed + || (decisionPR ? 'Blocked only because PR #' + Number(decisionPR.number) + ' waits on a human decision' + (decisionPR.decision_needed && decisionPR.decision_needed.question ? ' — ' + decisionPR.decision_needed.question : '') : '') + || (ask ? ask.reason : '') || (holdPill && typeof stageTrackerHoldTip === 'function' ? stageTrackerHoldTip(item, Date.now()) : '') || (mods.indexOf('blocked') >= 0 && Array.isArray(item.blocked_on) && item.blocked_on.length ? 'Withheld from the scanner until ' + item.blocked_on.join(', ') + (item.blocked_on.length > 1 ? ' close' : ' closes') : '') || (anyBlockedPR ? anyBlockedPR.tip : '') @@ -445,8 +790,12 @@ // popover (what to decide, who asked, the applicable actions) instead // of a native tooltip. // A hive-set hold is a decision too (release or keep): its pill opens the same popover. - const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || decisionPR || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; if (decision) return sentinel + stageTrackerDecisionTriggerHtml(decision, inner, tip, 'ham-badge ham-badge-mod ' + cls); + // No popover to open (the ask is the issue's own while a covering + // PR drives the strip): the pill is a button that reveals the row's + // "Needs human: …" note line and carries the full reason as its hover. + if (ask && typeof stageTrackerItemKey === 'function') return sentinel + `<button type="button" class="ham-badge ham-badge-mod ${esc(cls)} ham-needs-human-pill" data-action="stageTrackerNeedsHumanReveal" data-arg0="${esc(stageTrackerItemKey(item))}" data-stop="1" title="${esc(tip)}" aria-label="${esc(text + ' — ' + ask.reason + '. Click to show why on the row.')}">${inner}</button>`; return sentinel + `<span class="ham-badge ham-badge-mod ${esc(cls)}"${tip ? ` title="${esc(tip)}"` : ''}>${inner}</span>`; } @@ -471,6 +820,9 @@ 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', + // Historical ledger entries only: the hive now re-authors its own + // exhausted PRs itself and a person's rewrite of a contributor PR is adopt. + 're-author': 'Re-author (now: adopt)', }; // "Rebase, then merge as maintainer" is merge-now on a row that needs a // rebase (hivecommons/hive#14822): the server relabels the option and diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index fefa4f23d1..e88ebd5eb4 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -19,6 +19,15 @@ const detour = (!terminal && !pushedBack && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_HUMAN_GATED && typeof stageTrackerTrainWord === 'function' && stageTrackerTrainWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (typeof stageTrackerBlockerWord === 'function' && cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION && stageTrackerBlockerWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || (cur === STAGE_TRACKER_HUMAN_GATED && item.adopted_by_state)) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; if (detour && cur === 70 && !detour.sentinel && typeof stageTrackerFixingWord === 'function') detour.text = stageTrackerFixingWord(item, detour.text); + // A bare "Needs human decision" (045 / 085) says why in the chevron + // itself — "Needs human · edits CI workflows" — when a short reason + // is known (rationguard#480: "what does 'needs human' mean?"). A + // word already carrying its why (Blocked · …, Waiting for @x · …, + // the train, the sentinel) stands. + if (detour && (cur === STAGE_TRACKER_NEEDS_DECISION || cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION) && !detour.sentinel && detour.text === STAGE_TRACKER_ACTIVE_WORD[cur] && typeof stageTrackerNeedsHumanWord === 'function') { + const nh = stageTrackerNeedsHumanWord(item); + if (nh) detour.text = nh; + } if (detour && (cur === 71 || cur === 72) && typeof stageTrackerReturnedWord === 'function') { detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); @@ -29,7 +38,7 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : code.caption) : 'Code activity unknown'; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : (code.state === 'fixing' ? String(code.caption || '').replace(/^Fixing\b/, 'Remediating') : code.caption)) : 'Code activity unknown'; if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer · activity unknown'; if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; if (detour && code && cur === 74 && codeWorking) detour.text += ' · ' + codeCaption; @@ -50,6 +59,7 @@ const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 10 && cur === 10 && typeof stageTrackerTrackingWord === 'function') { const tw = stageTrackerTrackingWord(item); if (tw) word = tw; } if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } @@ -87,7 +97,12 @@ const os = stageTrackerOpenSince(item); if (os.ms) { word += ' · since ' + stageTrackerShortAgo(nowMs - os.ms); openSince = Object.assign({ stale: !openDraft && nowMs - os.ms > STAGE_TRACKER_OPEN_STALE_DAYS * 86400000 }, os); } } - return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; + // An issue parked on a blocker whose strip a human's covering PR + // drives (via_pr): the issue's own column keeps the blocker in + // view — "Blocked · App lacks workflows permission 👤" — rather + // than reading as a passed step (hivecommons/docs#612 under #620). + const blockerNote = state === 'done' && n === STAGE_TRACKER_ISSUE_DECISION_COLUMN && item.via_pr && item.kind === 'issue' && item.blocker && typeof stageTrackerBlockerWord === 'function' && (item.needs_human === true || (typeof stageTrackerItemNeedsHuman === 'function' && stageTrackerItemNeedsHuman(item))) ? stageTrackerBlockerWord(item) : ''; + return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, blockerNote, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; }); segs.push({ number: STAGE_TRACKER_TERMINAL, code: '', short: 'Merged', label: 'Merged', description: 'Merged — the pipeline is complete', state: terminal ? 'active' : 'todo', terminal, cap: true, detour: null }); return segs; @@ -109,7 +124,11 @@ 20: '<rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/>', 30: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="5" r="1.5"/><path d="M4 4.5v7M12 6.5c0 3-8 1-8 4"/>', 40: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="12" r="1.5"/><path d="M4 4.5v7M4 6c0 3 6 2 6.5 5"/>', + // Column 50 splits into two tracks: CI wears a flask (checks run, no + // verdict implied), Review keeps the eye. The eye alone on both read + // as one duplicated glyph (operator, 2026-11-03). 50: '<path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/>', + ci: '<path d="M5.5 1.5h5M6.5 1.5v4.6L2.6 12.9a1 1 0 0 0 .9 1.6h9a1 1 0 0 0 .9-1.6L9.5 6.1V1.5"/><path d="M4.4 10.5h7.2"/>', // Merge queue: the same railcar as the column header and train chip // (STAGE_TRACKER_TRAIN_ICON_PATH in tracker-words.js; a test keeps them equal). 80: '<rect x="2" y="3.5" width="12" height="7" rx="1.5"/><path d="M2 7.5h12M6.5 3.5v4M10.5 3.5v4M4 13.5l-1.5 1.5M12 13.5l1.5 1.5"/><circle cx="5" cy="12.5" r="1.5"/><circle cx="11" cy="12.5" r="1.5"/>', diff --git a/src/pkg/dashboard/static-src/js/tracker-words-core.js b/src/pkg/dashboard/static-src/js/tracker-words-core.js index f3c9d3328d..fa4bd49384 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -40,10 +40,44 @@ if (state === 'resolving-conflicts') return 'Adopting · fixer resolving conflicts'; return 'Adopted → #' + by; } - const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human'; + // "Waiting for @clubanderson · rerun shared ci on GitHub": the person + // owed the step is named when the author is one (a hive / bot / clanker + // author cannot grant the permission; a maintainer is asked instead). + const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Waiting for'; + const STAGE_TRACKER_UNAUTHORIZED_WHERE = 'on GitHub'; + function stageTrackerUnauthorizedWho(item) { + // An issue row drawn on its one covering PR names that PR's author. + const linked = item && item.via_pr && Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => lp && String(lp.unauthorized_step || '').trim()) : []; + const src = linked.length === 1 ? linked[0] : item; + const author = String((src && src.author) || '').trim().replace(/^@/, ''); + const kind = String((src && src.author_kind) || ''); + if (author && kind !== 'hive' && kind !== 'bot' && kind !== 'clanker') return '@' + author; + return 'a maintainer'; + } function stageTrackerUnauthorizedWord(item) { const step = String((item && item.unauthorized_step) || '').trim(); - return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ': ' + step : ''; + return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ' ' + stageTrackerUnauthorizedWho(item) + ' · ' + step + ' ' + STAGE_TRACKER_UNAUTHORIZED_WHERE : ''; + } + // A PR parked at 085 because a person has to act ON THE PR (rerun CI, + // approve workflow runs, resolve a permission, answer review findings + // or red checks still open on its head) is not queued, merging or + // merge-ready: it lights PR in progress, never Merge queue. Merge + // queue is only for rows actually queued / merging / merged, or a + // merge-ready PR (review approved, CI green on this head) parked on a + // merge decision. A bare 085 with no track evidence keeps the gate: + // the person decides there (hive#14821). Hive's own #16524 read + // "Awaiting human: rerun shared ci" under Merge queue with CI unknown + // and review findings open. Mirrors stageTrackerPersonActsOnPR in Go. + function stageTrackerPersonActsOnPR(item) { + if (!item || (item.via_pr ? 'pr' : item.kind) !== 'pr' || Number(item.stage) !== STAGE_TRACKER_HUMAN_GATED) return false; + if (item.merge_gate && item.merge_gate.state) return false; + if (item.merge_train && item.merge_train.state) return false; + const onHead = a => !!a && (!a.head || !item.head || String(a.head) === String(item.head)); + const review = onHead(item.review_activity) ? item.review_activity : null; + const ci = onHead(item.ci_activity) ? item.ci_activity : null; + const mergeReady = !!(review && review.state === 'approved' && ci && ci.state === 'passing'); + if (String(item.unauthorized_step || '').trim()) return !mergeReady; + return !!((review && review.state !== 'approved') || (ci && ci.state !== 'passing')); } // A parked issue with a structured blocker (item.blocker, #15099) reads // "Blocked · App lacks workflows permission", never "Needs human @@ -54,6 +88,56 @@ const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' · ' + short : ''; } + // Why a person is needed, in a few words, for the row itself to say + // (hivecommons/docs#612, rationguard#480: "it's not clear reading the + // row why a human is needed"). The structured blocker's short text + // first; else the server's reason key (stage_actor.human_reason, the + // human-merge reason, the clause after "—" in stage_actor.why) through + // a small map of known reasons; else that clause's first sentence. + const STAGE_TRACKER_NEEDS_HUMAN_SHORT = { + 'workflow path': 'edits CI workflows', + 'hive signoff attribution': 'hive signoff attribution', + 'high-risk review': 'high-risk review', + 'optional check failing': 'optional check failing', + 'capability:workflows-permission': 'App lacks workflows permission', + }; + const STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX = 48; + const STAGE_TRACKER_NEEDS_HUMAN_WORD = 'Needs human'; + function stageTrackerNeedsHumanShort(item) { + if (!item) return ''; + const b = item.blocker; + if (b && String(b.short || '').trim()) return String(b.short).trim(); + if (b && STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]; + const sa = item.stage_actor || {}; + const afterDash = s => { const t = String(s || ''); const i = t.indexOf(' — '); return i >= 0 ? t.slice(i + 3) : ''; }; + const keys = [sa.human_reason, item.human_merge_reason, afterDash(sa.why), afterDash(item.caption), item.reason]; + for (const k of keys) { + const key = String(k || '').replace(/\s+/g, ' ').trim().toLowerCase(); + if (key && STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]; + } + const clause = String(afterDash(sa.why) || sa.human_reason || '').replace(/\s+/g, ' ').trim().split(/[;.](?:\s|$)/)[0].trim(); + if (!clause) return ''; + return clause.length > STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX ? clause.slice(0, STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…' : clause; + } + // The lit 045 / 085 chevron's caption: "Needs human · edits CI + // workflows" rather than a bare "Needs human decision". '' when no + // short reason is known (the plain stage word stands). + function stageTrackerNeedsHumanWord(item) { + const short = stageTrackerNeedsHumanShort(item); + return short ? STAGE_TRACKER_NEEDS_HUMAN_WORD + ' · ' + short : ''; + } + // A decomposed parent at 010 (server `open_children` > 0, hive#16481) + // reads "Tracking · 3/4" (children known) or "Tracking · 1 open child", + // never "Actionable": the scanner leaves it to its children, so the + // row is not a stuck unclaimed issue. + const STAGE_TRACKER_TRACKING_WORD = 'Tracking'; + function stageTrackerTrackingWord(item) { + const open = Number(item && item.open_children) || 0; + if (!(open > 0) || !item || item.kind !== 'issue') return ''; + const c = item.children; + if (c && Number(c.total) > 0) return STAGE_TRACKER_TRACKING_WORD + ' · ' + (Number(c.completed) || 0) + '/' + Number(c.total); + return STAGE_TRACKER_TRACKING_WORD + ' · ' + open + ' open child' + (open === 1 ? '' : 'ren'); + } // Issue-slot placeholders for a closing reference whose title the server // could not resolve (the issue is closed and unreadable, or of unknown state). const STAGE_TRACKER_CLOSED_ISSUE_TITLE = '(closed issue)'; @@ -232,7 +316,7 @@ // the chevron and the caption name one blocker (hive's own #15577 read // "Merge queued · 1st" while its caption said "check build-and-test // still running"). Keys below STAGE_TRACKER_MERGE_READY only. - const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Fixing', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; // Pure: true when the row's queue slot is a forecast — the server says // so (merge_train.provisional), or, from an older server, the row's // own stage is short of the merge gate. @@ -339,7 +423,7 @@ // (mergeTrainHead* in Go) — short enough for a chevron. A head on a // person says what the person has to do (the owner's ask: "waiting on // #15425 (needs maintainer merge)"), not "waiting for a maintainer". - const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being fixed by its author', unknown: 'head not in this view' }; + const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being remediated by its author', unknown: 'head not in this view' }; // Pure: the short reason a stalled head is stuck — the head_state // table, a human-decision head told apart by its reason, else the // head's own plain-word reason cut at its first clause. diff --git a/src/pkg/dashboard/static-src/js/tracker-words-gate.js b/src/pkg/dashboard/static-src/js/tracker-words-gate.js index 3c7690a726..4ac06300e8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -19,7 +19,8 @@ if (!d || d.effect !== 'pending' || !d.text) return null; nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); const sep = String(d.text).indexOf(' · '); - const word = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const rawWord = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const word = rawWord === 'Fixing' ? 'Remediating' : rawWord; let detail = sep > 0 ? d.text.slice(sep + 3) : ''; const until = d.next_at ? Date.parse(d.next_at) : 0; if (until > nowMs) detail += (detail ? ' · ' : '') + 'in ' + stageTrackerShortLeft(until - nowMs); @@ -28,10 +29,16 @@ // Pure: the in-flight caption for a recorded decision — from the // server's projection when it has one, else from the result's action. const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting · opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; + // A park-keeping verdict by what it recorded: a recommendation only + // when there is one (recommend-only); owner-only / operator-action hand + // the decision back, so the caption says so (hivecommons/hive#16572). + const STAGE_TRACKER_PARK_KEPT_ACTING = { 'recommend-only': 'Recommendation recorded', 'owner-only': 'Your decision needed · owner sign-off', 'operator-action': 'Your action needed · operator step' }; function stageTrackerDecidedActing(result, item) { const d = item && item.decided; if (d && d.acting) return d.acting; - return STAGE_TRACKER_DECIDED_ACTING[result && result.action] || 'Hive decided…'; + const action = result && result.action; + if (action === 'recommended') return STAGE_TRACKER_PARK_KEPT_ACTING[result.verdict] || 'Your decision needed'; + return STAGE_TRACKER_DECIDED_ACTING[action] || 'Hive decided…'; } // Pure: the ✓ badge's first line for a decided row: the decision name // and who / what triggered it — "you · Let hive decide · hive chose diff --git a/src/pkg/dashboard/static-src/js/tracker-words-stage.js b/src/pkg/dashboard/static-src/js/tracker-words-stage.js index 297c8b6ff8..2a43790182 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-stage.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-stage.js @@ -135,7 +135,7 @@ case 45: return 'Needs a human decision'; case 50: return 'Waiting for review' + viaPR; case 60: return 'Reviewed' + viaPR; - case 70: return 'Fixing review findings' + viaPR; + case 70: return 'Remediating CI or review findings' + viaPR; case 71: return 'Waiting on the author' + viaPR; case 72: return 'Back with the contributor' + viaPR; case 74: return 'Hive took it over' + viaPR; @@ -227,7 +227,7 @@ // Stage → operator phrase, mirrored from stageTrackerStagePhrase // (stage_tracker_vocabulary.go): every string the page renders names a // stage by its chevron's words, never by a code ("060 reviewed"). - const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed · waiting for merge admission', 70: 'being fixed by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; + const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed · waiting for merge admission', 70: 'being remediated by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; // Pure: a stage's name in plain words for cues and tooltips — its short // word when the stages table has one, else its label with the lane's // "stage/060-" slug prefix dropped and the slug humanised ("Reviewed"). diff --git a/src/pkg/dashboard/static-src/js/welcome.js b/src/pkg/dashboard/static-src/js/welcome.js index 6b80577785..e0ded66cc8 100644 --- a/src/pkg/dashboard/static-src/js/welcome.js +++ b/src/pkg/dashboard/static-src/js/welcome.js @@ -536,8 +536,7 @@ updateWelcomeProgress(); } - checkGHAuth(); + dashboardScheduleWork('welcome-gh-auth', checkGHAuth).catch(console.error); dashboardSetInterval('welcome-gh-auth', checkGHAuth, GH_AUTH_CHECK_INTERVAL_MS); initWelcomeDialog(); initNPSSurvey(); - diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 2f049665d1..62820db249 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -33,10 +33,10 @@ css/welcome.css css/review-campaigns.css css/kiosk.css css/popout.css -css/matrix.css +css/reader.css css/variables.css glue/style-close-body-open.html -js/matrix.js +js/reader.js js/boot.js glue/boot-script-close.html html/auth.html @@ -58,6 +58,7 @@ html/tracker.html html/faq.html glue/main-script-open.html js/core.js +js/progressive.js js/feedback.js js/sections.js js/layout.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 700cf7b120..d00e700155 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -42,8 +42,11 @@ --font-ui: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace; /* Type ramp — section headers / card titles / labels only; body-copy sizes stay. */ - --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; - --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; + --fs-2xs: .6rem; --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; + --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; --fs-2xl: 1.5rem; --fs-3xl: 2rem; + /* The A6 ends of the ramp (2xs/2xl/3xl) were only ever defined inside + .config-modal, so var(--fs-2xs) elsewhere fell back to the 16px body + size (hivecommons/hive#16601). Same values in light and dark. */ /* Touch floor: iOS Safari zooms the page when a focused control is under 16px. */ --fs-touch: 16px; /* Mobile icon-only buttons (section ?/⚙/grip, topbar chips): a fixed @@ -1424,7 +1427,7 @@ grid, the slot takes the Merge gate column plus the ✓ cap and right-aligns the chip over the gate. It never wraps with the filter bar, so the chip stays put whatever the toolbar does. */ - .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-5) var(--sp-2); } + .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-4) var(--sp-2); } /* Each entry is fenced by a hairline above it and lights up as a whole on hover, so a tall row (wrapped title, ↳ PR line) still reads as one block: its chip and age can only belong to the strip they sit beside. */ @@ -1432,40 +1435,44 @@ .ham-row:hover { background: color-mix(in srgb, var(--text) 4%, transparent); border-radius: var(--r-sm); } /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a - PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - the cap column is kept for the modifier chip and the since column is - an empty spacer (the time on step rides the strip row's since cell, in - line with the chevrons). Both cells wrap rather than collide; the lead - keeps a clear gap before the PR column. The spanning cells' flex-basis - absorbs the gaps they cover so the PR cell starts exactly at the PR in - progress chevron. */ + PR cell spanning PR in progress..Merge gate carries "[icon] #N title" + with the modifier chips / action buttons right-anchored on that same + line (margin-left: auto), wrapping under the PR metadata only when + there is no room. No separate toolbar line: the chevrons sit directly + under the title line. The since column is an empty spacer (the time on + step rides the strip row's since cell). + Explicit grid spans share the chevrons' tracks, including the two + concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } .ham-head-cols { flex: 1 1 auto; min-width: 0; min-height: 1.3em; align-items: flex-start; } .ham-head-cols .ham-strip { height: auto; } .ham-head-cols .ham-seg { background: transparent; clip-path: none; align-items: flex-start; justify-content: flex-start; padding: 0 var(--sp-2) 0 var(--sp-4); white-space: normal; } - /* Lead = exactly three of the six equal chevrons (half of the strip - minus the fixed 4em cap and the six gaps) plus the two gaps between - them, so the PR cell starts at the PR in progress chevron; the PR cell takes what - is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } - .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } - /* The PR cell is one line: connector, author icon + #N + title, lineage - chip and base pill sit side by side; the lineage chip gives way first - (flex-shrink 2), then the title (1), the pills and the connector never shrink - (hivecommons/hive "consolidate from 3 lines of text to 1"). */ - .ham-head-cols .ham-seg.ham-head-pr { flex: 1 1 0; flex-direction: row; flex-wrap: nowrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: hidden; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico, .ham-head-cols .ham-seg.ham-head-pr > .ham-badge { flex: 0 0 auto; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { display: block; flex: 0 2 auto; min-width: 7em; overflow: hidden; text-overflow: ellipsis; } + .ham-head-cols .ham-seg.ham-head-lead { grid-column: 1 / var(--ham-pr-start); grid-row: 1; padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-pr { grid-column: var(--ham-pr-start) / -2; grid-row: 1; flex-direction: row; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: visible; padding: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } - .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - /* The chip hugs the bottom of the title block (align-items: flex-end - inside the stretched cap cell): on a two-line title it sits on the - second line, directly over the strip it describes, never up at the - previous entry's edge. */ - .ham-head-cols .ham-seg.cap { flex: 0 0 auto; min-width: 4em; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; } - .ham-head-main { display: flex; flex: 1; align-items: center; gap: var(--sp-3); min-width: 0; overflow: hidden; } - .ham-head-main > .ham-badge { flex: 0 0 auto; } + /* The PR ref shares the first line with the right-anchored pills: it + grows into the free space but keeps a readable floor, so pills wrap + under it only when the line is genuinely full. */ + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 1 1 0; min-width: min(100%, 20em); } + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line > .ham-pr-ref { flex: 1 1 0; min-width: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges { position: static; flex: 0 1 auto; flex-wrap: wrap; justify-content: flex-end; margin-left: auto; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges:empty { display: none; } + .ham-head-cols .ham-seg.ham-head-tools { align-items: flex-start; } + .ham-head-cols .ham-seg.ham-head-tools:has(> .ham-badges:empty) { display: none; } + .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } + .ham-head-main > .ham-badge { flex: 0 1 auto; } + /* The title fills whatever is left of the first line beside its chips + (flex-basis 0) and only wraps its own words when there is no room; + with a max-content basis (flex: 0 1 auto) a wrapping flex container + drops the whole title onto a second line as soon as it cannot fit + entirely, even with half the row free (hivecommons/hive#16454). */ + .ham-head-main > .ham-title { flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-title { flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } .ham-linked-ico { color: var(--text-faint); font-size: var(--fs-xs); margin-right: var(--sp-1); } @@ -1560,8 +1567,8 @@ .ham-preparation-node:focus-visible { outline: var(--focus-ring-width) solid var(--ham-train-accent); outline-offset: var(--sp-1); } .ham-row.ham-preparation-gap::before, .ham-sub.ham-preparation-member.ham-preparation-gap::before { border-left-style: dashed; } .ham-preparation-unverified > .ham-strip-row > .ham-preparation-node::after { background: var(--bg); box-shadow: 0 0 0 var(--line-width) var(--ham-train-accent); } - .ham-preparation-comment { animation: none; } - .ham-human-context { animation: none; } + .cue-event.ham-preparation-comment { animation: none; } + .cue-event.ham-human-context { animation: none; } /* Mixed issue trees keep their existing children; only actual prep PRs receive a rail, at the original gutter offset minus the parent inset. */ .ham-row > .ham-preparation-head { margin-left: calc(-1 * var(--sp-2)); } @@ -1667,22 +1674,14 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } - /* The chevron strips (and the column header) are a grid; the title - line's strip is not — its lead / PR / cap cells size by flex. The - ham-head-cols class sits on the strip's row, not on the strip, so - the exclusion is spelled on the row: on the strip itself it matched - every strip and put the title line's cap chips in one chevron-wide - column, where wide chips spilled left over the PR title. */ - .ham-strip-row:not(.ham-head-cols) > .ham-strip { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 1; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } - .ham-track-name { font-weight: var(--fw-semibold); } - .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + /* The concurrent CI / Review lanes are chevrons like every other stage + (same clip-path, padding and height — the boxed card opt-out of + #16384 is gone); their lane state reads through fill, tint and text + colour exactly as done / todo / active do, never a border or ring, + which the notched polygon would clip anyway. */ .ham-track-state a { color: inherit; } - .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } - .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } - .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -1692,17 +1691,23 @@ /* The holder's offline / not-registered state is muted: a flag, not an alarm. */ .ham-holder-presence { margin-right: 0; color: var(--text-faint); font-weight: normal; } .ham-holder-presence.ham-presence-offline { --ham-presence-color: var(--text-faint); } - /* A word with a holder ("PR in progress · @bob's clanker") stays on one - line: the stage word keeps its width and the name gives way with an - ellipsis before anything wraps (hivecommons/hive#15541). */ - .ham-seg-t.ham-has-holder, .ham-detour.ham-has-holder { display: inline-flex; align-items: baseline; min-width: 0; max-width: 100%; white-space: nowrap; } - .ham-has-holder > .ham-holder { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: pre; } .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } + /* Evidence-based remediation on the PR in progress chevron: a red PR + nobody has picked up is bright and still; a pushed fix head is a + done-style step that keeps its word (stage_tracker_remediation.go). */ + .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } + .ham-seg.done.ham-fix-pushed { color: var(--green); } +/* A done decision column that still names the blocker a person must + clear while a covering PR drives the strip (hivecommons/docs#612). */ +.ham-seg.done.ham-blocker-note { color: var(--amber); opacity: 1; } +/* The "needs human" pill is a button: click scrolls to the Needs human line. */ +.ham-needs-human-pill { cursor: pointer; font: inherit; } +.ham-needs-human-pill:hover, .ham-needs-human-pill:focus-visible { text-decoration: underline; } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } - .ham-sub { display: grid; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } + .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } /* Only the two moving buckets animate (see stageTrackerMotion): the hive acting = gentle pulse; waiting on a person = slower amber→red breathe. A lit step with no data-motion (Open, Open · hold, Claimed, …) is a @@ -1712,6 +1717,65 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } + /* A CI / Review track wears its own state on the current head + (hivecommons/hive#16484): in progress = the full .active fill, done = + .done, a finding (red CI, changes requested) = .failing in the error + colour, not started = .todo with the glyph alone. No muted + "current-phase" tint: the operator reads the words, not the shade. + Only fresh observed work earns the pulse. */ + .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } + /* A FILLED chevron means "this is where the item is / what moves now" + (hivecommons/hive#16540). A CI / Review track is filled only while it + runs (.active, amber). Every other state is words on the muted field + with the semantic colour on text and glyph only: green for passed / + approved, red for a finding, muted for pending, decided or not started. */ + .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* A not-yet-run track in the current phase (CI unknown on a 050 row, + Review queued beside running CI) keeps the same muted field as its + done / failing neighbours — the glyph alone, neutral — so the current + phase stays a visibly filled location (hivecommons/hive#16599). */ + .ham-seg.ham-activity-track.todo.ham-current { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; } + /* Words without motion (checks not reported, unknown evidence, a row + parked on a person): current-phase text on a muted field, never amber. */ + .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* The stage chevron while both tracks run: bright words, no amber, no pulse. */ + .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } + .ham-seg.active.ham-settled-current::before { display: none; } + .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve — done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } + /* The count words stay on one line and ellipsize instead of wrapping. */ + .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } + /* A settled verdict is the glyph alone (green passed / approved, red + failed / changes requested — the .done / .failing colours above); + the words live in the tooltip. Same box, same height: only the + trailing gap goes and the stroke firms up so the colour reads. */ + .ham-chevron-copy.ham-track-verdict .ham-ico { margin-right: 0; stroke-width: 2; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -1741,10 +1805,32 @@ after the word ("next sweep in 42s", "7m left") is muted. */ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } - /* The detail is a fixed short phrase; should a long one ever reach it - (hivecommons/docs#512 drew a raw GitHub URL across the column) it is - clipped with an ellipsis rather than overflowing the chip. */ - .ham-gate-detail { font-weight: normal; opacity: 0.85; white-space: nowrap; font-variant-numeric: tabular-nums; display: inline-block; vertical-align: bottom; max-width: 12em; overflow: hidden; text-overflow: ellipsis; } + .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } + /* Every physical chevron is one caption line tall (--ham-chevron-text-lines: + 1, the clamp below ellipsises the rest): the strip rides directly under + the title line as a ~20px band, the density the tracker had before + hivecommons/hive#16454 doubled it with a two-line budget and sp-2 + vertical padding. The grid row sizes to content with that one-line + floor so icon-only cells and siblings share the row's height, never a + fixed box. The portal tooltip is outside the clipped polygon; keyboard + focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } + /* min-height: 0 and no ::before ring: on phones / coarse pointers + responsive.css turns every .config-info into a --tap-target (40px) + square with a drawn ring; the chevron's info wrapper is not that + icon, and its 40px floor made every chevron a 44px box. */ + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; min-height: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info::before { content: none; } + .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } + .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } + /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with + their icons, sit centred in the chevron as before; a wrapped second + line is centred under the first rather than ragged-left. */ + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } + .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { min-height: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ Owner request: a viewer must always read where an item stands, @@ -1841,7 +1927,7 @@ page text: ≥ 15:1 in both themes, see the contrast test) above the stripes and the pulse overlay, on one line with an ellipsis. */ .cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; } - .ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .ham-seg.active > .cue-acting-cap > .cue-acting-spin { vertical-align: -1px; margin-right: var(--sp-2); } .cue-event { display: flex; align-items: baseline; gap: var(--sp-2); margin: 0; padding-left: var(--sp-5); font-size: var(--fs-xs); color: var(--muted); overflow-wrap: anywhere; animation: cue-event-in 0.4s ease-out; } .cue-event-who { font-weight: var(--fw-medium); color: var(--text); } @@ -2007,7 +2093,7 @@ .ham-row { position: relative; } .ham-row:focus-visible { outline: var(--focus-ring-width) solid var(--accent); outline-offset: calc(-1 * var(--focus-ring-width)); border-radius: var(--r-sm); } .ham-row.ham-selected { background: color-mix(in srgb, var(--accent) 10%, transparent); box-shadow: inset var(--sp-1) 0 0 var(--accent); border-radius: var(--r-sm); } - .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-5); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } + .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-4); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } /* A nested PR sub-row carries its own gutter (checkbox + ⋯), so each PR under an issue is selected and acted on by itself (two PRs under one issue, one decision each — the owner's 2026-10-28 report). The @@ -2080,15 +2166,21 @@ .ham-decision-act[aria-disabled="true"] { color: var(--text-faint); border-style: dashed; cursor: default; opacity: 0.6; } .ham-decision-act[aria-disabled="true"]:hover { background: transparent; border-color: var(--line-subtle); } .ham-decision-act.ham-decision-more { color: var(--text-muted); } - /* The row's inline lead action (the ⋯ menu's lead entry, in sight): a - small primary pill in the chip slot, the popover lead's recipe, the - row's cue colour; dashed and faint with its reason when the viewer - may not take it. */ - .ham-lead-act { padding: 0 var(--sp-3); border: var(--line-width) solid var(--cue-state, var(--accent)); border-radius: var(--r-pill); background: color-mix(in srgb, var(--cue-state, var(--accent)) 10%, transparent); color: var(--cue-state, var(--accent)); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.4; cursor: pointer; white-space: nowrap; } - .ham-lead-act:hover, .ham-lead-act:focus-visible { background: color-mix(in srgb, var(--cue-state, var(--accent)) 22%, transparent); outline: none; } - .ham-lead-act:focus-visible { box-shadow: 0 0 0 var(--line-width) var(--accent); } - .ham-lead-act.ham-menu-danger { color: var(--red); border-color: var(--red); background: color-mix(in srgb, var(--red) 10%, transparent); } - .ham-lead-act[aria-disabled="true"] { color: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; } + /* The row's inline action pills (the ⋯ menu's lead entry, and "Let hive + decide" beside it on a row parked on a human decision): real buttons + that must not pass for the record pills in the same slot ("adopted + from #N", the base branch — muted outlines, no hover). So: a filled + chip, a trailing ▸ glyph, pointer cursor, hover lift and focus ring. + Primary (the lead) fills amber; secondary (delegate) fills neutral; + danger (a server-led close) fills red. Dashed, faint and glyph-less + with its reason when the viewer may not take it. */ + .ham-lead-act { --ham-act-fill: var(--amber); --ham-act-ink: var(--bg); display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-3); border: var(--line-width) solid var(--ham-act-fill); border-radius: var(--r-pill); background: var(--ham-act-fill); color: var(--ham-act-ink); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.5; cursor: pointer; white-space: nowrap; transition: filter 120ms ease, box-shadow 120ms ease; } + .ham-lead-act::after { content: '▸'; opacity: 0.85; } + .ham-lead-act.ham-act-secondary { --ham-act-fill: var(--panel-strong); --ham-act-ink: var(--text); border-color: var(--line-strong); } + .ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red); --ham-act-ink: var(--bg); } + .ham-lead-act:hover, .ham-lead-act:focus-visible { filter: brightness(1.12); outline: none; box-shadow: 0 0 0 var(--line-width) var(--bg), 0 0 0 calc(var(--line-width) * 3) var(--ham-act-fill); } + .ham-lead-act[aria-disabled="true"] { --ham-act-fill: transparent; --ham-act-ink: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; filter: none; box-shadow: none; } + .ham-lead-act[aria-disabled="true"]::after { content: none; } /* Busy (Let hive decide gathering its preview) also sets aria-disabled, so this compound rule sits after the disabled one and wins: the working colour, not faint/dashed. */ .ham-lead-act[aria-busy="true"][aria-disabled="true"] { cursor: progress; opacity: 1; border-style: solid; border-color: var(--cue-work); background: color-mix(in srgb, var(--cue-work) 10%, transparent); color: var(--cue-work); } @@ -2105,21 +2197,16 @@ a needs-human step keeps a steady red tint so it still stands out. */ @media (prefers-reduced-motion: reduce) { .ham-seg.active { animation: none; box-shadow: inset 0 0 0 2px var(--surface-0); } .ham-seg.active[data-motion]::before { display: none; } .ham-seg.active[data-motion="needs-human"] { background: color-mix(in srgb, var(--amber) 45%, var(--red)); } } @media (max-width: 1100px) { - /* Keep the aligned progress strip compact; put its active step in a - wrapping caption instead of squeezing actionable words into a chevron. */ - .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + /* Stack headers, but keep the same two-line progress text budget. */ + .ham-cols .ham-seg-t { display: none; } .ham-cols .ham-track-head .ham-seg-t { display: inline; } - .ham-track-state { display: none; } - .ham-track-code-note, .ham-track-context { display: none; } - .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } .ham-head-cols { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2) var(--sp-3); } .ham-head-cols > .ham-strip { display: contents; } - .ham-head-cols .ham-seg.ham-head-lead, .ham-head-cols .ham-seg.ham-head-pr { grid-column: 1 / -1; padding: 0; } + .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-start; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } @@ -2127,6 +2214,11 @@ .ham-cols .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-cols .ham-seg.cap { flex-basis: 2em; } } + @media (max-width: 640px) { + #activity-monitor-panel { --ham-compact-min-width: 60em; } + .ham-row > .ham-strip-row, .ham-sub > .ham-strip-row, .ham-cols > .ham-strip-row { overflow-x: auto; } + .ham-row > .ham-strip-row > .ham-strip, .ham-sub > .ham-strip-row > .ham-strip, .ham-cols > .ham-strip-row > .ham-strip { min-width: var(--ham-compact-min-width); } + } /* Movement animation: when an item's lit chevron changes column between two refreshes, the chosen effect (settings gear → Movement animation) plays once on that row. Overlays live in .ham-anim-layer, an absolute @@ -3296,23 +3388,30 @@ .overview-repo-filter { display: grid; gap: var(--sp-2); max-height: min(16rem, 32vh); overflow: auto; padding: var(--sp-2); border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg); } .overview-settings-links { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .overview-headline { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); } - .overview-kpis { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } + /* No headline child may widen the single auto column: on a phone a nowrap + stale pill otherwise stretches the track and every KPI tile with it + (hivecommons/hive#16601). */ + .overview-headline > * { min-width: 0; max-width: 100%; } + .overview-kpis { display: grid; min-width: 0; grid-template-columns: repeat(7, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } .overview-kpi-operator { display: inline-flex; align-items: center; justify-content: center; align-self: start; padding-top: var(--sp-3); color: var(--muted); font-size: var(--fs-lg); font-weight: 800; line-height: 1; } .overview-kpi-coverage-spacer { width: 1px; min-height: 100%; background: var(--border); opacity: 0.8; } - .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; white-space: nowrap; } + .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; justify-self: start; min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } @media (max-width: 1799px) { .overview-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } .overview-kpi-operator, .overview-kpi-coverage-spacer { display: none; } } @media (max-width: 720px) { .overview-kpis { grid-template-columns: minmax(0, 1fr); } } .overview-kpi-range { display: inline-flex; gap: var(--sp-1); } .overview-kpi-range-btn { min-width: 2rem; height: 1.25rem; border: 1px solid var(--border); border-radius: var(--r-pill); background: var(--bg); color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; cursor: pointer; } .overview-kpi-range-btn.active { border-color: var(--accent); color: var(--accent); } - .overview-kpi { display: grid; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } + .overview-kpi { display: grid; min-width: 0; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } .overview-kpi:hover { border-color: var(--accent); } .overview-kpi-value { font-size: var(--fs-lg); font-weight: 800; font-variant-numeric: tabular-nums; } .overview-kpi-label { color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; } - .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; } - .overview-kpi-spark { min-height: 24px; display: flex; align-items: end; margin-top: var(--sp-1); } - .overview-kpi-spark .sparkline { width: 100%; } - .overview-kpi-spark svg { width: 100%; height: 24px; } + .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; min-width: 0; overflow-wrap: anywhere; } + .overview-kpi-spark { min-height: 24px; min-width: 0; display: flex; align-items: end; margin-top: var(--sp-1); } + .overview-kpi-spark .sparkline { width: 100%; max-width: 100%; min-width: 0; } + .overview-kpi-spark svg { width: 100%; max-width: 100%; height: 24px; } + /* Phone: keep the tile label/subline at the compact body sizes the tiles + shipped with rather than the 2xs helper size. */ + @media (max-width: 720px) { .overview-kpi-label { font-size: var(--fs-base); } .overview-kpi-subline { font-size: var(--fs-md); } } .overview-kpi-coverage[data-coverage-state="success"] { --overview-coverage-color: var(--green); } .overview-kpi-coverage[data-coverage-state="warn"] { --overview-coverage-color: var(--yellow); } .overview-kpi-coverage[data-coverage-state="danger"] { --overview-coverage-color: var(--red); } @@ -4590,6 +4689,7 @@ .cmp-banner { border: 1px solid color-mix(in srgb, var(--yellow) 45%, transparent); background: color-mix(in srgb, var(--yellow) 8%, transparent); border-radius: var(--r); padding: var(--sp-4) var(--sp-5); margin-bottom: var(--sp-6); font-size: var(--fs-sm); } .cmp-banner strong { color: var(--text); } .cmp-banner-detail { color: var(--muted); margin-top: var(--sp-2); } + ul.cmp-banner-detail { margin: var(--sp-2) 0 0 var(--sp-5); } .cmp-framework { display: flex; gap: var(--sp-4); align-items: flex-start; padding: var(--sp-3) var(--sp-0); cursor: pointer; } .cmp-framework input { width: auto; margin-top: var(--sp-1); } .cmp-framework-name { font-weight: 600; color: var(--text); } @@ -7180,8 +7280,8 @@ boot.js set body.kiosk-cta-on (kiosk=1 and not cta=off), so the operator dashboard never shows it. Bottom-right, under the toast stack's corner and above the tracker; sized to read off a 720p Twitch transcode of a - 1920x1080 capture (URL >= 22px). The Matrix view (css/matrix.css) lifts - it above its fixed canvas and dims it. */ + 1920x1080 capture (URL >= 22px). The Code activity view (css/reader.css) + lifts it above its fixed overlay and dims it. */ #kiosk-cta { display: none; } body.kiosk-cta-on #kiosk-cta { display: flex; align-items: center; gap: var(--sp-4); @@ -7340,23 +7440,32 @@ body.display-shift #activity-monitor-section { animation: none; } body.display-mode #activity-monitor-panel, body.display-mode #activity-monitor-meta, body.display-mode #activity-monitor-sticky, body.display-mode #activity-monitor-native-queue { transition: none; } } -body.matrix-mode #hive-dashboard-root { display: none !important; } -body.matrix-mode #hive-matrix { - --matrix-bg: #000804; - --matrix-fg: #52ed86; - --matrix-surface: #000000; - --matrix-text: #e8f5eb; - --matrix-muted: #b8ccbb; - position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; +body.reader-mode #hive-dashboard-root { display: none !important; } +body.reader-mode #hive-reader { + --reader-bg: #0b0f0c; + --reader-surface: #121a14; + --reader-text: #e8f5eb; + --reader-muted: #b8ccbb; + --reader-add: #7ee2a0; + --reader-del: #ff8f8f; + --reader-tail: 10rem; + position: fixed; inset: 0; z-index: 100000; display: flex; flex-direction: column; + background: var(--reader-bg); color: var(--reader-text); font: 20px/1.5 monospace; } -body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } -body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } -body.matrix-mode .matrix-list small { color: var(--matrix-muted); } -body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; } +body.reader-mode .reader-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-5); padding: var(--sp-3) var(--sp-5); color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-status { flex: 1 1 auto; color: var(--reader-text); } +body.reader-mode .reader-pause { font: inherit; color: var(--reader-text); background: var(--reader-surface); border: 1px solid var(--reader-muted); border-radius: var(--radius-sm); padding: var(--sp-2) var(--sp-6); cursor: pointer; } +body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-0) var(--sp-5) var(--reader-tail); } +body.reader-mode .reader-card { max-width: 80rem; margin: 0 auto 1.5rem; padding: var(--sp-3) var(--sp-5); background: var(--reader-surface); border-radius: var(--radius); } +body.reader-mode .reader-meta { display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-repo { color: var(--reader-text); font-weight: 600; } +body.reader-mode a.reader-repo { text-decoration: underline; } +body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } +body.reader-mode .reader-add { color: var(--reader-add); } +body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode .reader-context { color: var(--reader-text); } +body.reader-mode #hive-reader [hidden] { display: none !important; } +body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } .var-empty{color:var(--muted);font-size:var(--fs-sm);padding:var(--sp-2) var(--sp-0)} .var-section{margin-top:var(--sp-6);border-top:1px solid var(--border);padding-top:var(--sp-5)} .var-heading{font-weight:600;font-size:var(--fs-sm);margin-bottom:var(--sp-4)} @@ -7374,350 +7483,255 @@ </head> <body> <script> -// Matrix is an opt-in display only. Content always comes from the authorized -// pull endpoint; the shared SSE stream carries a content-free nudge. +// Code activity reader (#16475): changed regions as readable paragraphs on +// the kiosk. Opt-in like Matrix and fed by the same authorized pull endpoint +// (the shared SSE stream only nudges). Code is always set with textContent. (function(){ 'use strict'; var pull = function(){}; - window.hiveMatrixAttach = function(source){ - if (!window.HIVE_MATRIX) return; + window.hiveReaderAttach = function(source){ + if (!window.HIVE_READER) return; source.addEventListener('code-lines', function(){ pull(); }); source.addEventListener('open', function(){ pull(); }); }; - window.hiveMatrixStart = function(){ - if (!window.HIVE_MATRIX || document.getElementById('hive-matrix')) return; - var params = new URL(window.location.href).searchParams; - function option(name, fallback){ - var value = params.get('mx.' + name); - try { - if (value === null) value = localStorage.getItem('hive.matrix.' + name); - else localStorage.setItem('hive.matrix.' + name, value); - } catch(e) {} - return value === null ? fallback : value; - } - function number(name, fallback, min, max){ - var value = Number(option(name, String(fallback))); - return Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback; - } - var effect = option('effect', 'rain'); - if (['rain', 'cascade', 'ghost', 'terminal'].indexOf(effect) < 0) effect = 'rain'; - var captions = option('captions', 'on') !== 'off'; - var speed = number('speed', 1, 0.1, 5), fps = number('fps', 30, 1, 60); - var palette = option('palette', 'green'); - var colors = {green: '#52ed86', amber: '#ffb347', gold: '#ffd700'}; - var color = colors[palette] || colors.green; + window.hiveReaderStart = function(){ + if (!window.HIVE_READER || document.getElementById('hive-reader')) return; + // Cards kept on screen, regions waiting to be read, and how long one + // paragraph stays in focus before the next arrives. + var MAX_CARDS = 32, MAX_LINES = 1200, MAX_BYTES = 256 * 1024, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; var root = document.createElement('main'); - root.id = 'hive-matrix'; - root.style.setProperty('--matrix-color', color); + root.id = 'hive-reader'; + root.setAttribute('aria-label', 'Code activity reader'); document.body.appendChild(root); - function element(tag, className, text){ + function element(tag, className, text, parent){ var el = document.createElement(tag); el.className = className; if (text) el.textContent = text; - root.appendChild(el); + (parent || root).appendChild(el); return el; } - var canvas = element('canvas', 'matrix-canvas'); - canvas.setAttribute('aria-label', 'Pushed code lines · Matrix ' + effect); - var list = element('div', 'matrix-list'); - var notice = element('p', 'matrix-notice', 'Waiting for pushed lines…'); - notice.setAttribute('role', 'status'); - var labels = element('div', 'matrix-labels'); - var source = document.createElement('div'); - source.textContent = 'Source: lines pushed by hive · public allowlisted repos'; - var freshness = document.createElement('div'); - var pausedLabel = document.createElement('div'); - labels.append(source, freshness, pausedLabel); - var ctx = canvas.getContext('2d'); + var bar = element('div', 'reader-bar'); + element('span', 'reader-source', 'Source: changes pushed by hive · public allowlisted repos', bar); + var status = element('span', 'reader-status', 'Waiting for pushed changes…', bar); + status.setAttribute('role', 'status'); + var button = element('button', 'reader-pause', 'Pause', bar); + button.setAttribute('type', 'button'); + button.setAttribute('aria-pressed', 'false'); + button.setAttribute('title', 'Pause or resume (P / Space)'); + var replay = element('button', 'reader-pause reader-replay', 'Replay buffered snapshot', bar); + replay.setAttribute('type', 'button'); + replay.setAttribute('title', 'Explicit replay of retained changes; off by default'); + var freshness = element('span', 'reader-freshness', 'Source has not completed an ingest pass', bar); + var scroller = element('div', 'reader-scroll'); + scroller.setAttribute('tabindex', '0'); + var feed = element('div', 'reader-feed', '', scroller); var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); - var lines = [], lastSeq = 0, lastAt = 0, lastIngestAt = 0, startedAt = Date.now(); - var enabled = false, manualPause = false, loading = false, pending = false; - var frame = 0, previous = 0, page = 0, pageTimer = 0, drops = []; - var atlas = document.createElement('canvas'), glyphs = new Map(); - var width = 0, height = 0, cell = 20, rowH = 20, charW = 10; - // Ghost coder and Terminal type the delivered lines in order; once the - // queue runs dry they replay the bounded latest-line window. - var queue = [], tabs = [], typing = null, termRows = [], termHead = '', termClock = 0; - var muted = '#6f8f78', syntaxColors = {keyword: '#7fd4ff', string: '#ffd27f', comment: muted, number: '#ff9cf0'}; - var languages = { - go: {comment: '//', words: 'package import func return if else for range var const type struct interface map chan go defer select case switch default break continue nil true false'}, - js: {comment: '//', words: 'function var let const return if else for while do new class extends import export from default async await this null undefined true false typeof instanceof switch case break continue try catch finally throw of in'}, - py: {comment: '#', words: 'def class import from return if elif else for while in not and or is None True False with as lambda yield pass raise try except finally async await'}, - sh: {comment: '#', words: 'if then else elif fi for while do done case esac function local export return in'}, - rs: {comment: '//', words: 'fn let mut pub use mod struct enum impl trait match if else for while loop return self Self true false const static where async await'}, - c: {comment: '//', words: 'if else for while do return break continue switch case default new class public private protected static const struct enum typedef sizeof void int char long double float unsigned true false null this import package'} - }; - var extensions = {go: 'go', js: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', jsx: 'js', py: 'py', sh: 'sh', bash: 'sh', - rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; - Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); + var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var retained = [], retainedLines = 0, retainedBytes = 0, epoch = '', snapshotThrough = null, contentGeneration = 0; + var enabled = false, manualPause = false, loading = false, again = false, problem = ''; function paused(){ return manualPause || document.hidden; } - function resize(){ - width = window.innerWidth; height = window.innerHeight; - canvas.width = width; canvas.height = height; - drops = []; - ctx.font = '16px monospace'; - charW = (ctx.measureText && ctx.measureText('M').width) || 10; - } - function resetText(){ queue = []; tabs = []; typing = null; termRows = []; termHead = ''; termClock = 0; } - function clearContent(message){ - enabled = false; lines = []; drops = []; glyphs.clear(); resetText(); - lastSeq = 0; lastAt = 0; lastIngestAt = 0; - list.replaceChildren(); ctx.clearRect(0, 0, width, height); - notice.textContent = message; - sync(); - } - function updateLabels(){ - var minutes = Math.floor(Math.max(0, Date.now() - (lastAt || startedAt)) / 60000); - var text = minutes >= 10 ? 'stale · no new lines for ' + minutes + 'm' : - (lastAt ? 'last line ' + (minutes ? minutes + 'm ago' : 'just now') : 'waiting for first line'); - // When stale, say whether the hive is still looking: a recent ingest - // means nothing was pushed, an old one means the feed itself is behind. - if (minutes >= 10 && lastIngestAt) { - var ingestMinutes = Math.floor(Math.max(0, Date.now() - lastIngestAt) / 60000); - text += ' · last ingest ' + (ingestMinutes ? ingestMinutes + 'm ago' : 'just now'); - } - freshness.textContent = text; - pausedLabel.textContent = paused() ? 'paused' : 'p / Space to pause'; - } - function caption(line){ return line.repo + '#' + line.pr + ' · ' + line.path; } - function prKey(line){ return line.repo + '#' + line.pr; } - function nextLine(key){ - if (!queue.length) queue = lines.slice(); - var at = 0; - for (var i = 0; key && i < queue.length; i++) if (prKey(queue[i]) === key) { at = i; break; } - return queue.splice(at, 1)[0] || null; - } - // Minimal keyword/string/comment/number colouring keyed on the extension; - // unknown extensions render in the palette colour. - function tokens(path, text){ - var ext = (/\.([^.\/]+)$/.exec(path || '') || [])[1]; - var lang = languages[extensions[ext ? ext.toLowerCase() : '']]; - if (!lang) return [{text: text, color: color}]; - var out = [], last = 0, match; - var pattern = /("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`[^`]*`?)|(\b\d[\w.]*)|([A-Za-z_$][\w$]*)|(\/\/|#)/g; - function push(t, c){ if (t) out.push({text: t, color: c}); } - while ((match = pattern.exec(text))) { - push(text.slice(last, match.index), color); - last = pattern.lastIndex; - if (match[4] === lang.comment) { push(text.slice(match.index), syntaxColors.comment); last = text.length; break; } - push(match[0], match[1] ? syntaxColors.string : match[2] ? syntaxColors.number : - match[3] && lang.words.has(match[0]) ? syntaxColors.keyword : color); - } - push(text.slice(last), color); - return out; - } - function openTab(line){ - var key = prKey(line), tab = null; - tabs.forEach(function(t){ if (t.key === key) tab = t; }); - if (!tab) { - tab = {key: key, rows: [], count: 0}; tabs.push(tab); - if (tabs.length > 6) tabs.shift(); - } - tab.path = line.path; - return tab; - } - function startTyping(line){ - typing = line ? {tab: openTab(line), line: line, chars: Array.from(line.line), typed: 0} : null; - } - function drawGhost(dt, now){ - if (!typing) startTyping(nextLine('')); - if (!typing) return; - typing.typed += dt * 40; - // A short beat at the end of each line before the next one starts. - if (typing.typed >= typing.chars.length + 4) { - var done = typing.tab; - done.count++; - done.rows.push({n: done.count, path: typing.line.path, text: typing.line.line}); - if (done.rows.length > 200) done.rows.shift(); - startTyping(nextLine(done.key)); - if (!typing) return; - } - var tab = typing.tab, top = 34, tabW = Math.min(240, width / Math.max(1, tabs.length)); - ctx.font = '13px monospace'; - tabs.forEach(function(t, i){ - ctx.fillStyle = t === tab ? '#0b2a16' : '#02140a'; - ctx.fillRect(i * tabW, 0, tabW - 2, 28); - ctx.fillStyle = t === tab ? color : muted; - ctx.fillText(t.path, i * tabW + 10, 19, tabW - 20); - }); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(typing.line), 10, 48, width - 20); - top = 56; - } - ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - 100) / rowH)); - var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; - tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ - var y = top + (i + 1) * rowH, col = 0; - ctx.fillStyle = muted; ctx.fillText(String(row.n), 10, y); - tokens(row.path, row.text).forEach(function(token){ - ctx.fillStyle = token.color; ctx.fillText(token.text, 60 + col * charW, y); - col += Array.from(token.text).length; - }); - if (row.current && Math.floor(now / 530) % 2 === 0) { ctx.fillStyle = color; ctx.fillRect(60 + col * charW, y - 14, 2, 18); } + // The source supplies indivisible regions. Never infer a paragraph from + // neighbouring sequence numbers or merge across context/page boundaries. + function group(regions){ + regions.forEach(function(region){ + if (!region || !Array.isArray(region.lines) || !region.lines.length) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-' || line.op === ' '); })) return; + var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); + if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; + var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, + stage: 'Pushed PR', at: region.at, lines: region.lines, size: size, + delivery: Number(region.seq) <= snapshotThrough ? 'Buffered snapshot' : 'Newly received checkpoint'}; + retained.push(item); pending.push(item); + retainedLines += item.lines.length; retainedBytes += size; + while (retainedLines > MAX_LINES || retainedBytes > MAX_BYTES) { + var victim = retained.findIndex(function(r){ return r !== current; }); + var old = retained.splice(victim, 1)[0]; + retainedLines -= old.lines.length; retainedBytes -= old.size; + pending = pending.filter(function(r){ return r !== old; }); + if (old.node) { feed.removeChild(old.node); old.node = null; } + if (current === old) current = null; + } }); } - function emitTerminal(){ - var line = nextLine(''); - if (!line) return; - if (caption(line) !== termHead) { - termHead = caption(line); - if (captions) { - if (termRows.length) termRows.push({text: '', color: color}); - termRows.push({text: termHead, color: '#b8ccbb'}); - } + function prLink(region){ + var url = typeof region.prURL === 'string' ? region.prURL : ''; + if (/^https:\/\/[^\s"'<>]+\/pull\/\d+$/.test(url)) return url; + if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { + return 'https://github.com/' + region.repo + '/pull/' + region.pr; } - termRows.push({text: '+ ' + line.line, color: color}); - var keep = Math.ceil(height / rowH) + 4; - if (termRows.length > keep) termRows = termRows.slice(-keep); - } - function drawTerminal(dt){ - if (!termRows.length) emitTerminal(); - termClock += dt * 4; - while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - 100; - ctx.font = '16px monospace'; - termRows.forEach(function(row, i){ - var y = bottom - (termRows.length - 1 - i + termClock) * rowH; - if (y < -rowH || !row.text) return; - ctx.fillStyle = row.color; ctx.fillText(row.text, 10, y, width - 20); - }); + return ''; } - function staticPage(){ - list.replaceChildren(); - var latest = lines.slice(-60).reverse(); - if (page * 8 >= latest.length) page = 0; - latest.slice(page * 8, page * 8 + 8).forEach(function(line){ - var row = document.createElement('div'); - var label = document.createElement('small'); - label.textContent = caption(line); - var text = document.createElement('pre'); - text.textContent = line.line; - row.append(label, text); list.appendChild(row); + function observed(at){ + var ms = Date.parse(at); + if (!Number.isFinite(ms)) return {iso: '', text: 'observed time unknown'}; + var d = new Date(ms); + // The shared helper honours the dashboard time-zone preference. + var shown = typeof formatDashboardDateTime === 'function' ? formatDashboardDateTime(d) : d.toISOString(); + return {iso: d.toISOString(), text: 'observed ' + shown}; + } + function card(region){ + var article = document.createElement('article'); + article.className = 'reader-card'; + var meta = element('header', 'reader-meta', '', article); + var href = prLink(region); + var repo = element(href ? 'a' : 'span', 'reader-repo', region.repo + (region.pr > 0 ? ' #' + region.pr : ''), meta); + if (href) { + repo.href = href; + repo.setAttribute('target', '_blank'); + repo.setAttribute('rel', 'noopener noreferrer'); + } + element('span', 'reader-file', region.path, meta); + element('span', 'reader-stage', region.stage, meta); + element('span', 'reader-delivery', region.delivery, meta); + var when = observed(region.at); + var time = element('time', 'reader-time', when.text, meta); + if (when.iso) time.setAttribute('datetime', when.iso); + var diff = element('pre', 'reader-diff', '', article); + region.lines.forEach(function(line){ + var removed = line.op === '-', context = line.op === ' '; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : context ? 'reader-context' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : context ? ' ' : '+ ') + line.line + '\n'; }); - } - function buildAtlas(){ - // Bounded by the same latest-line window as the renderer. No synthetic - // characters: every glyph in a column belongs to an incoming line. - glyphs.clear(); - lines.forEach(function(line){ Array.from(line.line).forEach(function(g){ - if (!glyphs.has(g)) glyphs.set(g, glyphs.size); - }); }); - atlas.width = 64 * cell; - atlas.height = Math.max(cell, Math.ceil(glyphs.size / 64) * cell); - var ac = atlas.getContext('2d'); - ac.font = '16px monospace'; ac.fillStyle = color; - glyphs.forEach(function(i, g){ ac.fillText(g, (i % 64) * cell, Math.floor(i / 64) * cell + 16); }); - } - function spawn(x){ - var line = lines[Math.floor(Math.random() * lines.length)]; - return {x: x, y: -Math.random() * height, speed: 25 + Math.random() * 65, - line: line, chars: Array.from(line.line)}; - } - function draw(now){ - frame = 0; - if (paused() || motion.matches || !enabled) return; - if (!previous) previous = now; - var elapsed = now - previous; - if (elapsed >= 1000 / fps) { - previous = now; - var dt = Math.min(elapsed, 100) / 1000 * speed; - ctx.fillStyle = effect === 'rain' ? 'rgba(0, 8, 4, 0.18)' : '#000804'; - ctx.fillRect(0, 0, width, height); - ctx.font = '16px monospace'; - if (lines.length && effect === 'ghost') drawGhost(dt, now); - else if (lines.length && effect === 'terminal') drawTerminal(dt); - else if (lines.length) { - var count = effect === 'rain' ? Math.ceil(width / cell) : 12; - while (drops.length < count) drops.push(spawn(effect === 'rain' ? drops.length * cell : Math.random() * width * 0.5)); - drops.forEach(function(drop, i){ - drop.y += drop.speed * dt; - if (drop.y > height + 40) { drops[i] = spawn(drop.x); return; } - if (effect === 'cascade') { - ctx.fillStyle = color; ctx.fillText(drop.line.line, drop.x, drop.y, width - drop.x); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(drop.line), drop.x, drop.y + 18, width - drop.x); - ctx.font = '16px monospace'; - } - } else if (drop.chars.length) { - var g = drop.chars[Math.floor(drop.y / cell + drop.chars.length * 100) % drop.chars.length]; - var index = glyphs.get(g); - if (index !== undefined) ctx.drawImage(atlas, (index % 64) * cell, Math.floor(index / 64) * cell, cell, cell, drop.x, drop.y, cell, cell); - ctx.fillStyle = '#effff2'; ctx.fillText(g, drop.x, drop.y + 16); - } - }); - } + return article; + } + function dwell(region){ return Math.min(MAX_DWELL, BASE_DWELL + region.lines.length * LINE_DWELL); } + // Drop the oldest cards and keep the visible text where it was. + function trim(){ + while (feed.children.length > MAX_CARDS) { + var first = feed.children[0], height = first.offsetHeight || 0; + feed.removeChild(first); + retained.forEach(function(r){ if (r.node === first) r.node = null; }); + scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); + } + } + function reveal(region, scroll){ + region.node = card(region); + feed.appendChild(region.node); + trim(); + current = region; + readUntil = Date.now() + dwell(region); + if (scroll && region.node.scrollIntoView) region.node.scrollIntoView({block: 'start', behavior: motion.matches ? 'auto' : 'smooth'}); + } + function updateStatus(){ + var text = problem; + if (!text && enabled) { + if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; + else text = current ? 'Caught up with available checkpoints · holding' : 'No buffered checkpoints · source may still be warming or filtering'; + } + if (paused()) text = 'paused' + (text ? ' · ' + text : ''); + status.textContent = text; + button.textContent = manualPause ? 'Resume' : 'Pause'; + button.setAttribute('aria-pressed', manualPause ? 'true' : 'false'); + } + function stop(){ clearTimeout(timer); timer = 0; } + function advance(){ + timer = 0; + if (!enabled || paused() || motion.matches) return; + // Quiet hold when caught up: no replay, no filler, nothing scheduled. + if (pending.length) { + reveal(pending.shift(), true); + timer = setTimeout(advance, dwell(current)); + } + updateStatus(); + } + // Starts the next reveal once the current paragraph's dwell ends; never + // restarts a running dwell, so incoming work cannot interrupt reading. + function schedule(fresh){ + if (timer || !enabled || paused()) { updateStatus(); return; } + if (motion.matches) { + // Static and scrollable: everything is shown, nothing scrolls by itself. + while (pending.length) reveal(pending.shift(), false); + updateStatus(); + return; + } + if (fresh && current) { + readUntil = Date.now() + dwell(current); + if (current.node && current.node.scrollIntoView) current.node.scrollIntoView({block: 'start', behavior: 'smooth'}); } - frame = requestAnimationFrame(draw); + var wait = readUntil - Date.now(); + if (pending.length && wait <= 0) { advance(); return; } + if (pending.length) timer = setTimeout(advance, wait); + updateStatus(); } - function sync(){ - if (frame) cancelAnimationFrame(frame); - frame = 0; previous = 0; - clearTimeout(pageTimer); pageTimer = 0; - updateLabels(); - canvas.hidden = motion.matches || !enabled; - list.hidden = !motion.matches || !enabled; - if (!enabled || paused()) return; - if (motion.matches) { - staticPage(); - pageTimer = setTimeout(function(){ page++; sync(); }, 15000); - } else frame = requestAnimationFrame(draw); + function setPaused(value){ + if (manualPause === value) return; + manualPause = value; + stop(); + if (!manualPause) schedule(true); + updateStatus(); + } + function inspect(){ setPaused(true); } + function clearContent(message){ + contentGeneration++; + stop(); + enabled = false; pending = []; retained = []; retainedLines = 0; retainedBytes = 0; + current = null; lastSeq = 0; snapshotThrough = null; problem = message; + feed.replaceChildren(); + updateStatus(); } pull = function(){ - if (loading) { pending = true; return; } - loading = true; pending = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + if (document.hidden) return; + if (loading) { again = true; return; } + loading = true; again = false; + var requestGeneration = contentGeneration; + fetch('/api/matrix/lines?since=' + lastSeq + '&format=regions', {cache: 'no-store', credentials: 'same-origin'}) .then(function(response){ - if (response.status === 404) { clearContent('Matrix mode is not enabled on this hive'); return null; } - if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read Matrix lines'); return null; } - if (!response.ok) throw new Error('Matrix pull failed'); + if (requestGeneration !== contentGeneration || document.hidden) return null; + if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } + if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } + if (!response.ok) throw new Error('reader pull failed'); return response.json(); }).then(function(data){ - if (!data) return; - var incoming = (Array.isArray(data.lines) ? data.lines : []).filter(function(line){ return typeof line.line === 'string'; }); + if (!data || requestGeneration !== contentGeneration || document.hidden) return; var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; replace the old backlog. - if (seq < lastSeq) { lines = []; drops = []; resetText(); } - if (seq !== lastSeq && incoming.length) { - var at = Date.parse(incoming[incoming.length - 1].at); - lastAt = Number.isFinite(at) ? at : Date.now(); + if (data.epoch !== epoch || seq < lastSeq) { + clearContent(''); epoch = data.epoch; } + if (snapshotThrough === null) snapshotThrough = Number(data.latest) || 0; + group(Array.isArray(data.regions) ? data.regions : []); + freshness.textContent = data.last_ingest_at + ? 'Last source pass: ' + data.last_ingest_at + ' · next expected in ' + (data.next_ingest_in_s || 0) + 's' + : 'Source has not completed an ingest pass · empty does not mean no work'; + if (seq < Number(data.latest)) again = true; lastSeq = seq; - var ingestAt = Date.parse(data.last_ingest_at); - lastIngestAt = Number.isFinite(ingestAt) ? ingestAt : 0; - lines = lines.concat(incoming).slice(-120); - queue = queue.concat(incoming).slice(-120); - enabled = true; - notice.textContent = lines.length ? '' : 'Waiting for pushed lines…'; - if (!motion.matches) buildAtlas(); - sync(); - }).catch(function(){ clearContent('Matrix lines unavailable · retrying'); }) - .finally(function(){ loading = false; if (pending) pull(); }); + enabled = true; problem = ''; + schedule(false); + }).catch(function(){ clearContent('Code activity unavailable · retrying'); }) + .finally(function(){ loading = false; if (again) pull(); }); }; - document.addEventListener('visibilitychange', function(){ sync(); if (!document.hidden) pull(); }); + replay.addEventListener('click', function(){ + if (!enabled || !retained.length) return; + stop(); feed.replaceChildren(); current = null; readUntil = 0; + retained.forEach(function(r){ r.node = null; r.delivery = 'Replay · buffered snapshot'; }); + pending = retained.slice(); schedule(false); + }); + button.addEventListener('click', function(){ setPaused(!manualPause); }); + scroller.addEventListener('wheel', inspect, {passive: true}); + scroller.addEventListener('touchstart', inspect, {passive: true}); + document.addEventListener('visibilitychange', function(){ + if (document.hidden) { clearContent('Hidden · buffered code cleared'); return; } + pull(); + }); document.addEventListener('keydown', function(event){ - if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || - /INPUT|TEXTAREA|SELECT/.test(event.target.tagName) || event.target.isContentEditable) return; - if (event.key === 'p' || event.key === 'P' || event.code === 'Space') { - event.preventDefault(); manualPause = !manualPause; sync(); + var target = event.target || {}; + if (event.ctrlKey || event.metaKey || event.altKey || + /INPUT|TEXTAREA|SELECT/.test(target.tagName) || target.isContentEditable) return; + if (NAV_KEYS.indexOf(event.key) >= 0) { inspect(); return; } + if (event.repeat) return; + if (event.key === 'p' || event.key === 'P' || (event.code === 'Space' && target.tagName !== 'BUTTON')) { + event.preventDefault(); setPaused(!manualPause); } }); - motion.addEventListener('change', function(){ - ctx.clearRect(0, 0, width, height); - if (!motion.matches) buildAtlas(); - sync(); - }); - window.addEventListener('resize', resize); - resize(); sync(); pull(); + motion.addEventListener('change', function(){ stop(); schedule(false); }); + updateStatus(); pull(); // Recover from missed nudges, endpoint activation and transient failures. if (typeof dashboardSetInterval === 'function') { - dashboardSetInterval('matrix-poll', function(){ updateLabels(); if (!document.hidden) pull(); }, 30000); + dashboardSetInterval('reader-poll', function(){ if (!document.hidden) pull(); }, 30000); } }; })(); -// Apply layout immediately and hide content until first data render. +// Apply layout immediately; keep the shell visible while live data loads. // NOTE: only body classes are set here — the .layout-toggle buttons do NOT // exist in the DOM yet at this point, so any label write here is a no-op. // applyLayout() (defined in the main script) is the single source of truth @@ -7755,10 +7769,12 @@ (function(){ var kiosk=false, popout=false, display=false, view='', sound=true, density='', shift=false; try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; view=u.searchParams.get('view'); popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} - window.HIVE_MATRIX = kiosk && view === 'matrix'; - if(window.HIVE_MATRIX){ - document.body.classList.add('matrix-mode'); - document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); + // Code activity is the sole opt-in code display (#16477); view=matrix is a + // deprecated alias so saved Matrix display URLs open the reader. + window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix'); + if(window.HIVE_READER){ + document.body.classList.add('reader-mode'); + document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); } window.HIVE_KIOSK=kiosk; window.HIVE_POPOUT=popout&&!kiosk; @@ -7803,9 +7819,6 @@ if(window.HIVE_KIOSK){ var kt=null; try { kt=new URL(window.location.href).searchParams.get('theme'); } catch(e) {} m=(kt==='light')?'light':'dark'; } if(!m)m='light'; if(m==='light'){document.body.classList.add('light-mode')} - document.body.style.opacity='0'; - document.body.style.transition='opacity 0.15s ease-in'; - setTimeout(function(){ document.body.style.opacity='1'; }, 3000); document.addEventListener('DOMContentLoaded', function(){ if (typeof applyLayout === 'function' && typeof getLayout === 'function') { applyLayout(getLayout()); @@ -7890,7 +7903,6 @@ document.addEventListener('DOMContentLoaded', renderStyleState); } })(); - </script> <div id="gh-auth-banner" class="gh-auth-banner" style="display:none"> <span id="gh-auth-msg">GitHub login required for advisory posting</span> @@ -8286,7 +8298,7 @@ <h2 class="config-title">🐝 Getting Started<span id="welcome-progress" class=" <div class="oc-topbar-right"> <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">🐛</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> - <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display — opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> + <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=reader" target="_blank" rel="noopener" title="Code activity — published pushed changes as readable paragraphs (opens in a new tab)" aria-label="Code activity" hidden><span class="nav-chip__label">Code activity</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings — governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">⚙</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> @@ -9027,7 +9039,7 @@ <h3 class="faq-group-title">Where to get help</h3> </div><!-- /#hive-dashboard-root --> <!-- Kiosk call-to-action badge (#16236). The server replaces this comment with pkg/webassets/kioskcta markup at start-up; it sits outside - #hive-dashboard-root because the Matrix view hides the root. Visible + #hive-dashboard-root because the Matrix and reader views hide the root. Visible only with body.kiosk-cta-on (kiosk=1 and not cta=off, see js/boot.js). --> <!-- hive-kiosk-cta --> @@ -9258,6 +9270,165 @@ <h3 class="faq-group-title">Where to get help</h3> })(); + const DASHBOARD_BACKGROUND_CONCURRENCY = 2; + const DASHBOARD_IDLE_TIMEOUT_MS = 1000; + const DASHBOARD_YIELD_MS = 32; + const DASHBOARD_BACKGROUND_DELAY_MS = 350; + const DASHBOARD_TASK_SECTIONS = Object.freeze({ + 'backend-discovery': ['debug-section'], + 'stat-sources': ['agents-section'], + 'cost': ['cost-panel'], + 'hive-advice': ['advisory-section'], + 'acmm-reco': ['advisory-section'], + 'lifecycle': ['advisory-section'], + 'pr-throughput': ['pr-throughput-section'], + 'approvals': ['approvals-section'], + 'fact-history': ['knowledge-section'], + 'overview-kpi-history': ['overview-section'], + 'history': ['overview-section', 'repos-section'], + 'budget-ignore': ['repos-section'], + 'budget-history': ['governor'], + 'nous-status': ['nous-section'], + 'public-knowledge': ['knowledge-section'], + 'knowledge-stats': ['knowledge-section'], + 'audit-log': ['audit-section'], + 'review-queue': ['review-queue-section'], + 'review-pipeline': ['review-queue-section'], + 'stage-tracker': ['activity-monitor-section'], + 'contributors': ['contributors-section'], + 'leaderboard': ['contributors-section'], + 'git-version': ['debug-section'], + 'acmm-evaluation': ['acmm-eval-section'], + 'version-check': ['debug-section'], + 'version-reload-check': ['debug-section'], + 'weekly-trends': ['overview-section'], + 'timeline': ['governor'], + 'agent-logs': ['logs-section'], + 'debug-section': ['debug-section'], + 'chat-capabilities': [], + 'chat-presence': [], + 'welcome-gh-auth': [], + 'welcome-claude-auth': [], + 'gh-auth-banner': [], + }); + const _dashboardBackgroundJobs = new Map(); + const _dashboardRenderJobs = new Map(); + let _dashboardBackgroundRunning = 0; + let _dashboardBackgroundScheduled = false; + let _dashboardRenderScheduled = false; + let _dashboardBackgroundReady = false; + + function dashboardWorkPriority(sections) { + let priority = 2; + for (const id of sections || []) { + if (window.location.hash === '#section-' + id) return 0; + const el = document.getElementById(id); + if (!el || !el.getClientRects().length) continue; + const rect = el.getBoundingClientRect(); + if (rect.bottom >= 0 && rect.top <= window.innerHeight) priority = 1; + } + return priority; + } + function dashboardNextWork(jobs) { + let next; + let priority = Infinity; + for (const job of jobs.values()) { + if (job.running) continue; + const rank = dashboardWorkPriority(job.sections); + if (rank < priority) { next = job; priority = rank; } + } + return next; + } + function dashboardIdle(callback) { + if (typeof window.requestIdleCallback === 'function') { + window.requestIdleCallback(callback, { timeout: DASHBOARD_IDLE_TIMEOUT_MS }); + } else { + setTimeout(callback, DASHBOARD_YIELD_MS); + } + } + function dashboardWakeBackground() { + if (!_dashboardBackgroundReady || document.hidden || _dashboardBackgroundScheduled || + _dashboardBackgroundRunning >= DASHBOARD_BACKGROUND_CONCURRENCY || + !dashboardNextWork(_dashboardBackgroundJobs)) return; + _dashboardBackgroundScheduled = true; + dashboardIdle(function() { + _dashboardBackgroundScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardBackgroundJobs); + if (!job) return; + job.running = true; + _dashboardBackgroundRunning++; + function finished() { + _dashboardBackgroundJobs.delete(job.key); + _dashboardBackgroundRunning--; + dashboardWakeBackground(); + } + Promise.resolve().then(job.fn).then(function(value) { + finished(); job.resolve(value); + }, function(err) { + finished(); job.reject(err); + }); + dashboardWakeBackground(); + }); + } + // Keep a slot through JSON decoding and rendering, not just response headers. + // Repeated timer ticks share the same flight rather than adding stale work. + function dashboardScheduleWork(key, fn) { + const existing = _dashboardBackgroundJobs.get(key); + if (existing) return existing.promise; + let resolve, reject; + const promise = new Promise(function(ok, fail) { resolve = ok; reject = fail; }); + _dashboardBackgroundJobs.set(key, { + key, fn, promise, resolve, reject, running: false, + sections: DASHBOARD_TASK_SECTIONS[key] || [], + }); + dashboardWakeBackground(); + return promise; + } + function dashboardWakeRender() { + if (document.hidden || _dashboardRenderScheduled || !_dashboardRenderJobs.size) return; + _dashboardRenderScheduled = true; + dashboardIdle(function() { + _dashboardRenderScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardRenderJobs); + if (!job) return; + _dashboardRenderJobs.delete(job.key); + if (job.snapshot && !dashboardStatusCanRender(job.snapshot)) { + dashboardWakeRender(); + return; + } + const anchor = typeof captureScrollAnchor === 'function' ? captureScrollAnchor() : null; + try { + job.fn(); + job.sections.forEach(function(id) { + if (typeof applySectionCollapse === 'function') applySectionCollapse(id); + }); + if (typeof refreshDashboardSectionSummaries === 'function') refreshDashboardSectionSummaries(); + } catch (err) { + console.error('dashboard render ' + job.key + ' failed', err); + } finally { + if (anchor && typeof restoreScrollAnchor === 'function' && + (typeof _hashScrollPending === 'undefined' || !_hashScrollPending)) restoreScrollAnchor(anchor); + dashboardWakeRender(); + } + }); + } + // Latest snapshot wins. Paint one section per idle turn so input and + // navigation can run between large cards, even when SSE arrives in a burst. + function dashboardRenderSection(key, sections, fn, snapshot) { + _dashboardRenderJobs.set(key, { key, sections, fn, snapshot }); + dashboardWakeRender(); + } + function dashboardProgressiveWake() { + dashboardWakeBackground(); + dashboardWakeRender(); + } + document.addEventListener('visibilitychange', dashboardProgressiveWake); + setTimeout(function() { + _dashboardBackgroundReady = true; + dashboardWakeBackground(); + }, DASHBOARD_BACKGROUND_DELAY_MS); // ── Console-style dashboard feedback ─────────────────────────────────── const FEEDBACK_DRAFT_KEY = 'hive-feedback-draft-v1'; const FEEDBACK_IDENTITY_KEY = 'hive-feedback-github-username-v1'; @@ -11764,7 +11935,7 @@ <h3 class="faq-group-title">Where to get help</h3> } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', start); - } else { start(); } + } else { queueMicrotask(start); } })(); const OC_TOPBAR_HEIGHT = 64; @@ -11904,6 +12075,7 @@ <h3 class="faq-group-title">Where to get help</h3> document.querySelectorAll('.oc-nav-item').forEach(i => i.classList.remove('active')); const active = document.querySelector(`.oc-nav-item[data-agent-nav="${(window.CSS && CSS.escape) ? CSS.escape(name) : String(name).replace(/["\\]/g, '\\$&')}"]`); if (active) active.classList.add('active'); + if (typeof dashboardProgressiveWake === 'function') dashboardProgressiveWake(); navPeekRestore('agents-section', { instant: true }); const expanded = navPeekExpand('agents-section'); if (!expanded && isSectionCollapsed('agents-section')) toggleSection('agents-section', { collapsed: false, persist: false, navPeek: true }); @@ -12709,7 +12881,6 @@ <h3 class="faq-group-title">Where to get help</h3> // Agent descriptions now come from the JSON status payload (agent.description field). // This empty map serves as a fallback for agents without a description in config. const AGENT_DESCRIPTIONS = {}; - // ── Config-driven agent color/sort helpers ────────────────────────────── const _DEFAULT_AGENT_COLOR = 'var(--muted)'; function _getAgentColor(name) { @@ -13408,19 +13579,28 @@ <h3 class="faq-group-title">Where to get help</h3> } function dashboardSetInterval(key, fn, ms) { dashboardClearInterval(key); - const entry = { fn, ms, timer: null }; + const entry = { key, fn, ms, timer: null }; DASHBOARD_INTERVALS[key] = entry; if (!document.hidden) dashboardStartInterval(entry); return entry; } function dashboardStartInterval(entry) { - entry.timer = setInterval(entry.fn, entry.ms); + entry.timer = setInterval(function() { + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } + }, entry.ms); } function dashboardClearInterval(key) { if (!DASHBOARD_INTERVALS[key]) return; clearInterval(DASHBOARD_INTERVALS[key].timer); delete DASHBOARD_INTERVALS[key]; } + function dashboardRunInterval(entry) { + if (typeof dashboardScheduleWork === 'function' && + Object.prototype.hasOwnProperty.call(DASHBOARD_TASK_SECTIONS, entry.key)) { + return dashboardScheduleWork(entry.key, entry.fn); + } + return entry.fn(); + } document.addEventListener('visibilitychange', () => { for (const [key, entry] of Object.entries(DASHBOARD_INTERVALS)) { if (DASHBOARD_INTERVALS[key] !== entry) continue; @@ -13431,7 +13611,7 @@ <h3 class="faq-group-title">Where to get help</h3> // A refresh failure must not prevent the other panels from resuming. // Snapshot iteration also permits a callback to clear/replace itself. if (DASHBOARD_INTERVALS[key] === entry) { - try { Promise.resolve(entry.fn()).catch(console.error); } catch (err) { console.error(err); } + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } } } }); @@ -13881,7 +14061,6 @@ <h3 class="faq-group-title">Where to get help</h3> capHistory(historyData); } } - // ── Cost spend-over-time (hourly / daily / weekly / monthly / custom) ── // The server keeps 30 days of CUMULATIVE all-time estimated-$ snapshots at // ~5-min resolution. We derive per-bucket SPEND on the client by taking the @@ -15698,10 +15877,44 @@ <h3 class="faq-group-title">Where to get help</h3> if (state === 'resolving-conflicts') return 'Adopting · fixer resolving conflicts'; return 'Adopted → #' + by; } - const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human'; + // "Waiting for @clubanderson · rerun shared ci on GitHub": the person + // owed the step is named when the author is one (a hive / bot / clanker + // author cannot grant the permission; a maintainer is asked instead). + const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Waiting for'; + const STAGE_TRACKER_UNAUTHORIZED_WHERE = 'on GitHub'; + function stageTrackerUnauthorizedWho(item) { + // An issue row drawn on its one covering PR names that PR's author. + const linked = item && item.via_pr && Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => lp && String(lp.unauthorized_step || '').trim()) : []; + const src = linked.length === 1 ? linked[0] : item; + const author = String((src && src.author) || '').trim().replace(/^@/, ''); + const kind = String((src && src.author_kind) || ''); + if (author && kind !== 'hive' && kind !== 'bot' && kind !== 'clanker') return '@' + author; + return 'a maintainer'; + } function stageTrackerUnauthorizedWord(item) { const step = String((item && item.unauthorized_step) || '').trim(); - return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ': ' + step : ''; + return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ' ' + stageTrackerUnauthorizedWho(item) + ' · ' + step + ' ' + STAGE_TRACKER_UNAUTHORIZED_WHERE : ''; + } + // A PR parked at 085 because a person has to act ON THE PR (rerun CI, + // approve workflow runs, resolve a permission, answer review findings + // or red checks still open on its head) is not queued, merging or + // merge-ready: it lights PR in progress, never Merge queue. Merge + // queue is only for rows actually queued / merging / merged, or a + // merge-ready PR (review approved, CI green on this head) parked on a + // merge decision. A bare 085 with no track evidence keeps the gate: + // the person decides there (hive#14821). Hive's own #16524 read + // "Awaiting human: rerun shared ci" under Merge queue with CI unknown + // and review findings open. Mirrors stageTrackerPersonActsOnPR in Go. + function stageTrackerPersonActsOnPR(item) { + if (!item || (item.via_pr ? 'pr' : item.kind) !== 'pr' || Number(item.stage) !== STAGE_TRACKER_HUMAN_GATED) return false; + if (item.merge_gate && item.merge_gate.state) return false; + if (item.merge_train && item.merge_train.state) return false; + const onHead = a => !!a && (!a.head || !item.head || String(a.head) === String(item.head)); + const review = onHead(item.review_activity) ? item.review_activity : null; + const ci = onHead(item.ci_activity) ? item.ci_activity : null; + const mergeReady = !!(review && review.state === 'approved' && ci && ci.state === 'passing'); + if (String(item.unauthorized_step || '').trim()) return !mergeReady; + return !!((review && review.state !== 'approved') || (ci && ci.state !== 'passing')); } // A parked issue with a structured blocker (item.blocker, #15099) reads // "Blocked · App lacks workflows permission", never "Needs human @@ -15712,6 +15925,56 @@ <h3 class="faq-group-title">Where to get help</h3> const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' · ' + short : ''; } + // Why a person is needed, in a few words, for the row itself to say + // (hivecommons/docs#612, rationguard#480: "it's not clear reading the + // row why a human is needed"). The structured blocker's short text + // first; else the server's reason key (stage_actor.human_reason, the + // human-merge reason, the clause after "—" in stage_actor.why) through + // a small map of known reasons; else that clause's first sentence. + const STAGE_TRACKER_NEEDS_HUMAN_SHORT = { + 'workflow path': 'edits CI workflows', + 'hive signoff attribution': 'hive signoff attribution', + 'high-risk review': 'high-risk review', + 'optional check failing': 'optional check failing', + 'capability:workflows-permission': 'App lacks workflows permission', + }; + const STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX = 48; + const STAGE_TRACKER_NEEDS_HUMAN_WORD = 'Needs human'; + function stageTrackerNeedsHumanShort(item) { + if (!item) return ''; + const b = item.blocker; + if (b && String(b.short || '').trim()) return String(b.short).trim(); + if (b && STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]; + const sa = item.stage_actor || {}; + const afterDash = s => { const t = String(s || ''); const i = t.indexOf(' — '); return i >= 0 ? t.slice(i + 3) : ''; }; + const keys = [sa.human_reason, item.human_merge_reason, afterDash(sa.why), afterDash(item.caption), item.reason]; + for (const k of keys) { + const key = String(k || '').replace(/\s+/g, ' ').trim().toLowerCase(); + if (key && STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]; + } + const clause = String(afterDash(sa.why) || sa.human_reason || '').replace(/\s+/g, ' ').trim().split(/[;.](?:\s|$)/)[0].trim(); + if (!clause) return ''; + return clause.length > STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX ? clause.slice(0, STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…' : clause; + } + // The lit 045 / 085 chevron's caption: "Needs human · edits CI + // workflows" rather than a bare "Needs human decision". '' when no + // short reason is known (the plain stage word stands). + function stageTrackerNeedsHumanWord(item) { + const short = stageTrackerNeedsHumanShort(item); + return short ? STAGE_TRACKER_NEEDS_HUMAN_WORD + ' · ' + short : ''; + } + // A decomposed parent at 010 (server `open_children` > 0, hive#16481) + // reads "Tracking · 3/4" (children known) or "Tracking · 1 open child", + // never "Actionable": the scanner leaves it to its children, so the + // row is not a stuck unclaimed issue. + const STAGE_TRACKER_TRACKING_WORD = 'Tracking'; + function stageTrackerTrackingWord(item) { + const open = Number(item && item.open_children) || 0; + if (!(open > 0) || !item || item.kind !== 'issue') return ''; + const c = item.children; + if (c && Number(c.total) > 0) return STAGE_TRACKER_TRACKING_WORD + ' · ' + (Number(c.completed) || 0) + '/' + Number(c.total); + return STAGE_TRACKER_TRACKING_WORD + ' · ' + open + ' open child' + (open === 1 ? '' : 'ren'); + } // Issue-slot placeholders for a closing reference whose title the server // could not resolve (the issue is closed and unreadable, or of unknown state). const STAGE_TRACKER_CLOSED_ISSUE_TITLE = '(closed issue)'; @@ -15890,7 +16153,7 @@ <h3 class="faq-group-title">Where to get help</h3> // the chevron and the caption name one blocker (hive's own #15577 read // "Merge queued · 1st" while its caption said "check build-and-test // still running"). Keys below STAGE_TRACKER_MERGE_READY only. - const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Fixing', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; // Pure: true when the row's queue slot is a forecast — the server says // so (merge_train.provisional), or, from an older server, the row's // own stage is short of the merge gate. @@ -15997,7 +16260,7 @@ <h3 class="faq-group-title">Where to get help</h3> // (mergeTrainHead* in Go) — short enough for a chevron. A head on a // person says what the person has to do (the owner's ask: "waiting on // #15425 (needs maintainer merge)"), not "waiting for a maintainer". - const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being fixed by its author', unknown: 'head not in this view' }; + const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being remediated by its author', unknown: 'head not in this view' }; // Pure: the short reason a stalled head is stuck — the head_state // table, a human-decision head told apart by its reason, else the // head's own plain-word reason cut at its first clause. @@ -16516,7 +16779,7 @@ <h3 class="faq-group-title">Where to get help</h3> case 45: return 'Needs a human decision'; case 50: return 'Waiting for review' + viaPR; case 60: return 'Reviewed' + viaPR; - case 70: return 'Fixing review findings' + viaPR; + case 70: return 'Remediating CI or review findings' + viaPR; case 71: return 'Waiting on the author' + viaPR; case 72: return 'Back with the contributor' + viaPR; case 74: return 'Hive took it over' + viaPR; @@ -16608,7 +16871,7 @@ <h3 class="faq-group-title">Where to get help</h3> // Stage → operator phrase, mirrored from stageTrackerStagePhrase // (stage_tracker_vocabulary.go): every string the page renders names a // stage by its chevron's words, never by a code ("060 reviewed"). - const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed · waiting for merge admission', 70: 'being fixed by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; + const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed · waiting for merge admission', 70: 'being remediated by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; // Pure: a stage's name in plain words for cues and tooltips — its short // word when the stages table has one, else its label with the lane's // "stage/060-" slug prefix dropped and the slug humanised ("Reviewed"). @@ -16655,7 +16918,8 @@ <h3 class="faq-group-title">Where to get help</h3> if (!d || d.effect !== 'pending' || !d.text) return null; nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); const sep = String(d.text).indexOf(' · '); - const word = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const rawWord = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const word = rawWord === 'Fixing' ? 'Remediating' : rawWord; let detail = sep > 0 ? d.text.slice(sep + 3) : ''; const until = d.next_at ? Date.parse(d.next_at) : 0; if (until > nowMs) detail += (detail ? ' · ' : '') + 'in ' + stageTrackerShortLeft(until - nowMs); @@ -16664,10 +16928,16 @@ <h3 class="faq-group-title">Where to get help</h3> // Pure: the in-flight caption for a recorded decision — from the // server's projection when it has one, else from the result's action. const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting · opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; + // A park-keeping verdict by what it recorded: a recommendation only + // when there is one (recommend-only); owner-only / operator-action hand + // the decision back, so the caption says so (hivecommons/hive#16572). + const STAGE_TRACKER_PARK_KEPT_ACTING = { 'recommend-only': 'Recommendation recorded', 'owner-only': 'Your decision needed · owner sign-off', 'operator-action': 'Your action needed · operator step' }; function stageTrackerDecidedActing(result, item) { const d = item && item.decided; if (d && d.acting) return d.acting; - return STAGE_TRACKER_DECIDED_ACTING[result && result.action] || 'Hive decided…'; + const action = result && result.action; + if (action === 'recommended') return STAGE_TRACKER_PARK_KEPT_ACTING[result.verdict] || 'Your decision needed'; + return STAGE_TRACKER_DECIDED_ACTING[action] || 'Hive decided…'; } // Pure: the ✓ badge's first line for a decided row: the decision name // and who / what triggered it — "you · Let hive decide · hive chose @@ -17665,6 +17935,10 @@ <h3 class="faq-group-title">Where to get help</h3> // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; @@ -17699,6 +17973,15 @@ <h3 class="faq-group-title">Where to get help</h3> const detour = (!terminal && !pushedBack && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_HUMAN_GATED && typeof stageTrackerTrainWord === 'function' && stageTrackerTrainWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (typeof stageTrackerBlockerWord === 'function' && cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION && stageTrackerBlockerWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || (cur === STAGE_TRACKER_HUMAN_GATED && item.adopted_by_state)) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; if (detour && cur === 70 && !detour.sentinel && typeof stageTrackerFixingWord === 'function') detour.text = stageTrackerFixingWord(item, detour.text); + // A bare "Needs human decision" (045 / 085) says why in the chevron + // itself — "Needs human · edits CI workflows" — when a short reason + // is known (rationguard#480: "what does 'needs human' mean?"). A + // word already carrying its why (Blocked · …, Waiting for @x · …, + // the train, the sentinel) stands. + if (detour && (cur === STAGE_TRACKER_NEEDS_DECISION || cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION) && !detour.sentinel && detour.text === STAGE_TRACKER_ACTIVE_WORD[cur] && typeof stageTrackerNeedsHumanWord === 'function') { + const nh = stageTrackerNeedsHumanWord(item); + if (nh) detour.text = nh; + } if (detour && (cur === 71 || cur === 72) && typeof stageTrackerReturnedWord === 'function') { detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); @@ -17709,7 +17992,7 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : code.caption) : 'Code activity unknown'; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : (code.state === 'fixing' ? String(code.caption || '').replace(/^Fixing\b/, 'Remediating') : code.caption)) : 'Code activity unknown'; if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer · activity unknown'; if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; if (detour && code && cur === 74 && codeWorking) detour.text += ' · ' + codeCaption; @@ -17730,6 +18013,7 @@ <h3 class="faq-group-title">Where to get help</h3> const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 10 && cur === 10 && typeof stageTrackerTrackingWord === 'function') { const tw = stageTrackerTrackingWord(item); if (tw) word = tw; } if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } @@ -17767,7 +18051,12 @@ <h3 class="faq-group-title">Where to get help</h3> const os = stageTrackerOpenSince(item); if (os.ms) { word += ' · since ' + stageTrackerShortAgo(nowMs - os.ms); openSince = Object.assign({ stale: !openDraft && nowMs - os.ms > STAGE_TRACKER_OPEN_STALE_DAYS * 86400000 }, os); } } - return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; + // An issue parked on a blocker whose strip a human's covering PR + // drives (via_pr): the issue's own column keeps the blocker in + // view — "Blocked · App lacks workflows permission 👤" — rather + // than reading as a passed step (hivecommons/docs#612 under #620). + const blockerNote = state === 'done' && n === STAGE_TRACKER_ISSUE_DECISION_COLUMN && item.via_pr && item.kind === 'issue' && item.blocker && typeof stageTrackerBlockerWord === 'function' && (item.needs_human === true || (typeof stageTrackerItemNeedsHuman === 'function' && stageTrackerItemNeedsHuman(item))) ? stageTrackerBlockerWord(item) : ''; + return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, blockerNote, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; }); segs.push({ number: STAGE_TRACKER_TERMINAL, code: '', short: 'Merged', label: 'Merged', description: 'Merged — the pipeline is complete', state: terminal ? 'active' : 'todo', terminal, cap: true, detour: null }); return segs; @@ -17789,7 +18078,11 @@ <h3 class="faq-group-title">Where to get help</h3> 20: '<rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/>', 30: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="5" r="1.5"/><path d="M4 4.5v7M12 6.5c0 3-8 1-8 4"/>', 40: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="12" r="1.5"/><path d="M4 4.5v7M4 6c0 3 6 2 6.5 5"/>', + // Column 50 splits into two tracks: CI wears a flask (checks run, no + // verdict implied), Review keeps the eye. The eye alone on both read + // as one duplicated glyph (operator, 2026-11-03). 50: '<path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/>', + ci: '<path d="M5.5 1.5h5M6.5 1.5v4.6L2.6 12.9a1 1 0 0 0 .9 1.6h9a1 1 0 0 0 .9-1.6L9.5 6.1V1.5"/><path d="M4.4 10.5h7.2"/>', // Merge queue: the same railcar as the column header and train chip // (STAGE_TRACKER_TRAIN_ICON_PATH in tracker-words.js; a test keeps them equal). 80: '<rect x="2" y="3.5" width="12" height="7" rx="1.5"/><path d="M2 7.5h12M6.5 3.5v4M10.5 3.5v4M4 13.5l-1.5 1.5M12 13.5l1.5 1.5"/><circle cx="5" cy="12.5" r="1.5"/><circle cx="11" cy="12.5" r="1.5"/>', @@ -18044,9 +18337,227 @@ <h3 class="faq-group-title">Where to get help</h3> return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History — decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Pure: which of the two column-50 tracks the hive is waiting on when + // both share the current phase (hivecommons/hive#16484). Review + // findings and red CI are the fixer's turn ("the fix"); otherwise CI + // leads until it is green, then review. newHead: the head was just + // pushed, so CI is (re)running on it and the review is a re-review. + function stageTrackerTrackLead(item) { + if (!item || !item.head) return null; + const stateOf = k => { const a = item[k + '_activity']; return a && a.head === item.head && a.state ? a.state : 'unknown'; }; + const ci = stateOf('ci'); + const review = stateOf('review'); + const done = s => s === 'passing' || s === 'approved'; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + if (review === 'changes_requested') return { track: 'review', waitingOn: 'the fix', newHead: false }; + if (ci === 'failing') return { track: 'ci', waitingOn: 'the fix', newHead: false }; + if (done(ci) && done(review)) return null; + if (done(ci)) return { track: 'review', waitingOn: 'review', newHead }; + return { track: 'ci', waitingOn: 'CI', newHead }; + } + + // Pure: the chevron's primary words — the count grammar the operator + // asked for (hivecommons/hive#16484): "CI 12/14 passed", "CI 11/14 · 1 + // failing (lint)", "CI 0/14 · queued", "CI ?/? · no checks reported + // yet"; "Review 3/5 perspectives", "Review 5/5 approved", "Review 0/5 · + // re-review pending (new head)", "Review 2/5 · awaiting human + // decision". '' means the track has not started on this head (the + // chevron shows its glyph alone). current: column 50 is the row's + // active phase, so even absent evidence is "in progress" there. + function stageTrackerTrackWord(item, kind, current) { + const a = item && item[kind + '_activity']; + const matches = !!(a && item.head && a.head === item.head); + const state = matches ? a.state || 'unknown' : 'unknown'; + if (state === 'unknown' && !current) return ''; + const n = k => matches ? Number(a[k]) || 0 : 0; + if (kind === 'ci') { + const total = n('checks_total'); + const passed = n('checks_passed'); + const failed = n('checks_failed'); + const names = matches && Array.isArray(a.checks_failing) ? a.checks_failing : []; + const count = 'CI ' + (total ? passed + '/' + total : '?/?'); + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; + const blocker = matches && a.blocker ? String(a.blocker) : ''; + switch (state) { + case 'passing': return count + ' passed'; + case 'failing': return count + ' · ' + (failing || 'failing' + (blocker ? ' (' + blocker + ')' : '')); + case 'running': return count + ' · running' + (failing ? ' · ' + failing : ''); + case 'queued': return count + ' · queued' + (failing ? ' · ' + failing : ''); + case 'skipped': return count + ' · ' + (blocker ? blocker + ' skipped' : 'skipped'); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' · waiting on workflow approval' + (failing ? ' · ' + failing : ''); + return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } + default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); + } + } + const total = n('perspectives_total'); + const done = n('perspectives_done'); + const count = 'Review' + (total ? ' ' + done + '/' + total : ''); + const actor = matches && a.actor ? String(a.actor) : ''; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + switch (state) { + case 'approved': return count + ' approved'; + case 'changes_requested': return count + ' · changes requested'; + // The hive on the repair (adopted / remediating) is not a human + // decision: the findings are the changes requested. Otherwise the + // reviews are done and a person's sign-off is what is left — the + // viewer's when the ask names them, else the owner's. Never + // "awaiting human" to the human it waits on (hivecommons/hive#16572: + // "why does review say awaiting humans if 5/5 reviews are good?"). + case 'human_decision': { + if (stageTrackerHiveOwnsRepair(item)) return count + ' · changes requested'; + const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; + const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; + const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); + return count + (mine ? ' · needs your sign-off' : ' · needs owner sign-off'); + } + case 'reviewing': return count + ' · ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' · ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' · queued' + stageTrackerQueueAheadWord(a); + default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:<n>" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve — done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return `<circle class="${cls}" cx="${c}" cy="${c}" r="${r}"/>`; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return `<path class="${cls}" d="M${pt(from)} A${r} ${r} 0 ${large} 1 ${pt(to)}"/>`; + }; + const open = `<svg class="ham-ico ham-ring ham-ring-${tone}${running ? ' ham-ring-running' : ''}" viewBox="0 0 16 16" fill="none" stroke-width="2.2" stroke-linecap="butt" role="img" aria-label="${esc(a11y)}" data-ring-total="${t}" data-ring-done="${d}" data-ring-failed="${f}">`; + if (!t) return open + `<circle class="ham-ring-track" cx="${c}" cy="${c}" r="${r}"/></svg>`; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); + } + return open + segs.join('') + '</svg>'; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled — CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled — + // queued, in progress, adjudicating alike — because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; + } + + function stageTrackerHiveOwnsRepair(item) { + if (!item || item.needs_human || item.on_hold || item.hold) return false; + const code = item.code_activity; + const hive = code && code.head === item.head && ['adopted', 'remediating', 'unassigned', 'fix_pushed', 'fixing'].includes(code.state); + return !!(hive || item.stage === 74 || item.adopted_by); + } + + // A row parked on a person: the contributor's move (071/072 or a + // waiting_owner code word), a hold, or a human decision. Nothing of + // the hive's is in motion on it, so no CI / Review track is amber. + function stageTrackerWaitingOnPerson(item) { + if (!item) return false; + if (item.needs_human || item.on_hold || item.hold) return true; + const stage = Number(item.stage); + // A freshly pushed head is in motion: checks run on it, matching + // tracker-row-anchor's column-50 anchor (hivecommons/hive#16552). + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state))) return true; + const code = item.code_activity; + return !!(code && code.head === item.head && code.state === 'waiting_owner'); + } + + // A CI / Review track is in motion only on concrete evidence on the + // current head: a check-run in_progress / queued, or a reviewer + // running / queued (or the backend's own active flag). Checks that + // have not reported, unknown evidence and settled verdicts are not + // motion (hivecommons/hive#16540). + function stageTrackerTrackRunning(item, kind) { + const a = item && item[kind + '_activity']; + if (!a || !item.head || a.head !== item.head) return false; + if (stageTrackerWaitingOnPerson(item)) return false; + const moving = kind === 'ci' ? ['running', 'queued'] : ['reviewing', 'adjudicating', 'assigned']; + return !!(a.active || moving.includes(a.state)); + } + // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + // The chevron wears its glyph plus the count words from + // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the + // track's own state on the current head: running = the full active + // fill (both tracks may be lit at once; the words disambiguate); done, + // a finding, pending and decided are words in their colour on the muted + // field — only a running track is filled (hivecommons/hive#16540); not + // started = the empty chevron with the glyph alone. Freshness gates only + // the pulse. + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -18056,16 +18567,45 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); - const active = matches && a.active && Number.isFinite(observed) && !stale; + const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown · last observed ' + state; - const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; + const active = known && a.active; + if (matches && !known && state !== 'unknown') caption = name + ' activity unknown · last observed ' + state + ' · ' + caption; + const ownsPR = item.kind === 'pr' || item.via_pr; + const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); + const finished = matches && (state === 'passing' || state === 'approved'); + const finding = matches && (state === 'failing' || state === 'changes_requested'); + // A complete verdict parked on a person is settled (muted icon). + const settled = matches && state === 'human_decision' && (!known || !a.active); + // ACTIVE = filled amber with its words; 1 ≤ active ≤ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone — green for + // a pass, red for a finding, neutral when not run or decided — with + // its count words in the tooltip (hivecommons/hive#16599). + const running = stageTrackerTrackRunning(item, kind); + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; - const blocker = matches && a.blocker ? ' · ' + a.blocker : ''; - let tip = caption + blocker + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; - const ownsPR = item.kind === 'pr' || item.via_pr; + let blocker = matches && a.blocker ? ' · ' + a.blocker : ''; + // A sign-off ask: the tooltip carries the question itself (who should + // decide what, and why — "workflow change from a fork") when the + // review evidence did not already quote it. + const ask = matches && state === 'human_decision' && item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question) : ''; + if (ask && blocker.indexOf(ask) < 0) blocker += ' · ' + ask; + // The backend's plain-language sentence behind the caption rides in + // the tooltip only; the chevron clamps the caption. + const detail = matches && a.detail ? ' · ' + a.detail : ''; + let tip = caption + blocker + detail + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; const code = item.code_activity; const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && ((kind === 'review' && code.state === 'waiting_fixer') || (kind === 'ci' && code.state === 'waiting_ci')) ? code.caption : ''; @@ -18074,12 +18614,32 @@ <h3 class="faq-group-title">Where to get help</h3> let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); - const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); + const sha7 = item.head ? String(item.head).slice(0, 7) : ''; + const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. + const verdict = finished ? 'pass' : finding ? 'fail' : ''; + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); - return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' · ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' · ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + const hold = item.hold; + const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + (text ? text + ' · ' : '') + tip + + (matches && a.actor ? ' · actor ' + a.actor : '') + + (codeNote || contextWord ? ' · ' + (codeNote || contextWord) : '') + + (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + + (lead ? ' · hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); + const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); + const copy = `<span class="ham-chevron-copy ham-track-state${lit ? '' : ' ham-track-verdict'}">${evidenceLink}</span>${personIco}`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}"${stalled ? ' data-stalled="true"' : ''} data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -18095,7 +18655,10 @@ <h3 class="faq-group-title">Where to get help</h3> const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); const humanIcon = actorKind === 'human' || actorKind === 'maintainer'; - const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item); + // A current requirement from the server (human_attention), or a + // decision the row carries itself (045 / 085 with decision_needed, + // which the server leaves out of human_attention past the gate). + const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item) || (typeof stageTrackerNeedsHumanAsk === 'function' && !!stageTrackerNeedsHumanAsk(item)); const actorIco = actorKind && (!humanIcon || humanRequired) ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; const actorTip = stageTrackerActorTip(item); // Guarded: test harnesses lift this function by name without stageTrackerHumanReason. @@ -18128,15 +18691,35 @@ <h3 class="faq-group-title">Where to get help</h3> if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + // Evidence-based remediation (stage_tracker_remediation.go): the PR in + // progress chevron pulses only while somebody is KNOWN to be on a red + // PR (kick / claim); "unassigned" is bright but still; a fix head + // pushed after the red signal is done-style with its word. + const codeOnHead = code && String(code.head || '') === String(item.head || ''); + const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; + if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; + // Both tracks running: the PR waits on them, nobody works it. The + // stage chevron is settled-current (bright words, no amber, no pulse) + // so the row never lights three chevrons (hivecommons/hive#16540). + const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; + const waitingOnTracks = tracksRunning === 2; + if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; + const blockerNote = sg.state === 'done' && sg.blockerNote ? String(sg.blockerNote) : ''; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', blockerNote ? 'ham-blocker-note' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; + let gateCaption = ''; if (active) { tip = sg.label + (sg.description ? ' — ' + sg.description : ''); if (sg.blocked) tip += ' — ' + stageTrackerBlockedTip(item); @@ -18148,7 +18731,10 @@ <h3 class="faq-group-title">Where to get help</h3> // With merge_gate in the payload the sentence is the gate's own // (what holds it, next sweep, soak left — #15073). const gateInfo = !sg.detour && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs, trains) : null; - if (gateInfo) tip = sg.label + ' — ' + gateInfo.tip; + if (gateInfo) { + tip = sg.label + ' — ' + gateInfo.tip; + gateCaption = [gateInfo.word, gateInfo.detail].filter(Boolean).join(' · '); + } else if (!sg.detour && (curStage === 60 || curStage === 80)) tip = sg.label + ' — not yet admitted' + (item.caption || item.reason ? ' — ' + (item.caption || item.reason) : ''); else if (curStage === STAGE_TRACKER_PRE_MERGE_SOAK) tip = sg.label + ' — admitted, soaking' + stageTrackerSoakLeft(item); else if (curStage === 100) tip = sg.label + ' — admitted, merging'; @@ -18170,9 +18756,12 @@ <h3 class="faq-group-title">Where to get help</h3> if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' · head ' + (item.head || 'unknown') + ' · ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown'); + if (code.detail) tip += ' · ' + code.detail; + if (evidence) tip += ' · ' + evidence; if (code.blocker) tip += ' · ' + code.blocker; if (claimant) tip += ' · ' + stageTrackerClaimantLine(claimant, nowMs); } + if (waitingOnTracks && !sg.cap) tip = 'Waiting on CI and review, both running — ' + tip; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -18199,9 +18788,32 @@ <h3 class="faq-group-title">Where to get help</h3> // The cap chevron is the ✓ only once the PR is merged; until then // the column is the row's history and wears the history mark. if (sg.cap) inner = sg.terminal ? stageTrackerIcon(sg.number, 'ham-ico') : stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — no decisions or actions recorded yet'); - else if (active) inner = gateCue + workIco + (decision ? stageTrackerDecisionTriggerHtml(decision, word, tip) : word) + (actorIco || holderIco); - else inner = stageTrackerIcon(sg.number, 'ham-ico'); - return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' — ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' — ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; + else if (active) { + const fullTip = [tip, gateCaption || (sg.detour ? sg.detour.text : sg.short), item.caption, item.reason, + item.head ? 'head ' + item.head : '', + item.hold ? (item.hold.pill || 'Held by @' + item.hold.by) + (item.hold.reason ? ' · ' + item.hold.reason : '') : ''].filter(Boolean).join(' · '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + const caption = gateWord || word; + const text = decision ? stageTrackerDecisionTriggerHtml(decision, caption, fullTip) : caption; + const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; + // A decision's dialog is its sole hover/focus detail surface. + inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else if (fixPushed) { + const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' · '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + } else if (blockerNote) { + // The issue's own column keeps the blocker in view while the + // covering PR's strip runs (hivecommons/docs#612): the word, the + // person glyph, and the blocker's detail as the hover. + const b = item.blocker || {}; + const noteTip = [blockerNote, b.detail, item.human_attention && item.human_attention.reason].filter(Boolean).join(' — '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(noteTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(blockerNote)}</span></span>${stageTrackerIcon('human', 'ham-ico ham-actor-ico', 'Next move: human')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(noteTip)}</span></span>`; + } else inner = stageTrackerIcon(sg.number, 'ham-ico'); + return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' — ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' — ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } @@ -18224,7 +18836,7 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + const word = !working && ['Fixing', 'Remediating'].includes(decidedInfo.word) ? 'Fix requested' : decidedInfo.word; text = word + (decidedInfo.detail ? ' · ' + decidedInfo.detail : '') + (regressed ? ' · ' + regressed : ''); } const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { @@ -18415,6 +19027,23 @@ <h3 class="faq-group-title">Where to get help</h3> return lines.join('\n'); } + // Pure: the one open covering PR an issue's `blocked` pill stands for + // when nothing else blocks the issue — no structured blocker, no + // blocked_on dependencies, no blocked-on-PR marker, no re-check + // deadline — and that PR is parked on a human decision (085). The + // pill then reads "decision on #N" rather than a bare "blocked" + // (rationguard#431 under #480). null otherwise. + function stageTrackerBlockedForDecisionPR(item) { + if (!item || item.kind !== 'issue' || item.blocker) return null; + if (Array.isArray(item.blocked_on) && item.blocked_on.length) return null; + if (typeof stageTrackerBlockedOnPR === 'function' && stageTrackerBlockedOnPR(item)) return null; + if (/^blocked until /i.test(String(item.bucket_reason || ''))) return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && (typeof stageTrackerLinkedPROpen !== 'function' || stageTrackerLinkedPROpen(lp, item))); + if (open.length !== 1) return null; + const lp = open[0]; + const parked = Number(lp.stage) === STAGE_TRACKER_NEEDS_DECISION || (Array.isArray(lp.modifiers) && lp.modifiers.indexOf('needs-decision') >= 0) || !!(lp.decision_needed && lp.decision_needed.question); + return parked ? lp : null; + } function stageTrackerChipsHtml(item) { // A row Hive cannot finish on its own: the server's your-turn decision // (item.finisher, from the status refresh rather than the current step) @@ -18448,8 +19077,10 @@ <h3 class="faq-group-title">Where to get help</h3> // A row the scheduler withholds for open GitHub "blocked by" dependencies names them (hivecommons/hive#14765); // one blocked on a PR (hive:blocked-on marker) names it and links to it (hivecommons/hive#14952). const blockedPR = mods[0] === 'blocked' ? stageTrackerBlockedOnPR(item) : null; + const decisionPR = mods[0] === 'blocked' && !blockedPR ? stageTrackerBlockedForDecisionPR(item) : null; if (mods[0] === 'blocked' && Array.isArray(item.blocked_on) && item.blocked_on.length) text = stageTrackerBlockedTip(item); else if (blockedPR) text = 'blocked on ' + blockedPR.short; + else if (decisionPR) text = 'decision on #' + Number(decisionPR.number); // A blocked row with a hive:recheck-after deadline ("blocked until <RFC3339>") names when the sweep re-checks it. const recheck = mods[0] === 'blocked' ? /^blocked until (\S+)/i.exec(String(item.bucket_reason || '')) : null; const recheckMs = recheck ? Date.parse(recheck[1]) : NaN; @@ -18461,7 +19092,14 @@ <h3 class="faq-group-title">Where to get help</h3> // the regressed pill explains itself; a blocked pill names what it waits on; // failing all three, a draft pill does. const anyBlockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; + // A needs-human pill's hover is the full ask (hivecommons/docs#612 + // showed a bare muted "needs human" with no reason anywhere on the row). + const askable = mods[0] === 'needs-human' || mods[0] === 'needs-decision'; + const ask = (askable && typeof stageTrackerHumanAttentionOf === 'function' && stageTrackerHumanAttentionOf(item)) + || (askable && typeof stageTrackerNeedsHumanAsk === 'function' && stageTrackerNeedsHumanAsk(item)) || null; const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed + || (decisionPR ? 'Blocked only because PR #' + Number(decisionPR.number) + ' waits on a human decision' + (decisionPR.decision_needed && decisionPR.decision_needed.question ? ' — ' + decisionPR.decision_needed.question : '') : '') + || (ask ? ask.reason : '') || (holdPill && typeof stageTrackerHoldTip === 'function' ? stageTrackerHoldTip(item, Date.now()) : '') || (mods.indexOf('blocked') >= 0 && Array.isArray(item.blocked_on) && item.blocked_on.length ? 'Withheld from the scanner until ' + item.blocked_on.join(', ') + (item.blocked_on.length > 1 ? ' close' : ' closes') : '') || (anyBlockedPR ? anyBlockedPR.tip : '') @@ -18474,8 +19112,12 @@ <h3 class="faq-group-title">Where to get help</h3> // popover (what to decide, who asked, the applicable actions) instead // of a native tooltip. // A hive-set hold is a decision too (release or keep): its pill opens the same popover. - const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || decisionPR || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; if (decision) return sentinel + stageTrackerDecisionTriggerHtml(decision, inner, tip, 'ham-badge ham-badge-mod ' + cls); + // No popover to open (the ask is the issue's own while a covering + // PR drives the strip): the pill is a button that reveals the row's + // "Needs human: …" note line and carries the full reason as its hover. + if (ask && typeof stageTrackerItemKey === 'function') return sentinel + `<button type="button" class="ham-badge ham-badge-mod ${esc(cls)} ham-needs-human-pill" data-action="stageTrackerNeedsHumanReveal" data-arg0="${esc(stageTrackerItemKey(item))}" data-stop="1" title="${esc(tip)}" aria-label="${esc(text + ' — ' + ask.reason + '. Click to show why on the row.')}">${inner}</button>`; return sentinel + `<span class="ham-badge ham-badge-mod ${esc(cls)}"${tip ? ` title="${esc(tip)}"` : ''}>${inner}</span>`; } @@ -18500,6 +19142,9 @@ <h3 class="faq-group-title">Where to get help</h3> 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', + // Historical ledger entries only: the hive now re-authors its own + // exhausted PRs itself and a person's rewrite of a contributor PR is adopt. + 're-author': 'Re-author (now: adopt)', }; // "Rebase, then merge as maintainer" is merge-now on a row that needs a // rebase (hivecommons/hive#14822): the server relabels the option and @@ -18614,7 +19259,7 @@ <h3 class="faq-group-title">Where to get help</h3> } // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:adopt', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. @@ -18715,28 +19360,99 @@ <h3 class="faq-group-title">Where to get help</h3> if (a.kind === 'pr' && String(a.head || '') !== String(item.head || '')) return null; return a; } - function stageTrackerHumanAttentionLine(item) { - const a = stageTrackerHumanAttentionOf(item); + // Pure: the decision a row carries itself when the server supplies no + // human_attention — a 045 issue or 085 PR with decision_needed, or a + // needs-human flag with a blocker (hivecommons/docs#612, rationguard#480). + // Same shape as human_attention ({reason, asked_by, question, synthetic}) + // so the note line reads the same either way. null when the row is not + // parked on a person, or when human_attention already says it. + function stageTrackerNeedsHumanAsk(item) { + if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL + || item.superseded_by || item.adopted_by) return null; + const mods = Array.isArray(item.modifiers) ? item.modifiers : []; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged')) return null; + if (stageTrackerHumanAttentionOf(item)) return null; + const n = Number(item.stage) || 0; + const flagged = item.needs_human === true || mods.indexOf('needs-human') >= 0 || mods.indexOf('needs-decision') >= 0 + || n === (typeof STAGE_TRACKER_NEEDS_DECISION === 'number' ? STAGE_TRACKER_NEEDS_DECISION : 85) + || n === (typeof STAGE_TRACKER_ISSUE_NEEDS_DECISION === 'number' ? STAGE_TRACKER_ISSUE_NEEDS_DECISION : 45); + if (!flagged) return null; + const d = item.decision_needed || {}; + const b = item.blocker || {}; + const actor = item.stage_actor || {}; + const question = String(d.question || '').trim(); + const why = String(actor.why || '').trim(); + const whyClause = why.indexOf(' — ') >= 0 ? why.slice(why.indexOf(' — ') + 3).trim() : ''; + // Only evidence the server put on the row counts — a parked stage + // alone synthesizes nothing (the row may be mid-refresh or hive-owned). + const reason = question || String(b.detail || '').trim() || String(d.blocker || '').trim() || String(b.short || '').trim() || (actor.kind === 'human' ? whyClause : ''); + if (!reason) return null; + return { kind: item.kind, number: Number(item.number) || 0, reason, question, asked_by: String(d.asked_by || actor.login && actor.kind === 'hive' && 'the hive' || '').trim() || 'the hive', synthetic: true }; + } + // Pure: "Needs human: <short> — <first sentence of the reason>", the + // short reason first so the row names the blocker before explaining it. + // A reason that already starts with the short form is not repeated. + // whole: keep the whole reason (a decision question is the ask itself). + function stageTrackerNeedsHumanReasonText(item, reason, whole) { + const full = String(reason || '').trim(); + const short = typeof stageTrackerNeedsHumanShort === 'function' ? stageTrackerNeedsHumanShort(item) : ''; + if (!short || full.toLowerCase().indexOf(short.toLowerCase()) === 0) return full; + const m = whole ? null : full.match(/^[\s\S]*?[.!?](?=\s|$)/); + const first = m ? m[0].trim() : full; + return first ? short + ' — ' + first : short; + } + // Pure: the label of the row's lead action, when a lifted copy has one + // (tracker-actions). '' without one, or when the lead is the optional + // delegation itself — that is not what the person is asked to do. + function stageTrackerNeedsHumanLeadLabel(item, subRows) { + if (typeof stageTrackerLeadActionOnRow !== 'function' || typeof stageTrackerActionCtx !== 'function') return ''; + const ctx = stageTrackerActionCtx(item.repo); + if (!ctx) return ''; + ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; + const action = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!action || !action.label || action.id === 'decide:delegate' || action.id === 'decide:delegate-all') return ''; + return String(action.label).replace(/\s*[▸›]\s*$/, ''); + } + // Pure: the one open covering PR a person other than the hive is pushing + // for this issue, when exactly one covers it. null otherwise. + function stageTrackerNeedsHumanPusher(item) { + if (!item || item.kind !== 'issue') return null; + if (typeof stageTrackerLinkedPROpen !== 'function') return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && stageTrackerLinkedPROpen(lp, item)); + if (open.length !== 1) return null; + const lp = open[0]; + const human = (lp.author_kind || '') === 'human' || (lp.author_kind || '') === 'maintainer'; + return human && lp.author ? lp : null; + } + function stageTrackerHumanAttentionLine(item, subRows) { + const a = stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item); if (!a) return ''; - const reason = String(a.reason || '').trim() || 'Human decision required; reason unavailable'; + const reason = stageTrackerNeedsHumanReasonText(item, String(a.reason || '').trim() || 'Human decision required; reason unavailable', !!(a.synthetic && a.question)); const parts = ['Needs human: ' + reason]; if (a.owner) parts.push('next move: @' + a.owner); - if (a.asked_by) parts.push('requested by ' + a.asked_by); + if (a.asked_by) parts.push((a.synthetic ? 'asked by ' : 'requested by ') + a.asked_by); + const lead = stageTrackerNeedsHumanLeadLabel(item, subRows); + if (lead) parts.push('lead: ' + lead + ' ▸'); + const pusher = stageTrackerNeedsHumanPusher(item); + if (pusher) parts.push('@' + pusher.author + ' is pushing it in #' + Number(pusher.number)); return parts.join(' · '); } - function stageTrackerHumanRequirementText(item) { + function stageTrackerHumanRequirementText(item, subRows) { if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL || item.superseded_by || item.adopted_by || (item.modifiers || []).some(m => m === 'draft' || m === 'hold' || m === 'merged')) return ''; - const human = stageTrackerHumanAttentionLine(item); + const human = stageTrackerHumanAttentionLine(item, subRows); const d = item && item.decided; const review = d && d.current_blocker && String(d.head || '') === String(item.head || '') ? 'Current blocker: ' + d.current_blocker + ' · operator approval recorded separately, not review approval or merge readiness' : ''; return [human, review].filter(Boolean).join(' · '); } - function stageTrackerHumanContextOf(item, stages) { + function stageTrackerHumanContextOf(item, stages, subRows) { if (!item) return []; - const own = stageTrackerHumanRequirementText(item); - const out = own ? [{ item, text: own }] : []; + const own = stageTrackerHumanRequirementText(item, subRows); + // An issue's own ask is prefixed with its number, like a PR's line, + // so a row whose strip a covering PR drives still names the asker. + const asks = item.kind === 'issue' && !!(stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item)); + const out = own ? [{ item, text: (asks ? '#' + Number(item.number) + ' — ' : '') + own }] : []; if (item.kind !== 'issue') return out; // Include external drawn_under references, but never walk RFC ancestry // or assign one child's requirement to the issue / its other PRs. @@ -18753,26 +19469,65 @@ <h3 class="faq-group-title">Where to get help</h3> } return out; } - function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { - const required = stageTrackerHumanContextOf(item, stages); - const lines = required.map(entry => { - const it = entry.item; + // A human-requirement line is a hive note: it opens, then tucks into + // its ⬡ icon like the "Hive: …" line (stageTrackerHumanNoteHtml, + // tracker-motion). Lifted copies without tracker-motion (tests, + // previews) render the plain row instead. + function stageTrackerHumanContextLine(item, bodyHtml, text, nowMs) { + if (typeof stageTrackerHumanNoteHtml === 'function' && typeof stageTrackerItemKey === 'function') { + return stageTrackerHumanNoteHtml(stageTrackerItemKey(item), bodyHtml, text, nowMs); + } + return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; + } + /* ---- One note line per row ----------------------------------------- + Owner (2026-11-05): "we don't need 2 hive comments — there should + always be only one." A row used to stack its "Needs human: …" line + over the "Hive: moved to …" stage note. Now every candidate is + ranked — needs-human / decision (0) > blocker (1) > next move / + claim (2) > optional delegation (3) > stage-transition note (4) — + and the row renders the winner alone. Same-rank human asks (an + issue's and its PR's) share the line, " · " apart, each with its + View link. A lower line's facts ride along as a trailing clause + only when they say something the row does not already: a stage + note that merely restates the lit chevron ("moved to Needs human + decision" under a strip lit at Needs human decision) is dropped. */ + const STAGE_TRACKER_NOTE_RANK_HUMAN = 0; + const STAGE_TRACKER_NOTE_RANK_BLOCKER = 1; + const STAGE_TRACKER_NOTE_RANK_NEXT = 2; + const STAGE_TRACKER_NOTE_RANK_OPTIONAL = 3; + // Mod-change words (tracker-motion) a "Needs human:" line already says. + const STAGE_TRACKER_NOTE_HUMAN_RESTATES = ['waiting on a person', 'waiting on a decision']; + function stageTrackerNoteRankOf(text) { + const t = String(text || ''); + if (/(^|— )Needs human:|decision context unavailable/.test(t)) return STAGE_TRACKER_NOTE_RANK_HUMAN; + if (/Current blocker:/.test(t)) return STAGE_TRACKER_NOTE_RANK_BLOCKER; + if (/^Optional delegation:/.test(t)) return STAGE_TRACKER_NOTE_RANK_OPTIONAL; + return STAGE_TRACKER_NOTE_RANK_NEXT; + } + // Pure: the candidate human lines for the row, each { body, text, rank }. + function stageTrackerHumanContextEntries(item, stages, nowMs, subRows) { + const required = stageTrackerHumanContextOf(item, stages, subRows); + const entry = (body, text) => ({ body, text, rank: stageTrackerNoteRankOf(text) }); + const lines = required.map(e => { + const it = e.item; const href = it.url || item.url; - return `<div class="cue-event ham-human-context"><span>${esc(entry.text)}${href ? ` <a href="${esc(href)}" target="_blank" rel="noopener">View ${it.kind === 'pr' ? 'PR' : 'issue'} #${Number(it.number)}</a>` : ''}</span></div>`; + const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; + return entry(esc(e.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''), e.text + (view ? ' · ' + view : '')); }); - if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); + if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines; const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); const staleLinks = item.kind === 'issue' ? (item.linked_prs || []).filter(lp => stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; - return `<div class="cue-event ham-human-context"><span>${esc(refs)} · decision context unavailable for the displayed identity/head${item.url ? ` · <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''}</span></div>`; + const text = refs + ' · decision context unavailable for the displayed identity/head'; + return [entry(esc(text) + (item.url ? ` · <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text)]; } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => - stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return ''; + stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return []; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; - if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return ''; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return []; const actor = item.stage_actor; const actorHuman = actor && (actor.kind === 'human' || actor.kind === 'maintainer'); const claimant = item.claimant; @@ -18782,9 +19537,11 @@ <h3 class="faq-group-title">Where to get help</h3> const who = actor.login ? '@' + actor.login : 'a person'; const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; - lines.push(`<div class="cue-event ham-human-context"><span>Next move: ${esc(who + target)}${actor.why ? ' — ' + esc(actor.why) : ' · action reason unavailable'}</span></div>`); + const text = 'Next move: ' + who + target + (actor.why ? ' — ' + actor.why : ' · action reason unavailable'); + lines.push(entry(esc(text), text)); } else if (claimant && claimant.kind === 'person' && claimant.login) { - lines.push(`<div class="cue-event ham-human-context"><span>Claimed by @${esc(claimant.login)} · claim ownership, not a human decision request</span></div>`); + const text = 'Claimed by @' + claimant.login + ' · claim ownership, not a human decision request'; + lines.push(entry(esc(text), text)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -18793,23 +19550,82 @@ <h3 class="faq-group-title">Where to get help</h3> ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { - lines.push('<div class="cue-event ham-human-context"><span>Optional delegation: Let hive decide is available; it does not itself mean human input is required.</span></div>'); + const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; + lines.push(entry(esc(text), text)); } } } - return lines.join(''); + return lines; + } + // Pure: the row's current stage as the chevron names it ('' unknown). + function stageTrackerNoteStageName(item, stages) { + if (!item) return ''; + const sg = (Array.isArray(stages) ? stages : []).find(x => Number(x.number) === (Number(item.stage) || 0)); + if (typeof stageTrackerStageName === 'function') return stageTrackerStageName(sg) || stageTrackerStageName({ label: item.stage_label || '', short: '' }); + return sg ? String(sg.short || sg.label || '') : String(item.stage_label || ''); + } + // Pure: the stage note's words worth keeping under a human line, or + // '' when the line (or the lit chevron) already says it. + function stageTrackerNoteFoldText(evText, lineText, item, stages) { + const t = String(evText || '').trim(); + if (!t) return ''; + const line = String(lineText || '').toLowerCase(); + if (line.indexOf(t.toLowerCase()) >= 0) return ''; + if (/needs human:/i.test(line) && STAGE_TRACKER_NOTE_HUMAN_RESTATES.indexOf(t) >= 0) return ''; + const m = /^(?:moved to|fell back to) (.+)$/.exec(t); + if (m) { + const name = stageTrackerNoteStageName(item, stages).toLowerCase(); + const said = m[1].split(' — ')[0].trim().toLowerCase(); + if (name && said === name && m[1].indexOf(' — ') < 0) return ''; + } + return t; + } + // ctx / key (the row's events map and its key) let the human line + // absorb the row's stage note so the row shows one line, not two. + function stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, key) { + let entries = stageTrackerHumanContextEntries(item, stages, nowMs, subRows); + if (!entries.length) return ''; + const best = Math.min.apply(null, entries.map(e => e.rank)); + // "Let hive decide is available" is a control the row shows anyway; + // it only earns the line when nothing else wants it. + if (best < STAGE_TRACKER_NOTE_RANK_OPTIONAL) entries = entries.filter(e => e.rank < STAGE_TRACKER_NOTE_RANK_OPTIONAL); + entries.sort((a, b) => a.rank - b.rank); + let body = entries.map(e => e.body).join(' · '); + let text = entries.map(e => e.text).join(' · '); + const ev = ctx && ctx.events && key ? ctx.events[key] : null; + const fold = ev ? stageTrackerNoteFoldText(ev.text, text, item, stages) : ''; + if (fold) { + const who = ev.who === 'you' ? 'You: ' : ev.who === 'merge' ? 'Merge: ' : ''; + body += ' · ' + esc(who + fold); text += ' · ' + who + fold; + } + return stageTrackerHumanContextLine(item, body, text, nowMs); + } + // Pure: ctx without the row's stage note once the human line has + // taken it (folded or dropped), so the event slot stays empty. + function stageTrackerNoteTakenCtx(ctx, key) { + if (!ctx || !ctx.events || !key || !ctx.events[key]) return ctx; + const events = Object.assign({}, ctx.events); + delete events[key]; + return Object.assign({}, ctx, { events }); } // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs, and the cap cell the modifier chip, bottom-aligned so - // it sits on the last title line, directly over the strip's right end. + // the given refs followed by the modifier chips / action buttons, + // right-anchored on that same line (margin-left: auto). The chips ride + // the title line rather than a second full-width toolbar line, so the + // chevrons sit directly under the title (hivecommons/hive#16454 left a + // one-line band between them); when the PR metadata leaves no room the + // chips wrap under it, content-driven, never a fixed row. A row without + // PR refs still gets the PR cell (ham-head-tools) so its chips sit on + // the title line in the PR span, not on a line of their own. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); - return `<div class="ham-strip-row ham-head-cols"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li><li class="ham-seg ham-head-pr${wide ? ' ham-head-tools' : ''}"${!wide && prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${wide ? '' : prRefs.join('')}<span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { @@ -18867,7 +19683,7 @@ <h3 class="faq-group-title">Where to get help</h3> ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0, @@ -18923,13 +19739,17 @@ <h3 class="faq-group-title">Where to get help</h3> if (l.kind === 'superseded') return Number(l.to_number) > 0 ? 'superseded by #' + Number(l.to_number) + tail : ''; if (!(Number(l.from_number) > 0)) return ''; const whose = l.from_author ? '@' + l.from_author + "'s " : ''; - return (l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : 'adopted from ') + whose + '#' + Number(l.from_number) + tail; + // "re-authored from #N" is the hive rewriting its OWN exhausted PR; + // "adopted from" is a contributor's PR the hive took over. + const verb = l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : l.kind === 're-authored' ? 're-authored from ' : 'adopted from '; + return verb + whose + '#' + Number(l.from_number) + tail; } // Pure: the hover — why the hive took it over, in plain words. function stageTrackerLineageTip(item) { const l = item && item.lineage; if (!l || !l.kind) return ''; if (l.kind === 'superseded') return 'Hive took this PR over as #' + Number(l.to_number) + '; this original is closed when that merges.'; + if (l.kind === 're-authored') return "Hive's fixer gave up on its own #" + Number(l.from_number) + ', so the hive closed it as superseded and opened this fresh PR from the current base.' + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); const who = l.from_author ? '@' + l.from_author : 'the contributor'; const tip = STAGE_TRACKER_LINEAGE_REASON_TIP[l.reason] || STAGE_TRACKER_LINEAGE_REASON_TIP['ci-red-contributor-offline']; return tip.split('@AUTHOR').join(who) + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); @@ -18960,7 +19780,7 @@ <h3 class="faq-group-title">Where to get help</h3> let l = item && item.lineage; if (!l && item && item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length === 1) l = item.linked_prs[0].lineage; if (!l || !(Number(l.from_number) > 0) || l.kind === 'superseded') return ''; - return ' (adopted from #' + Number(l.from_number) + ')'; + return (l.kind === 're-authored' ? ' (re-authored from #' : ' (adopted from #') + Number(l.from_number) + ')'; } // Pure: the "↳ adopted from #N · you let hive decide 17:51" chip on the // hive's copy of an adopted PR (hivecommons/hive#15126). @@ -19019,12 +19839,10 @@ <h3 class="faq-group-title">Where to get help</h3> if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(pr); const superseded = typeof stageTrackerLinkedSupersededText === 'function' ? stageTrackerLinkedSupersededText(lp, issue) : ''; let ref = stageTrackerPRRef(pr.number, pr.url, pr.author_kind, pr.author, pr.title, (pr.title ? pr.title + ' · ' : '') + (superseded ? superseded + ' · ' + stageTrackerLinkedSupersededTip(lp) : stageTrackerTooltip(pr, nowMs)) + ' · ' + stageTrackerLinkedTip(issue, pr.number, ctx)); - // One line (hivecommons/hive: "consolidate from 3 lines of text to - // 1"): connector, repo chip, author icon + #N + title, the lineage / - // adopted-from chip, then the base pill — all siblings of the flex-row - // PR cell; the title ellipsizes, the pills never shrink. A superseded - // original wears neither pill — it closes as superseded, not as the - // closer of anything. + // Connector, repo chip, author icon + #N + title, lineage / + // adopted-from chip and base pill share the wrapping PR-side cell. + // A superseded original wears neither pill — it closes as superseded, + // not as the closer of anything. const lineage = superseded ? '' : ((typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(pr, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(pr, nowMs) : '')); const chip = ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : ''; if (chip) ref = `<span class="ham-pr-line">${chip}${ref}</span>`; @@ -19033,7 +19851,7 @@ <h3 class="faq-group-title">Where to get help</h3> if (superseded) { // The adopted original: one muted line, no chevron track, no row // tools, no needs-human styling — the copy carries the chevron. The - // trailing note never wraps; the title ellipsizes first (owner, + // trailing note stays distinct from the wrapping title (owner, // hivecommons/hive#15511: "superseded · hive adopted → #15574"). return `<div class="ham-sub ham-sub-superseded" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}" data-ham-superseded-by="${Number(lp.superseded_by || lp.adopted_by) || 0}"> <div class="ham-row-head"> @@ -19041,6 +19859,9 @@ <h3 class="faq-group-title">Where to get help</h3> </div> </div>`; } + const subKey = stageTrackerItemKey(pr); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs, undefined, ctx, subKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, subKey) : ctx; return `<div class="ham-sub${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(pr, ctx) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(pr, stages, ctx) : ''}" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}"> ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''} <div class="ham-row-head"> @@ -19051,7 +19872,7 @@ <h3 class="faq-group-title">Where to get help</h3> <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(pr), ctx)}>${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(pr, nowMs)} </div> - ${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs) : ''}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, ctx, stageTrackerItemKey(pr)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(pr), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} </div>`; } @@ -19297,7 +20118,7 @@ <h3 class="faq-group-title">Where to get help</h3> shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, finisher: fin.finisher || '', finisher_verb: fin.finisher_verb || '', finisher_reason: fin.finisher_reason || '' }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed @@ -19350,6 +20171,11 @@ <h3 class="faq-group-title">Where to get help</h3> const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(shown); + // One note line per row: the human line takes the stage note (folded + // or dropped), so the event slot below the caption renders nothing. + const rowKey = stageTrackerItemKey(item); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; return `<div class="ham-row${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(shown, ctx) : ''}${typeof stageTrackerTrainRowClass === 'function' ? stageTrackerTrainRowClass(item, ctx.prevRow || null, ctx.nextRow || null, ctx.trainIndex && trainKey ? ctx.trainIndex[trainKey] : undefined) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(item, stages, ctx) : ''}" tabindex="0" data-ham-kind="${esc(item.kind)}" data-ham-repo="${esc(item.repo || '')}" data-ham-stage="${Number(item.stage) || 0}"${prs ? ` data-ham-prs="${esc(prs)}"` : ''}${trainKey ? ` data-ham-train="${esc(trainKey)}"` : ''}> ${stageTrackerRowToolsHtml(item)} <div class="ham-row-head"> @@ -19359,7 +20185,7 @@ <h3 class="faq-group-title">Where to get help</h3> ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(item), ctx)}>${stageTrackerStripItems(shown, stages, range, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(shown, nowMs)} - </div>${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows) : ''}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, ctx, stageTrackerItemKey(item)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(item), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} + </div>${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} </div>`; } @@ -19559,6 +20385,7 @@ <h3 class="faq-group-title">Where to get help</h3> const next = stageTrackerStateMap(d && d.items); const ttl = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting() ? Infinity : STAGE_TRACKER_EVENT_MS; _stageTrackerEvents = stageTrackerEventsNext(_stageTrackerEvents, _stageTrackerStates, next, d && d.stages, nowMs, ttl); + _stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, next); _stageTrackerStates = next; } /* ---- Hive notes: show, then tuck --------------------------------------- @@ -19630,6 +20457,7 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerNoteTitle(ev, nowMs) { if (!ev) return ''; const age = stageTrackerAgoText(ev.at, nowMs); + if (ev.who === 'human') return ev.text + (age ? ' · ' + age : ''); return (ev.who === 'you' ? 'You' : 'Hive') + ': ' + ev.text + (age ? ' · ' + age : ''); } let _stageTrackerNoteTimer = 0; @@ -19644,7 +20472,7 @@ <h3 class="faq-group-title">Where to get help</h3> // it went hidden (the age keeps counting). const openNow = _stageTrackerNoteHiddenAt || nowMs; for (const p of Array.from(el.querySelectorAll('.cue-event[data-cue-key]'))) { - const ev = _stageTrackerEvents[p.getAttribute('data-cue-key')]; + const ev = stageTrackerNoteEventOf(p.getAttribute('data-cue-key')); const open = !ev || stageTrackerNoteOpen(ev, openNow, auto); if (open) p.classList.remove('cue-event-tucked'); else p.classList.add('cue-event-tucked'); const btn = p.querySelector('.cue-event-ico'); @@ -19655,18 +20483,32 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerNoteSchedule(nowMs) { if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } if (document.hidden) return; - const due = stageTrackerNoteNextDue(_stageTrackerEvents, nowMs, stageTrackerNoteTuckSetting()); + const due = stageTrackerNoteNextDue(stageTrackerNoteEventsAll(), nowMs, stageTrackerNoteTuckSetting()); if (due === Infinity) return; _stageTrackerNoteTimer = setTimeout(() => { _stageTrackerNoteTimer = 0; stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), Date.now()); }, due); } // The icon's click (and Enter / Space, it is a button). function stageTrackerNoteToggle(key) { - const ev = _stageTrackerEvents[key]; + const ev = stageTrackerNoteEventOf(key); if (!ev) return; const nowMs = Date.now(); - _stageTrackerEvents[key] = stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting()); + stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } + // The row's "needs human" pill: bring its "Needs human: …" line into + // view, untucked. rowKey: the row's data-ham-key. + function stageTrackerNeedsHumanReveal(rowKey) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel || !rowKey) return; + const rows = panel.querySelectorAll('.ham-row[data-ham-key]'); + let row = null; + for (const r of rows) if (r.getAttribute('data-ham-key') === String(rowKey)) { row = r; break; } + if (!row) return; + const line = row.querySelector('.ham-human-context[data-cue-key]'); + if (!line) return; + if (line.classList.contains('cue-event-tucked')) stageTrackerNoteToggle(line.getAttribute('data-cue-key')); + if (typeof line.scrollIntoView === 'function') line.scrollIntoView({ block: 'nearest' }); + } // Hidden tab: stop the clock on every open line; visible again: give // back the hidden time and re-arm. function stageTrackerNoteVisibility(hidden, nowMs) { @@ -19676,7 +20518,11 @@ <h3 class="faq-group-title">Where to get help</h3> if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } return; } - if (_stageTrackerNoteHiddenAt) { _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); _stageTrackerNoteHiddenAt = 0; } + if (_stageTrackerNoteHiddenAt) { + _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerHumanNotes = stageTrackerNoteShift(_stageTrackerHumanNotes, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerNoteHiddenAt = 0; + } stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // The owner's own action writes the row's line at once ("you: approved"). @@ -19693,15 +20539,71 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerEventHtml(key, ctx) { const ev = ctx && ctx.events ? ctx.events[key] : null; if (!ev) return ''; + const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; + const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; + return stageTrackerNoteLineHtml(key, ev, ctx, body, ''); + } + // Pure: one note line — the shared shape behind the hive line and the + // human-requirement line, so both open, tuck and re-open the same way. + function stageTrackerNoteLineHtml(key, ev, ctx, body, extraClass) { const nowMs = ctx && typeof ctx.nowMs === 'number' ? ctx.nowMs : Date.now(); const auto = ctx && typeof ctx.noteTuck === 'boolean' ? ctx.noteTuck : (typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting()); const fading = !auto && nowMs - stageTrackerEventShownAt(ev) > STAGE_TRACKER_EVENT_MS * 2 / 3; const open = !auto || stageTrackerNoteOpen(ev, nowMs, auto); - const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; - const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; - if (!auto) return `<p class="cue-event${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; + const cls = extraClass ? ' ' + extraClass : ''; + if (!auto) return `<p class="cue-event${cls}${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; const ico = `<button type="button" class="cue-event-ico" aria-label="${STAGE_TRACKER_NOTE_LABEL}" aria-expanded="${open ? 'true' : 'false'}" title="${esc(stageTrackerNoteTitle(ev, nowMs))}" data-action="stageTrackerNoteToggle" data-arg0="${esc(key)}" data-stop="1">${STAGE_TRACKER_NOTE_ICON}</button>`; - return `<p class="cue-event cue-event-tuckable${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + return `<p class="cue-event cue-event-tuckable${cls}${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + } + /* ---- Human-requirement notes ------------------------------------- + "Needs human: …" / "Current blocker: …" (tracker-human-attention) + are hive comments too. #16011 drew them as a static row under the + item so the ask stayed readable; the owner (2026-11-04): "these + things should be hive comments and they should hide (slide-left) + as they used to." They now ride the same show-then-tuck line as the + hive note — the row's Let hive decide / Sentinel alert controls keep + the decision state in view after the words tuck. Their own map, + keyed by row and words, remembers when this tab first showed each + line so a re-render never re-opens one already seen; a row leaving + the payload (or its words changing) drops the entry. */ + let _stageTrackerHumanNotes = {}; + function stageTrackerTextHash(text) { + let h = 5381; + for (let i = 0; i < text.length; i++) h = (h * 33 + text.charCodeAt(i)) >>> 0; + return h.toString(36); + } + function stageTrackerHumanNote(rowKey, text, nowMs) { + const key = 'human:' + rowKey + ':' + stageTrackerTextHash(text); + let ev = _stageTrackerHumanNotes[key]; + if (!ev) { ev = { who: 'human', row: rowKey, text, at: nowMs }; _stageTrackerHumanNotes[key] = ev; } + return { key, ev }; + } + // Pure: the human notes still backed by a row in nextStates. + function stageTrackerHumanNotesNext(notes, nextStates) { + const out = {}; + for (const k of Object.keys(notes || {})) if (!nextStates || nextStates[notes[k].row]) out[k] = notes[k]; + return out; + } + // bodyHtml is the line's already-escaped words (with its View link); + // text is the plain words the icon's tooltip and the key use. + function stageTrackerHumanNoteHtml(rowKey, bodyHtml, text, nowMs) { + nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); + const { key, ev } = stageTrackerHumanNote(rowKey, text, nowMs); + const auto = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting(); + // Auto-collapse off: the old two-minute life and fade, like a hive line. + if (!auto && nowMs - stageTrackerEventShownAt(ev) >= STAGE_TRACKER_EVENT_MS) return ''; + return stageTrackerNoteLineHtml(key, ev, { nowMs, noteTuck: auto }, `<span class="cue-event-text">${bodyHtml}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`, 'ham-human-context'); + } + // A note by key from either map; a toggle writes back to the map it + // came from. + function stageTrackerNoteEventOf(key) { + return _stageTrackerEvents[key] || _stageTrackerHumanNotes[key] || null; + } + function stageTrackerNoteEventSet(key, ev) { + if (_stageTrackerEvents[key]) _stageTrackerEvents[key] = ev; else _stageTrackerHumanNotes[key] = ev; + } + function stageTrackerNoteEventsAll() { + return Object.assign({}, _stageTrackerHumanNotes, _stageTrackerEvents); } const STAGE_TRACKER_CUE_TICK_MS = 15000; function stageTrackerCueAgeSync(el, nowMs) { @@ -20021,7 +20923,7 @@ <h3 class="faq-group-title">Where to get help</h3> // The hive note's open / tucked state is applied in place // (stageTrackerNoteSync), so it is not a reason to swap the node either. function stageTrackerRowSrcKey(html) { - return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="(?:You|Hive): [^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); + return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="[^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); } // Pure: whether the stamped move attributes name this strip. function stageTrackerRowHasMove(html) { return / data-ham-prev-col="\d+"/.test(String(html || '')); } @@ -20033,6 +20935,12 @@ <h3 class="faq-group-title">Where to get help</h3> tpl.innerHTML = html; const node = tpl.content.firstElementChild; node.dataset.hamKey = key; + // Bind canonical lane geometry when materializing root and nested rows. + if (typeof node.querySelectorAll === 'function') { + for (const header of node.querySelectorAll('.ham-head-cols[data-ham-pr-start]')) { + header.style.setProperty('--ham-pr-start', header.dataset.hamPrStart); + } + } if (_stageTrackerRowSrc) _stageTrackerRowSrc.set(node, stageTrackerRowSrcKey(html)); return node; } @@ -21753,15 +22661,15 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } // Pure: the DCO caveat the merge confirmations print BEFORE acting // when the stage record counted unsigned commits on the head (#15136): - // merging as-is then fails where DCO is required; re-authoring is the - // separate choice. + // merging as-is then fails where DCO is required; adopting as a hive + // PR is the separate choice. function stageTrackerDCOCaveat(items) { const rows = (Array.isArray(items) ? items : [items]).filter(it => it && Number(it.dco_unsigned) > 0); if (!rows.length) return ''; const it = rows[0]; const total = Number(it.dco_total) || 0; const of = total > 0 ? ' of ' + total + ' commit' + (total === 1 ? '' : 's') : ' commit' + (Number(it.dco_unsigned) === 1 ? '' : 's'); - return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Re-author as hive PR" is the separate choice for that; approving does not re-author.'; + return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Adopt as hive PR" is the separate choice for that; approving does not adopt.'; } const STAGE_TRACKER_ACTION_LABELS = { 'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide — all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', @@ -21770,7 +22678,6 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> 'decide:close-issue': 'Close issue', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', - 'decide:re-author': 'Re-author as hive PR', 'decide:adopt-now': 'Adopt now — hive takes it over', 'decide:reroute': 'Reroute to another clanker', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', @@ -21783,8 +22690,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // merger or owner only, like POST .../queue-automerge. const STAGE_TRACKER_MERGE_ACTIONS = ['decide:queue-merge', 'decide:merge-now']; // Generic items every row has; a server-named decision option with one - // of these ids is not repeated at the top of the menu. - const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt', 'decide:close-issue']; + // of these ids is not repeated at the top of the menu. `decide:adopt` + // is not generic: a row offers it either from the nudge (`adoption`) + // or as a server decision option (a contributor PR's DCO / fixer + // exhaustion, where it replaced "re-author"), never both. + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:close-issue']; const _stageTrackerCloseIssueBusy = new Set(); // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / @@ -21991,7 +22901,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const out = []; // First: the hive decides as the owner's delegate (policy + rails on // the server; recorded as a human decision with an audit marker). - out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled, why }); + // The server may rule delegation out for this row (a capability gap + // no decision closes — hivecommons/docs#612); its reason wins. + const served = stageTrackerServerDelegate(item); + const delegateOff = !!served && served.enabled === false; + out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled: enabled && !delegateOff, why: delegateOff ? (served.reason_if_disabled || 'The hive cannot decide this one') : why }); if (item.kind === 'pr') { out.push({ id: 'decide:approve', label: 'Approve (/lgtm + /approve)', enabled, why }); out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); @@ -22005,6 +22919,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> out.push({ id: 'decide:close-wontfix', label: "Close as won't-fix…", enabled, why, danger: true }); return out; } + // Pure: the server's decide:delegate option on the row, or null. + function stageTrackerServerDelegate(item) { + const opts = item && item.decision_needed && Array.isArray(item.decision_needed.options) ? item.decision_needed.options : []; + return opts.find(o => o && o.action === 'decide:delegate') || null; + } // Pure: the operator note for labels the row's stage has outrun // (stale_labels: a needs-triage still on a claimed issue, which the // reconciler removes on its next pass — hivecommons/hive#14586). '' when none. @@ -22187,7 +23106,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). if (typeof stageTrackerBlockerActions === 'function') for (const a of stageTrackerBlockerActions(item, ctx)) out.push(a); - if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item)) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); + if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item) && !out.some(a => a.id === 'decide:adopt')) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); // A PR waiting on a contributor's clanker offers Adopt now and Reroute // (hivecommons/hive#15038); each disabled with the server's reason. if (typeof stageTrackerTakeoverActions === 'function') for (const a of stageTrackerTakeoverActions(item, ctx, ctx.nowMs)) out.push(a); @@ -22217,6 +23136,15 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> if (lead) return lead; const decide = actions.find(a => a.id === 'decide'); const safe = decide && Array.isArray(decide.submenu) ? decide.submenu.filter(x => x && !x.danger) : []; + // The server ruled delegation out (a capability gap): the first + // enabled, non-destructive blocker option leads instead — the + // person's actual move (open App settings, re-check permissions), + // not a greyed "Let hive decide" (hivecommons/docs#612). + const served = stageTrackerServerDelegate(item); + if (served && served.enabled === false) { + const b = stageTrackerBlockerActions(item, ctx).find(x => x.enabled && !x.danger); + if (b) return Object.assign({}, b, { target: (decide && decide.target) || { kind: item.kind, number: item.number, repo: item.repo } }); + } if (safe.length) { const o = safe.find(x => x.enabled) || safe[0]; const enabled = !!decide.enabled && !!o.enabled; @@ -22289,12 +23217,50 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const sub = typeof stageTrackerLinkedPRItem === 'function' ? stageTrackerLinkedPRItem(item, lp) : null; return sub && stageTrackerLeadAction(sub, ctx) ? null : a; } - // The inline lead button for a row: a real <button> carrying the same - // id, hint and enable/disable reason as the ⋯ menu entry it mirrors; + // Pure: the second inline pill of a row parked on a human decision — + // the Decide… submenu's "Let hive decide" (decide:delegate), carrying + // the decide target and enable reason the way stageTrackerLeadAction's + // fallback does — when the server's lead is another verb (Re-author, + // Merge now…). A row saw only "Re-author" and asked where "Let hive + // decide" went (hivecommons/hive#16265 / #16456): the ⋯ menu is + // invisible, so both stand on the row. null when the lead already is + // delegate, the row has no human decision, or the lead is a passive chip. + function stageTrackerLeadCompanion(item, ctx, lead) { + if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; + const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const human = !!(dec && dec.item && dec.item.decision_needed) || !!item.decision_needed || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + if (!human) return null; + const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); + const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; + if (!o) return null; + const enabled = !!decide.enabled && !!o.enabled; + return Object.assign({}, o, { target: decide.target, enabled, why: enabled ? '' : (decide.enabled ? o.why : decide.why), hint: STAGE_TRACKER_ACTION_CONSEQUENCES['decide:delegate'], companion: true }); + } + // Pure: the inline pills a row renders — its lead, then (a row parked + // on a human decision whose lead is not delegate) "Let hive decide". + function stageTrackerLeadActionsOnRow(item, ctx, subRows) { + const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!a) return []; + const companion = stageTrackerLeadCompanion(item, ctx, a); + return companion ? [a, companion] : [a]; + } + // The inline lead button(s) for a row: real <button>s carrying the same + // id, hint and enable/disable reason as the ⋯ menu entries they mirror; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. function stageTrackerLeadActionHtml(item, ctx, subRows) { - const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + return stageTrackerLeadActionsOnRow(item, ctx, subRows).map(a => stageTrackerLeadPillHtml(item, a)).join(''); + } + // The hover text of an inline pill when the server sent no + // `consequence`: what happens when it is pressed, in one clause. + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + // A row's inline pills are buttons and must read as buttons beside the + // record pills they share a slot with ("adopted from #N", the base + // branch): a filled chip — ham-act-primary (the lead), ham-act-secondary + // ("Let hive decide" beside it) or ham-menu-danger — with a trailing + // glyph (tracker.css ::after). Owner on #16456: "Re-author" in the + // outlined pill read as a record of what happened, not a verb. + function stageTrackerLeadPillHtml(item, a) { if (!a) return ''; // The covering PR has its own row (or is drawn under another listed // issue): the decision — whatever its lead (Let hive decide, Merge @@ -22309,10 +23275,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> return `<button type="button" class="ham-badge ham-decision-pending" data-ham-scroll-to="${esc(to)}"${via} title="${esc('The decision is on PR #' + a.passive + ' — ' + String(a.label || a.id) + ' lives on ' + where + '. Click to go there.')}">decision pending on #${Number(a.passive) || 0}</button>`; } const label = String(a.label || a.id); - const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); + const tip = a.enabled ? String(a.hint || a.note || a.consequence || STAGE_TRACKER_ACTION_CONSEQUENCES[a.id] || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; const state = a.enabled ? (tip ? ` title="${esc(tip)}"` : '') : ` aria-disabled="true" title="${esc(tip)}"`; - return `<button type="button" class="ham-lead-act${a.danger ? ' ham-menu-danger' : ''}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' — ' + ref : ''))}">${esc(label)}</button>`; + const tone = a.danger ? ' ham-menu-danger' : (a.companion ? ' ham-act-secondary' : ' ham-act-primary'); + return `<button type="button" class="ham-lead-act${tone}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' — ' + ref : ''))}">${esc(label)}</button>`; } // Pure: the actions for a row parked on a blocker (hivecommons/hive#15099): // the server lists them in decision_needed.options (a capability gap @@ -22638,6 +23605,13 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const pr = stageTrackerLinkedPRItem(item, asking[0]); return { key: stageTrackerItemKey(pr), item: pr }; } + // Pure: whether the row's decision card (its own or its one parked + // PR's) offers the server option `action`. + function stageTrackerServerOption(item, action) { + const dec = stageTrackerDecisionOf(item); + const d = dec && dec.item && dec.item.decision_needed; + return !!(d && Array.isArray(d.options) && d.options.some(o => o && o.action === action)); + } // Pure: the trigger — the chevron word or the pill, as a button that // owns the popover. No native title: the popover is the hover text. function stageTrackerDecisionTriggerHtml(decision, innerHtml, tip, cls) { @@ -22759,9 +23733,14 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> function stageTrackerOpenDecisionPop(trigger, pin) { const key = trigger && trigger.dataset ? trigger.dataset.hamDecision : ''; if (!key) return; + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); if (_stageTrackerDecisionPop && _stageTrackerDecisionPop.key === key) { if (pin) _stageTrackerDecisionPop.pinned = true; clearTimeout(_stageTrackerDecisionPop.timer); + if (pin && pin.focus) { + const first = _stageTrackerDecisionPop.el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); + (first || _stageTrackerDecisionPop.el).focus({ preventScroll: true }); + } return; } stageTrackerCloseDecisionPop(false); @@ -22814,7 +23793,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> window.addEventListener('resize', p.onAway); window.addEventListener('scroll', p.onAway, true); _stageTrackerDecisionPop = p; - if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus(); } + if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus({ preventScroll: true }); } } // The pointer left the trigger or the popover: close after a beat unless // it is pinned or the pointer is back over either (rows re-render, so @@ -23654,10 +24633,6 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } case 'decide:queue-merge': return (await stageTrackerAsk(id, 'confirm', { title: 'Approve and let hive merge', message: preface + 'Approve ' + refs + ' as ' + who + '? Your approval stands in for the author\'s trust on this version: hive merges it as-is through its own App on the next tick once CI is green, and will not adopt or re-author it.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve' })) ? {} : null; - case 'decide:re-author': { - const caveat = stageTrackerDCOCaveat(items); - return (await stageTrackerAsk(id, 'confirm', { title: 'Re-author as hive PR', message: preface + 'Have the hive re-author ' + refs + ' as ' + who + '?' + (caveat || ' Its head cannot merge as-is.') + ' The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. Nothing is merged as-is, and the author\'s commits stay attributed.', confirmLabel: 'Re-author', danger: true })) ? {} : null; - } case 'decide:adopt': { const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; @@ -23765,7 +24740,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-issue': 'Closing…', - 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:re-author': 'Queuing re-authoring…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; const STAGE_TRACKER_ACTION_WORDS = { @@ -23784,7 +24759,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } // The ledger name of a row action id (the inverse of the badge's // STAGE_TRACKER_ACTED_OPTION_ID), for a failure noted on the client. - const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; + const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; // A failed or refused action is noted on the row at once, so the // history badge turns red and its hover's first line names the reason // — the server's ledger only sees 5xx and refused answers, and a @@ -24056,7 +25031,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> n.classList.add('cue-acting'); if (capEl && capEl.parentNode !== host) { capEl.remove(); capEl = null; } if (host && !capEl) { capEl = document.createElement('span'); capEl.className = 'cue-acting-cap'; capEl.setAttribute('role', 'status'); const sp = document.createElement('span'); sp.className = 'toast-spinner cue-acting-spin'; capEl.appendChild(sp); capEl.appendChild(document.createTextNode('')); host.appendChild(capEl); } - if (capEl) capEl.lastChild.nodeValue = cap; + if (capEl) { capEl.lastChild.nodeValue = cap; capEl.title = cap; capEl.setAttribute('aria-label', cap); capEl.setAttribute('tabindex', '0'); } } else { n.classList.remove('cue-acting'); if (capEl) capEl.remove(); @@ -24130,8 +25105,9 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> return { toasts: [], pending: [] }; } if (id === 'decide:adopt') { - // Adopt acts on the nudged PR row itself (072, not a decision park). - items = items.filter(stageTrackerAdoptOffered); + // Adopt acts on the nudged PR row itself (072, not a decision park) + // or on the row whose decision card offers it. + items = items.filter(it => stageTrackerAdoptOffered(it) || stageTrackerServerOption(it, 'decide:adopt')); if (!items.length) return { toasts: [], pending: [] }; } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. @@ -36266,11 +37242,11 @@ <h4 style="margin:14px 0 6px">Approval and audit records</h4>${approval}`; return INFERENCE_MODELS[backend] || []; } } - function refreshBackendDiscovery(force) { - INFERENCE_BACKENDS.forEach(b => fetchInferenceModels(b, force)); + async function refreshBackendDiscovery(force) { + for (const backend of INFERENCE_BACKENDS) await fetchInferenceModels(backend, force); // Load configured gateway names so the backend/method pickers list them // (e.g. openrouter) alongside KNOWN_BACKENDS after the first paint. - fetchConfiguredGateways(); + await fetchConfiguredGateways(); } const CLI_MODEL_CACHE_TTL_MS = 30000; @@ -37871,9 +38847,8 @@ <h4 style="margin:14px 0 6px">Approval and audit records</h4>${approval}`; renderCost(cost); } catch (e) { /* transient — leave last render in place */ } } - fetchCost(); + dashboardScheduleWork('cost', fetchCost).catch(console.error); dashboardSetInterval('cost', fetchCost, COST_POLL_MS); - // ── v4: ACMM level-up recommendation (advisory) + lifecycle timeline ── // Both are additive, read-only panels polled on their own modest interval. // They fail quietly: a transient error leaves the last render in place and @@ -40872,7 +41847,13 @@ <h4 style="margin:14px 0 6px">Approval and audit records</h4>${approval}`; // Prime both panels and poll them on a modest independent interval. Do not // block initial paint: these run after the main poll is already wired. - function v4RefreshPanels() { fetchHiveAdvice(); fetchACMMReco(); fetchLifecycle(); fetchPRThroughput(); fetchApprovals(); } + function v4RefreshPanels() { + [['hive-advice', fetchHiveAdvice], ['acmm-reco', fetchACMMReco], + ['lifecycle', fetchLifecycle], ['pr-throughput', fetchPRThroughput], + ['approvals', fetchApprovals]].forEach(function([key, fn]) { + dashboardScheduleWork(key, fn).catch(console.error); + }); + } v4RefreshPanels(); searchPaneProbe(); dashboardSetInterval('v4-panels', v4RefreshPanels, V4_PANELS_POLL_MS); @@ -40914,7 +41895,7 @@ <h4 style="margin:14px 0 6px">Approval and audit records</h4>${approval}`; } } catch (_) { /* dashboard unreachable — different problem */ } } - checkGhAuth(); + dashboardScheduleWork('gh-auth-banner', checkGhAuth).catch(console.error); dashboardSetInterval('gh-auth-banner', checkGhAuth, GH_AUTH_POLL_MS); function renderGhRateLimits(ghRateLimits) { @@ -41026,7 +42007,6 @@ <h4 style="margin:14px 0 6px">Approval and audit records</h4>${approval}`; function setIfChanged(el, html) { if (el.innerHTML !== html) el.innerHTML = html; } - // ── Experiment Lab (Nous) rendering ────────────────────────────────────── let _nousCache = null; let _nousPollTimer = null; @@ -45418,6 +46398,14 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> return Math.floor(h / 24) + 'd'; } + function fixerQueueHint(e) { + var position = Number(e && e.fixer_queue_position); + if (!Number.isInteger(position) || position < 1) return ''; + var ahead = Number(e.fixer_queue_ahead); + if (!Number.isInteger(ahead) || ahead < 0) ahead = position - 1; + return 'fixer queued, ' + ahead + ' ahead'; + } + function renderReviewQueueEntry(e) { var meta = reviewQueuePriorityMeta(e.priority); var title = String(e.title || ''); @@ -45433,6 +46421,8 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> if (e.confidence_band) metaBits.push(esc(String(e.confidence_band))); metaBits.push(reviewQueueAgeLabel(e.age_hours) + ' old'); if (e.held) metaBits.push('held'); + var fixerHint = fixerQueueHint(e); + if (fixerHint) metaBits.push('<span class="hf-label hf-label-hold">' + esc(fixerHint) + '</span>'); // Hive-owned stage/author labels (#12429) tell at a glance where the // PR sits in the pipeline; other labels stay out of the meta line. // stage/stalled means "no activity by anyone but the hive for the @@ -46643,27 +47633,22 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> const n = Number(minSeq); if (Number.isFinite(n) && n > _statusSeqFloor) _statusSeqFloor = n; } + // A snapshot accepted before a mutation can become stale while queued. + function dashboardStatusCanRender(data) { + return data.statusSeq == null || + (data.statusSeq >= _statusSeqFloor && data.statusSeq >= _lastStatusSeq && + (!data.statusInstance || !_statusInstance || data.statusInstance === _statusInstance)); + } var SCROLL_SETTLE_DELAY_MS = 500; var _deferredLoadPromise = null; function _afterPaint(callback) { _hashScrollPending = true; - if (_deferredLoadPromise) { - _deferredLoadPromise.then(function() { - requestAnimationFrame(function() { - requestAnimationFrame(function() { - callback(); - setTimeout(function() { _hashScrollPending = false; }, 200); - }); - }); - }); - } else { + requestAnimationFrame(function() { requestAnimationFrame(function() { - requestAnimationFrame(function() { - setTimeout(callback, SCROLL_SETTLE_DELAY_MS); - setTimeout(function() { _hashScrollPending = false; }, 500); - }); + setTimeout(callback, SCROLL_SETTLE_DELAY_MS); + setTimeout(function() { _hashScrollPending = false; }, SCROLL_SETTLE_DELAY_MS); }); - } + }); } const NAVBAR_CLOCK_TICK_MS = 1000; @@ -46988,8 +47973,8 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> _lastStatusSeq = data.statusSeq; } if (typeof data.matrixEnabled === 'boolean') { - const matrixTab = document.getElementById('oc-matrix-tab'); - if (matrixTab) matrixTab.hidden = !data.matrixEnabled; + const codeActivityTab = document.getElementById('oc-matrix-tab'); + if (codeActivityTab) codeActivityTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); @@ -47008,7 +47993,9 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> applyDashboardFeatureVisibility(); // The tracker's hop cue reads which agent is on which item from this // payload; redraw the rows when that set changes (no extra fetch). - if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') renderStageTracker(); + if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') { + dashboardRenderSection('tracker-workers', ['activity-monitor-section'], () => renderStageTracker()); + } if (typeof refreshThroughputSLA === 'function') refreshThroughputSLA(); if (window._acmmOverride) { if (data.acmmLevel === window._acmmOverride.level) { @@ -47046,26 +48033,30 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> renderSystemAlerts(data.systemAlerts || []); if (!_dropdownOpen && !_configModalOpen) { applyPinOverrides(data.agents || []); - renderAgents(data.agents || []); - renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(data.agents || []); + }, data); + dashboardRenderSection('governor', ['governor'], () => { + if (!_dropdownOpen && !_configModalOpen) renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + }, data); // Keep the focused agent detail in sync with fresh payloads — its // fast path only rebuilds when the config fingerprint changes. if (_ocSelectedAgent) ocRenderAgentDetail(); } - renderTokens(data.tokens || {}); - renderAdvisoryDigest(data.advisoryDigest || null); - renderRepos(data.repos || []); - renderRuns(dashboardRunsFromStatus(data)); - renderSwarm(data.swarm || {}); + dashboardRenderSection('tokens', ['token-panel'], () => renderTokens(data.tokens || {}), data); + dashboardRenderSection('advisory', ['advisory-section'], () => renderAdvisoryDigest(data.advisoryDigest || null), data); + dashboardRenderSection('repos', ['repos-section', 'overview-section'], () => renderRepos(data.repos || []), data); + dashboardRenderSection('runs', ['runs-section'], () => renderRuns(dashboardRunsFromStatus(data)), data); + dashboardRenderSection('swarm', ['repos-section'], () => renderSwarm(data.swarm || {}), data); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); renderPlatform(data.platform || null); - renderHiveAdvice(data.hiveAdvice || null); - renderFleetReport(data.fleetReport || null); - renderSystemGauges(data.systemResources || null); + dashboardRenderSection('hive-advice', ['advisory-section'], () => renderHiveAdvice(data.hiveAdvice || null), data); + dashboardRenderSection('fleet-report', ['advisory-section'], () => renderFleetReport(data.fleetReport || null), data); + dashboardRenderSection('system-gauges', ['debug-section'], () => renderSystemGauges(data.systemResources || null), data); ocUpdateSidebarAgents(); - renderDebugSection(); - renderFAQ(); + dashboardRenderSection('debug', ['debug-section'], () => renderDebugSection(), data); + dashboardRenderSection('faq', ['faq-section'], () => renderFAQ(), data); initializeDashboardSectionCards(); // Restore persisted collapsed state for all collapsible sections const COLLAPSIBLE_SECTION_IDS = [ @@ -53799,7 +54790,7 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> if (_eventSource) { _eventSource.onerror = null; _eventSource.onmessage = null; _eventSource.close(); _eventSource = null; } const source = new EventSource('/api/events'); _eventSource = source; - if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); + if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; const conn = document.getElementById('conn'); @@ -53884,10 +54875,14 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> const lastData = window._lastStatus || {}; if (lastData.agents) { applyPinOverrides(lastData.agents); - renderAgents(lastData.agents); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(lastData.agents); + }); // Keep the cost table's "running agents" column live as agents // switch models or pause/resume between cost polls. - if (_lastCost) renderCost(_lastCost); + if (_lastCost) dashboardRenderSection('cost', ['cost-panel'], () => { + if (_lastCost) renderCost(_lastCost); + }); } ocUpdateFocusedState(); const _lvl = (lastData.acmmLevel != null) ? lastData.acmmLevel : 0; @@ -55186,7 +56181,7 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> // agent's kick history over the selected time window. if (tabId === AGENT_PROMPTS_TAB) initAgentPromptHistory(); } else { - body.innerHTML = renderGovernorTab(tabId); + body.innerHTML = renderGateRegressionBanner() + renderGovernorTab(tabId); settingsAnnotateRows(body); if (tabId === 'Hub') { fetchQueueCount(); fetchAutoUpdateStatus(); } // The escalation breaker lives at the top level of hive.yaml, so the @@ -55226,6 +56221,18 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> if (typeof syncRepoSaveGuard === 'function') syncRepoSaveGuard(); } + // Safety-gate regression banner (#16438): /api/status config.gate_regressions + // lists the gates (review.require_labels, project.paused_repos, …) a + // previous runtime overlay carried that this boot's config dropped or + // loosened. Shown at the top of every Settings tab until the operator + // restores the gate (or removes it on purpose) and the hive restarts. + function renderGateRegressionBanner() { + const regs = ((window._lastStatus || {}).config || {}).gate_regressions || []; + if (!regs.length) return ''; + const items = regs.map(g => `<li><code>${esc(g.gate || '')}</code> was <code>${esc(g.previous || '')}</code>, now ${esc(g.effective || '')}${g.source ? ` <span class="text-muted">(from ${esc(g.source)})</span>` : ''}</li>`).join(''); + return `<div class="cmp-banner" id="gate-regression-banner" role="alert"><strong>Safety gate dropped at boot.</strong> This hive booted without ${regs.length === 1 ? 'a gate' : regs.length + ' gates'} its previous runtime config enforced; agents may now act on items it used to leave alone. Restore the setting here and save, or set <code>config.refuse_gate_regression: true</code> to make this fatal.<ul class="cmp-banner-detail">${items}</ul></div>`; + } + function renderAgentImport() { var exampleURL = 'https://github.com/hivecommons/hive/blob/HEAD/src/examples/agents/customized-agent.yaml'; var rawURL = 'https://raw.githubusercontent.com/hivecommons/hive/HEAD/src/examples/agents/customized-agent.yaml'; @@ -62341,7 +63348,7 @@ <h4 class="rt-h4">Clanker-requested PRs</h4> } return _statSources; } - ensureStatSources(); + dashboardScheduleWork('stat-sources', ensureStatSources).catch(console.error); /* statSourcesForDialog returns the source catalogue for the agent the config dialog is showing. The agent config response carries a catalogue @@ -62553,7 +63560,6 @@ <h4 style="margin:18px 0 8px">Agent Watchdog</h4> <span style="opacity:0.8">— fixed progression; the last step is the cap.</span> </div>`; } - // ── Watchdog activity strip (#7254) ────────────────────────────────────── // "Review the watchdog-*-observed entries in the Audit Log, then switch to // Heal" is only a data-driven decision if the data is on the page. The @@ -64684,6 +65690,14 @@ <h3 class="features-section-title">${esc(s.title)}</h3> <label>Fixer agent ${yamlHint('review.fixer_agent')} ${settingHelpMark('review-swarm', 'configuration', 'Fixer agent', `The agent kicked to address reviewer findings before re-review. Use the agent ID (the key in the roster, not its display name). Blank falls back to the PR's authoring agent, then scanner.`)}</label> <input type="text" value="${esc(rv.fixer_agent || '')}" placeholder="scanner (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"> </div> + <div class="config-field mt-3"> + <label>Fallback fixer agents (comma-separated) ${yamlHint('review.fixer_fallback_agents[]')} ${settingHelpMark('review-swarm', 'configuration', 'Fallback fixer agents', `Ordered agent IDs to try when the primary fixer cannot accept kicks. The first available fallback receives the repair without interrupting another turn. An empty list disables fallback routing.`)}</label> + <input type="text" value="${esc((rv.fixer_fallback_agents || []).join(', '))}" placeholder="e.g. fixer, scanner-2" spellcheck="false" data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"> + </div> + <div class="config-field mt-3"> + <label>Undeliverable kicks before fallback ${yamlHint('review.fixer_fallback_after_undeliverable')} ${settingHelpMark('review-swarm', 'configuration', 'Undeliverable kicks before fallback', `Consecutive undeliverable kicks before trying a fallback. 0 uses the default of 3. After at least one refusal, a fixer whose transcript exceeds its busy_no_activity_threshold can yield earlier. Requires a non-empty fallback agent list.`)}</label> + <input type="number" min="0" step="1" value="${esc(String(rv.fixer_fallback_after_undeliverable || ''))}" placeholder="3 (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"> + </div> <div class="config-field" style="margin-top:10px"> <label>Human decision label ${yamlHint('review.human_decision_label')} ${settingHelpMark('review-swarm', 'configuration', 'Human decision label', `An EXISTING repo label applied when the review swarm holds a PR for a human, so those PRs can be filtered from the list. There is no fleet-wide default and no standard name — use whatever the governed repos already maintain (this fleet's bluefin spoke uses 3-human-queue). The label is never created: if it is blank, misspelled, or absent from a repo, labeling is skipped there and the review comment's in-body marker still carries the signal.`)}</label> <input type="text" value="${esc(rv.human_decision_label || '')}" placeholder="(none) — must already exist in the repo" data-change-action="markDirty" data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"> @@ -67282,6 +68296,10 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 markDirty('review', 'require_labels', parseReviewRequireLabels(text)); } + function markDirtyReviewFixerFallbackAgents(text) { + markDirty('review', 'fixer_fallback_agents', String(text || '').split(',').map(s => s.trim()).filter(Boolean)); + } + // Reviewer agents pick-list (Settings → Features → Review Gate → // Reviewers, #13460). The checked rows become review.reviewer_agents; an // empty selection means "keyword scan", mirroring the server. @@ -69669,8 +70687,8 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 chatInput.value = localStorage.getItem(CHAT_DRAFT_KEY) || ''; renderChatCheatsheet(); renderChatSuggestions(); - detectChatCapabilities(); - refreshChatPresence(); + dashboardScheduleWork('chat-capabilities', detectChatCapabilities).catch(console.error); + dashboardScheduleWork('chat-presence', refreshChatPresence).catch(console.error); dashboardSetInterval('chat-presence', refreshChatPresence, 30000); chatFab.onclick = () => { @@ -71876,11 +72894,10 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 updateWelcomeProgress(); } - checkGHAuth(); + dashboardScheduleWork('welcome-gh-auth', checkGHAuth).catch(console.error); dashboardSetInterval('welcome-gh-auth', checkGHAuth, GH_AUTH_CHECK_INTERVAL_MS); initWelcomeDialog(); initNPSSurvey(); - // ── One-shot attention shimmy ────────────────────────────────────── // Draw the eye, once per page load, to two interactive affordances users // often miss: the ACMM level badge and the topbar Guide (Getting Started @@ -71912,7 +72929,7 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 } triggerAttentionShimmy(); - checkClaudeAuth(); + dashboardScheduleWork('welcome-claude-auth', checkClaudeAuth).catch(console.error); var CLAUDE_AUTH_CHECK_INTERVAL_MS = 60000; dashboardSetInterval('welcome-claude-auth', checkClaudeAuth, CLAUDE_AUTH_CHECK_INTERVAL_MS); @@ -71970,59 +72987,38 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 sendPresencePing(); })(); - // Deferred initialization — non-critical fetches staggered after first paint. - // Each entry returns a promise so anchor scrolling can wait for layout to settle. - const DEFERRED_INIT_DELAY_MS = 1500; - const DEFERRED_STAGGER_MS = 200; + // Visible sections win; slow background panels cannot delay navigation. + const DEFERRED_INIT_DELAY_MS = DASHBOARD_BACKGROUND_DELAY_MS; _deferredLoadPromise = new Promise(function(resolveAll) { setTimeout(() => { const deferred = [ - () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig()), - () => fetchFactHistory(), - () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); }), - () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); }), - () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(() => {}), - () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); }), - () => ensureNousPolling(), - () => fetchPublicKnowledgeSetting(), - () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); }), - () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); }), - () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }), - () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); }), - () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); }), - () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); }), - () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); }), - () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); }), - () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); }), - () => Promise.resolve(startVersionCheck()), - () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}).then(() => { dashboardSetInterval('weekly-trends', () => { fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}); }, TREND_REFRESH_MS); }), - () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); }), - () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); }), + ['backend-discovery', () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig())], + ['fact-history', () => fetchFactHistory()], + ['overview-kpi-history', () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); })], + ['history', () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); })], + ['budget-ignore', () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(console.error)], + ['budget-history', () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); })], + ['nous-status', () => ensureNousPolling()], + ['public-knowledge', () => fetchPublicKnowledgeSetting()], + ['knowledge-stats', () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); })], + ['audit-log', () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); })], + ['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })], + ['review-pipeline', () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); })], + ['stage-tracker', () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); })], + ['contributors', () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); })], + ['leaderboard', () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); })], + ['git-version', () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); })], + ['acmm-evaluation', () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); })], + ['version-check', () => Promise.resolve(startVersionCheck())], + ['weekly-trends', () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error).then(() => { dashboardSetInterval('weekly-trends', () => { return fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error); }, TREND_REFRESH_MS); })], + ['timeline', () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); })], + ['agent-logs', () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); })], ]; - // `Promise.resolve().then(fn)` rather than `fn()`, so ONE bad entry - // cannot strand the whole chain (#6581). `fn()` was called bare inside - // the setTimeout callback, so an entry that threw synchronously — or - // returned undefined and had `.then` called on it, which is what - // fetchTimeline did — threw out of the callback with nothing to catch - // it. That entry's promise then never settled, so Promise.all never - // settled, so resolveAll never ran and _deferredLoadPromise stayed - // pending for the life of the page. _afterPaint awaits it, so first- - // load view restoration (making #oc-agent-detail active, navigating to - // a saved section) silently never happened. - // - // Wrapping turns a synchronous throw into a rejection, which - // `.then(resolve, resolve)` already handles: the entry is recorded as - // finished-badly instead of never finishing, and the other twelve - // entries still complete. The throw is still reported below rather - // than swallowed — the point is that one broken entry degrades to one - // broken feature, not to a dashboard that never finishes initialising. - const allDone = deferred.map((fn, i) => - new Promise(resolve => setTimeout(() => { - Promise.resolve().then(fn).then(resolve, err => { - console.error('deferred init entry ' + i + ' failed', err); - resolve(); - }); - }, i * DEFERRED_STAGGER_MS)) + // A synchronous throw must not strand the other panels (#6581). + const allDone = deferred.map(([key, fn]) => + dashboardScheduleWork(key, () => Promise.resolve().then(fn)).catch(err => { + console.error('deferred init ' + key + ' failed', err); + }) ); Promise.all(allDone).then(resolveAll); }, DEFERRED_INIT_DELAY_MS); @@ -72236,7 +73232,6 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 gh84: function (event, A) { markSentinelDirty('exemptLogins', parseSecurityList(this.value)); }, gh85: function (event, A) { markSentinelDirty('repos', parseSecurityList(this.value)); }, }; - </script> </body> </html> diff --git a/src/pkg/dashboard/webhook_tracker_refresh.go b/src/pkg/dashboard/webhook_tracker_refresh.go index f8dcced9df..c7a6e4db62 100644 --- a/src/pkg/dashboard/webhook_tracker_refresh.go +++ b/src/pkg/dashboard/webhook_tracker_refresh.go @@ -252,6 +252,13 @@ func (s *Server) scheduleWebhookTrackerRefresh(res github.WebhookEventResult, de if !s.webhookTrackerRefreshEnabled() { return 0 } + if res.CIEvidence != nil && res.CIEvidence.Applied > 0 { + // The payload itself moved the row's CI evidence + // (hivecommons/hive#16521); the PR object did not change, so the + // re-read would only spend a request to confirm labels and title. + s.invalidateStageTrackerForWebhook() + return 0 + } keys := webhookTrackerKeys(res) if len(keys) == 0 { return 0 @@ -261,6 +268,17 @@ func (s *Server) scheduleWebhookTrackerRefresh(res github.WebhookEventResult, de return len(keys) } +// RefreshCIEvidence is the github.CIEvidenceHook: a check delivery or a +// coalesced check-run re-read changed the CI evidence for repo's head, so +// the tracker payload is dropped and the page nudged over SSE; the next GET +// re-derives the row's counts from the merged evidence. +func (s *Server) RefreshCIEvidence(repo, head string) { + if s == nil { + return + } + s.invalidateStageTrackerForWebhook() +} + // selfEditDeliveryID tags the re-reads the hive's own GitHub edits ask for, // in place of a webhook delivery id, in ItemPatches and the logs. const selfEditDeliveryID = "self:edit" @@ -804,6 +822,9 @@ func patchWorkPRAny(raw any, snap github.WebhookItemSnapshot) (any, bool) { w.Title = snap.Title w.Labels = append([]string(nil), snap.Labels...) w.Draft = snap.Draft + if snap.HeadSHA != "" { + w.HeadSHA = snap.HeadSHA + } if !snap.UpdatedAt.IsZero() { w.UpdatedAt = snap.UpdatedAt } diff --git a/src/pkg/dashboard/webstatic/dashboard_script.go b/src/pkg/dashboard/webstatic/dashboard_script.go new file mode 100644 index 0000000000..80984d2c01 --- /dev/null +++ b/src/pkg/dashboard/webstatic/dashboard_script.go @@ -0,0 +1,165 @@ +package webstatic + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "net/http" + "strconv" + "sync" +) + +const ( + dashboardMainScriptMarker = "<script>\n // Wrap fetch to inject auth token for mutation requests (PUT/POST/PATCH/DELETE)" + dashboardScriptCache = "private, max-age=31536000, immutable" +) + +// This trusted inline listener is hashed with the served shell by the CSP +// layer. It must precede the external script and work without application code, +// including when a request reaches a replica with a different asset hash. +const dashboardScriptBootstrap = `<script> +(function () { + var scriptID = 'hive-dashboard-main-script'; + function isMain(event) { return event.target && event.target.id === scriptID; } + function stopListening() { + window.removeEventListener('error', onError, true); + window.removeEventListener('load', onLoad, true); + } + function onLoad(event) { if (isMain(event)) stopListening(); } + function onError(event) { + var script = document.getElementById(scriptID); + if (!isMain(event) && !(script && event.filename === script.src)) return; + stopListening(); + var root = document.getElementById('hive-dashboard-root'); + if (root) { root.hidden = true; root.setAttribute('inert', ''); } + var dialog = document.createElement('dialog'); + dialog.id = 'hive-dashboard-load-error'; + dialog.setAttribute('role', 'alertdialog'); + dialog.setAttribute('aria-labelledby', 'hive-dashboard-load-error-title'); + dialog.setAttribute('aria-describedby', 'hive-dashboard-load-error-detail'); + var title = document.createElement('h2'); + title.id = 'hive-dashboard-load-error-title'; + title.textContent = 'Dashboard could not finish loading'; + var detail = document.createElement('p'); + detail.id = 'hive-dashboard-load-error-detail'; + detail.textContent = 'The application script could not be loaded. A dashboard update or connection problem may have interrupted loading. Reload to try again. If this keeps happening, contact your hive operator.'; + var reload = document.createElement('button'); + reload.type = 'button'; + reload.textContent = 'Reload dashboard'; + reload.addEventListener('click', function () { window.location.reload(); }); + dialog.addEventListener('cancel', function (event) { event.preventDefault(); }); + dialog.appendChild(title); + dialog.appendChild(detail); + dialog.appendChild(reload); + document.body.appendChild(dialog); + if (typeof dialog.showModal === 'function') dialog.showModal(); + else dialog.setAttribute('open', ''); + reload.focus(); + } + window.addEventListener('error', onError, true); + window.addEventListener('load', onLoad, true); +})(); +</script>` + +// DashboardScript is the exact main classic script from the final branded +// document. Its full SHA-256 URL changes with its bytes, including branding. +// Register it behind the same authentication middleware as the index document. +type DashboardScript struct { + path string + integrity string + document *IndexDocument + gzipOnce sync.Once + gzipETag string +} + +// ExternalizeDashboardScript replaces only the known main script with a +// same-origin deferred classic script. Keeping one script (not a module or +// wrapper) preserves its global lexical declarations and function bindings. +// The canonical generated index remains untouched for source-string consumers. +// Unexpected markup retains the original, working inline document and its CSP. +func ExternalizeDashboardScript(raw []byte) ([]byte, *DashboardScript) { + marker := []byte(dashboardMainScriptMarker) + if bytes.Count(raw, marker) != 1 { + return raw, nil + } + start := bytes.Index(raw, marker) + bodyStart := start + len("<script>") + closeOffset := bytes.Index(raw[bodyStart:], []byte("</script>")) + if closeOffset < 0 { + return raw, nil + } + bodyEnd := bodyStart + closeOffset + end := bodyEnd + len("</script>") + // Deferring a script ahead of a later inline script would reverse their + // execution order. Only split the final script element in the document. + if bytes.Contains(bytes.ToLower(raw[end:]), []byte("<script")) { + return raw, nil + } + body := raw[bodyStart:bodyEnd] + sum := sha256.Sum256(body) + asset := &DashboardScript{ + path: "/assets/dashboard-main." + hex.EncodeToString(sum[:]) + ".js", + integrity: "sha256-" + base64.StdEncoding.EncodeToString(sum[:]), + document: NewIndexDocument(body), + } + tag := []byte(dashboardScriptBootstrap + asset.scriptTag()) + shell := make([]byte, 0, len(raw)-(end-start)+len(tag)) + shell = append(shell, raw[:start]...) + shell = append(shell, tag...) + shell = append(shell, raw[end:]...) + return shell, asset +} + +// Path is the only URL this handler serves; it never opens filesystem paths. +func (s *DashboardScript) Path() string { return s.path } + +func (s *DashboardScript) scriptTag() string { + return `<script id="hive-dashboard-main-script" defer src="` + s.Path() + `" integrity="` + s.integrity + `"></script>` +} + +// Precompress prepares both the compressed bytes and their strong validator. +func (s *DashboardScript) Precompress() { + s.gzipOnce.Do(func() { + if body := s.document.compressedBody(); body != nil { + s.gzipETag = ETagFor(body) + } + }) +} + +func (s *DashboardScript) ServeHTTP(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + if r.URL.Path != s.path { + h.Set("Cache-Control", "no-cache") + http.NotFound(w, r) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + h.Set("Cache-Control", "no-cache") + h.Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + h.Set("Content-Type", "text/javascript; charset=utf-8") + h.Set("Cache-Control", dashboardScriptCache) + h.Add("Vary", "Accept-Encoding") + body, etag := s.document.raw, s.document.etag + if acceptsGzip(r.Header.Get("Accept-Encoding")) { + s.Precompress() + if s.document.gzipped != nil { + body, etag = s.document.gzipped, s.gzipETag + h.Set("Content-Encoding", "gzip") + } + } + h.Set("ETag", etag) + if ifNoneMatchHits(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return + } + h.Set("Content-Length", strconv.Itoa(len(body))) + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodHead { + _, _ = w.Write(body) + } +} diff --git a/src/pkg/dashboard/webstatic/dashboard_script_test.go b/src/pkg/dashboard/webstatic/dashboard_script_test.go new file mode 100644 index 0000000000..c4a873902e --- /dev/null +++ b/src/pkg/dashboard/webstatic/dashboard_script_test.go @@ -0,0 +1,428 @@ +package webstatic + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strconv" + "strings" + "testing" +) + +func dashboardScriptFixture() []byte { + return []byte("<html><head></head><body><script>window.boot = true;</script><main>Loading</main>\n " + + dashboardMainScriptMarker + "\n const lexical = '🐝';\n function action() { return lexical; }\n </script>\n</body></html>") +} + +func requireDashboardScript(t *testing.T, raw []byte) ([]byte, *DashboardScript) { + t.Helper() + shell, asset := ExternalizeDashboardScript(raw) + if asset == nil { + t.Fatal("main script was not externalized") + } + return shell, asset +} + +func TestExternalizeDashboardScriptPreservesBytesAndOrder(t *testing.T) { + raw := InjectBranding(dashboardScriptFixture()) + shell, asset := requireDashboardScript(t, raw) + originalScripts := ExtractInlineScripts(raw) + retainedScripts := ExtractInlineScripts(shell) + if len(originalScripts) != 2 || len(retainedScripts) != 2 { + t.Fatalf("script counts before=%d after=%d, want original boot and recovery bootstrap", len(originalScripts), len(retainedScripts)) + } + if !bytes.Equal(retainedScripts[0], originalScripts[0]) { + t.Fatal("inline boot script changed") + } + if !bytes.Equal(asset.document.raw, originalScripts[1]) { + t.Fatal("main script text, whitespace, lexical bindings or Unicode changed") + } + sum := sha256.Sum256(originalScripts[1]) + if want := "/assets/dashboard-main." + hex.EncodeToString(sum[:]) + ".js"; asset.Path() != want { + t.Fatalf("asset URL = %q, want full content address %q", asset.Path(), want) + } + tag := []byte(`<script id="hive-dashboard-main-script" defer src="` + asset.Path() + + `" integrity="sha256-` + base64.StdEncoding.EncodeToString(sum[:]) + `"></script>`) + replacement := append([]byte(dashboardScriptBootstrap), tag...) + recovered := bytes.Replace(shell, replacement, append(append([]byte("<script>"), asset.document.raw...), []byte("</script>")...), 1) + if !bytes.Equal(recovered, raw) { + t.Fatal("replacing external tag with recovered script did not reproduce exact original HTML") + } + if !bytes.Contains(shell, []byte(BrandingLinkTag)) || bytes.Index(shell, retainedScripts[0]) > bytes.Index(shell, tag) { + t.Fatal("branding or inline boot order was lost") + } + _, same := requireDashboardScript(t, raw) + if same.Path() != asset.Path() { + t.Fatal("identical script bytes produced a different content address") + } + changed := bytes.Replace(raw, []byte("'🐝'"), []byte("'branded bee'"), 1) + _, branded := requireDashboardScript(t, changed) + if branded.Path() == asset.Path() || !bytes.Contains(branded.document.raw, []byte("'branded bee'")) { + t.Fatal("final branded script bytes were not used for content addressing") + } + if bytes.Contains(shell, []byte("type=\"module\"")) || bytes.Contains(shell, []byte("async")) { + t.Fatal("main script must remain an ordered deferred classic script") + } + policy := ScriptSrcElemSources(shell) + if !strings.HasPrefix(policy, "'self' ") || !strings.Contains(policy, CSPScriptHash(retainedScripts[0])) { + t.Fatal("shell CSP must authorize same-origin asset and exact inline boot") + } + if !strings.Contains(policy, CSPScriptHash(retainedScripts[1])) || + bytes.Index(shell, retainedScripts[1]) > bytes.Index(shell, tag) { + t.Fatal("trusted recovery bootstrap must be CSP-authorized before the main script") + } + if strings.Contains(policy, CSPScriptHash(originalScripts[1])) || strings.Contains(policy, "unsafe-inline") { + t.Fatal("shell CSP should not need main-script hash or inline weakening") + } +} + +func TestExternalizeDashboardScriptUnexpectedMarkupIsUnchanged(t *testing.T) { + for name, raw := range map[string][]byte{ + "empty": nil, + "missing": []byte("<body><script>other()</script></body>"), + "unclosed": []byte("<body>" + dashboardMainScriptMarker + "\nmain()"), + "ambiguous": append(dashboardScriptFixture(), dashboardScriptFixture()...), + "later inline": append(dashboardScriptFixture(), []byte("<script>action()</script>")...), + "later external": append(dashboardScriptFixture(), + []byte(`<SCRIPT src="/after.js"></SCRIPT>`)...), + "changed tag": bytes.Replace(dashboardScriptFixture(), []byte(dashboardMainScriptMarker), + []byte(strings.Replace(dashboardMainScriptMarker, "<script>", `<script type="module">`, 1)), 1), + } { + t.Run(name, func(t *testing.T) { + got, asset := ExternalizeDashboardScript(raw) + if asset != nil || !bytes.Equal(got, raw) { + t.Fatal("unexpected markup must retain the original inline document with no asset") + } + }) + } +} + +func TestDashboardScriptRealIndexShellBudget(t *testing.T) { + raw, err := os.ReadFile("../static/index.html") + if err != nil { + t.Fatal(err) + } + shell, asset := requireDashboardScript(t, InjectBranding(raw)) + const maxShellBytes = 1024 * 1024 + const maxShellPercent = 25 + if len(shell) > maxShellBytes || len(shell)*100 > len(raw)*maxShellPercent { + t.Fatalf("initial HTML = %d bytes from %d-byte canonical index; want <= %d bytes and <= %d%%", + len(shell), len(raw), maxShellBytes, maxShellPercent) + } + scripts := ExtractInlineScripts(InjectBranding(raw)) + if len(scripts) != 2 || !bytes.Equal(asset.document.raw, scripts[1]) { + t.Fatal("real main script bytes or script boundary changed") + } + retained := ExtractInlineScripts(shell) + if len(retained) != 2 || !bytes.Equal(retained[0], scripts[0]) { + t.Fatal("real inline boot script changed") + } + for _, global := range []string{ + "window.HIVE_READER", "window.HIVE_KIOSK", "window.HIVE_POPOUT", + "window.HIVE_DISPLAY", "window.hiveURLWithHash", "window.hiveKioskCTAOn", + } { + if !bytes.Contains(retained[0], []byte(global)) || + bytes.Index(shell, []byte(global)) > bytes.Index(shell, []byte(asset.scriptTag())) { + t.Fatalf("ordinary early boot global %q must remain inline before application script", global) + } + } + // Revalidate the actual small shell, not the canonical monolith. + index := NewIndexDocument(shell) + rec := httptest.NewRecorder() + rec.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; script-src-elem 'self'; script-src-attr 'none'") + ApplyDocumentScriptSrcElem(rec, shell) + index.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + if !bytes.Equal(rec.Body.Bytes(), shell) || rec.Header().Get("Cache-Control") != "no-cache" { + t.Fatal("served shell must retain index revalidation semantics") + } + policy := rec.Header().Get("Content-Security-Policy") + for _, script := range retained { + if !strings.Contains(policy, CSPScriptHash(script)) { + t.Fatal("served shell CSP must authorize boot and failure listener exactly") + } + } + if !strings.Contains(policy, "script-src-elem 'self' ") || + !strings.Contains(policy, "script-src-attr 'none'") || strings.Contains(policy, "unsafe-inline") { + t.Fatal("external script source or event-handler CSP boundary changed") + } + req := httptest.NewRequest(http.MethodHead, "/index.html", nil) + req.Header.Set("If-None-Match", rec.Header().Get("ETag")) + rec = httptest.NewRecorder() + index.ServeHTTP(rec, req) + if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 { + t.Fatal("shell conditional HEAD must return an empty 304") + } +} + +func TestDashboardScriptHTTPRepresentations(t *testing.T) { + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + var identityETag string + for _, encoding := range []string{"", "gzip", "gzip;q=0"} { + t.Run("encoding="+encoding, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, asset.Path(), nil) + req.Header.Set("Accept-Encoding", encoding) + rec := httptest.NewRecorder() + rec.Header().Set("Vary", "Cookie") + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + for key, want := range map[string]string{ + "Content-Type": "text/javascript; charset=utf-8", + "X-Content-Type-Options": "nosniff", + "Cache-Control": dashboardScriptCache, + "Content-Length": strconv.Itoa(rec.Body.Len()), + "ETag": ETagFor(rec.Body.Bytes()), + } { + if got := rec.Header().Get(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } + if got := strings.Join(rec.Header().Values("Vary"), ", "); got != "Cookie, Accept-Encoding" { + t.Fatalf("Vary = %q, want existing Cookie plus Accept-Encoding", got) + } + body := rec.Body.Bytes() + if encoding == "gzip" { + if rec.Header().Get("Content-Encoding") != "gzip" { + t.Fatal("gzip response not labeled") + } + zr, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + body, err = io.ReadAll(zr) + _ = zr.Close() + if err != nil { + t.Fatal(err) + } + if rec.Header().Get("ETag") == identityETag { + t.Fatal("gzip and identity must have distinct strong validators") + } + } else { + identityETag = rec.Header().Get("ETag") + if rec.Header().Get("Content-Encoding") != "" { + t.Fatal("identity representation labeled as compressed") + } + } + if !bytes.Equal(body, asset.document.raw) { + t.Fatal("served main script bytes changed") + } + for _, method := range []string{http.MethodGet, http.MethodHead} { + head := httptest.NewRequest(method, asset.Path(), nil) + head.Header.Set("Accept-Encoding", encoding) + if method == http.MethodHead { + out := httptest.NewRecorder() + asset.ServeHTTP(out, head) + if out.Code != http.StatusOK || out.Body.Len() != 0 || + out.Header().Get("Content-Length") != rec.Header().Get("Content-Length") { + t.Fatal("HEAD must advertise GET length with no body") + } + } + for _, validator := range []string{ + rec.Header().Get("ETag"), "W/" + rec.Header().Get("ETag"), + `"stale", ` + rec.Header().Get("ETag"), "*", + } { + head.Header.Set("If-None-Match", validator) + out := httptest.NewRecorder() + asset.ServeHTTP(out, head) + if out.Code != http.StatusNotModified || out.Body.Len() != 0 || + out.Header().Get("Cache-Control") != dashboardScriptCache || + out.Header().Get("ETag") != rec.Header().Get("ETag") || + out.Header().Get("Vary") != "Accept-Encoding" || + out.Header().Get("Content-Length") != "" { + t.Fatalf("%s conditional response lost cache metadata or carried body: %+v", method, out) + } + } + } + miss := httptest.NewRequest(http.MethodGet, asset.Path(), nil) + miss.Header.Set("Accept-Encoding", encoding) + miss.Header.Set("If-None-Match", `"stale"`) + out := httptest.NewRecorder() + asset.ServeHTTP(out, miss) + if out.Code != http.StatusOK || out.Body.Len() == 0 { + t.Fatal("stale validator must receive the selected full representation") + } + }) + } +} + +func TestDashboardScriptOnlyServesItsExactPath(t *testing.T) { + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + for _, path := range []string{"/", "/index.html", "/assets/", asset.Path() + "/extra", "/assets/../server.go"} { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound || rec.Header().Get("ETag") != "" || + strings.Contains(rec.Header().Get("Cache-Control"), "immutable") { + t.Fatalf("path %q served or cached an asset: %+v", path, rec) + } + } + + req := httptest.NewRequest(http.MethodPost, asset.Path(), nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "GET, HEAD" { + t.Fatal("asset must reject writes before evaluating validators") + } +} + +func TestDashboardScriptLiteralAssetRoute(t *testing.T) { + const pattern = "GET /assets/{script}" + server, err := os.ReadFile("../server.go") + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(server, []byte("s.mux.Handle("+strconv.Quote(pattern)+", mainScript)")) { + t.Fatal("production asset route must remain a literal pattern discoverable by the API parity guard") + } + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + mux := http.NewServeMux() + mux.Handle(pattern, asset) + mux.HandleFunc("GET /", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusTeapot) + }) + for _, method := range []string{http.MethodGet, http.MethodHead} { + req := httptest.NewRequest(method, asset.Path(), nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || rec.Header().Get("ETag") == "" { + t.Fatalf("%s current asset: status=%d, headers=%v", method, rec.Code, rec.Header()) + } + if method == http.MethodHead && rec.Body.Len() != 0 { + t.Fatal("HEAD through the literal route must not carry a body") + } + req.Header.Set("If-None-Match", rec.Header().Get("ETag")) + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 { + t.Fatalf("%s current asset revalidation: status=%d, body=%d bytes", method, rec.Code, rec.Body.Len()) + } + } + for _, path := range []string{ + "/assets/dashboard-main." + strings.Repeat("0", hex.EncodedLen(sha256.Size)) + ".js", + asset.Path() + ".extra", "/assets/server.go", + } { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound || rec.Header().Get("ETag") != "" || + strings.Contains(rec.Header().Get("Cache-Control"), "immutable") { + t.Fatalf("nonmatching asset path %q must be rejected before validators: status=%d, headers=%v", + path, rec.Code, rec.Header()) + } + } + for _, path := range []string{"/", "/index.html", "/tokens.css", "/assets/nested/file.js"} { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + if rec.Code != http.StatusTeapot { + t.Fatalf("path %q escaped its existing fallback route: status=%d", path, rec.Code) + } + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, asset.Path(), nil)) + if rec.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST asset: status=%d, want 405", rec.Code) + } +} + +func TestDashboardScriptFailureBootstrap(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node is required for the bootstrap behavior regression") + } + scripts := ExtractInlineScripts([]byte(dashboardScriptBootstrap)) + if len(scripts) != 1 { + t.Fatal("expected exactly one trusted recovery bootstrap") + } + const harness = ` + const assert = require('node:assert/strict'); + const vm = require('node:vm'); + const source = require('node:fs').readFileSync(0, 'utf8'); + function realm(nativeDialog = true) { + const handlers = {}; + const appended = []; + let reloads = 0; + function element(tag) { + const el = {tag, attrs: {}, events: {}, children: [], + setAttribute(name, value) { this.attrs[name] = value; }, + appendChild(child) { this.children.push(child); }, + addEventListener(type, fn) { this.events[type] = fn; }, + focus() { this.focused = true; } + }; + if (nativeDialog) el.showModal = function() { this.modal = true; }; + return el; + } + const root = element('main'); + const main = {id: 'hive-dashboard-main-script', src: 'https://hive.example/assets/dashboard-main.hash.js'}; + const window = { + location: {reload() { reloads++; }}, + addEventListener(type, fn, capture) { assert.equal(capture, true); handlers[type] = fn; }, + removeEventListener(type, fn, capture) { + assert.equal(capture, true); + assert.equal(handlers[type], fn); + delete handlers[type]; + } + }; + const document = { + getElementById(id) { return id === main.id ? main : id === 'hive-dashboard-root' ? root : null; }, + createElement: element, + body: {appendChild(el) { appended.push(el); }} + }; + vm.runInNewContext(source, {window, document}); + return {handlers, appended, root, main, reloads: () => reloads}; + } + for (const mode of ['resource', 'runtime', 'no-native-dialog']) { + const r = realm(mode !== 'no-native-dialog'); + r.handlers.error({target: {id: 'unrelated-image'}}); + r.handlers.error({target: {}, filename: 'https://hive.example/unrelated.js'}); + assert.equal(r.appended.length, 0, 'unrelated failures must not hide a working dashboard'); + r.handlers.error(mode === 'runtime' ? {target: {}, filename: r.main.src} : {target: r.main}); + assert.equal(r.root.hidden, true, 'inert shell must no longer appear usable'); + assert.ok('inert' in r.root.attrs); + assert.equal(r.appended.length, 1); + assert.deepEqual(Object.keys(r.handlers), [], 'failure listeners must be removed after handling'); + const dialog = r.appended[0]; + assert.equal(dialog.tag, 'dialog'); + assert.equal(dialog.attrs.role, 'alertdialog'); + assert.equal(dialog.id, 'hive-dashboard-load-error'); + assert.equal(dialog.attrs['aria-labelledby'], dialog.children[0].id); + assert.equal(dialog.attrs['aria-describedby'], dialog.children[1].id); + assert.match(dialog.children[0].textContent, /could not finish loading/); + assert.match(dialog.children[1].textContent, /update or connection problem/); + assert.match(dialog.children[1].textContent, /contact your hive operator/); + const button = dialog.children[2]; + assert.equal(button.textContent, 'Reload dashboard'); + assert.equal(button.focused, true); + if (mode === 'no-native-dialog') assert.ok('open' in dialog.attrs); + else assert.equal(dialog.modal, true); + let prevented = false; + dialog.events.cancel({preventDefault() { prevented = true; }}); + assert.equal(prevented, true, 'Escape must not reveal a broken dashboard'); + assert.equal(r.reloads(), 0, 'no automatic reload loop'); + button.events.click(); + assert.equal(r.reloads(), 1); + } + const good = realm(); + good.handlers.load({target: {id: 'unrelated-image'}}); + assert.equal(typeof good.handlers.error, 'function'); + good.handlers.load({target: good.main}); + assert.deepEqual(Object.keys(good.handlers), []); + assert.equal(good.root.hidden, undefined); + assert.equal(good.appended.length, 0, 'successful load must not display an error'); + ` + cmd := exec.Command(node, "-e", harness) + cmd.Stdin = bytes.NewReader(scripts[0]) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("bootstrap behavior regression failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json b/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json new file mode 100644 index 0000000000..7baccd3f47 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json @@ -0,0 +1,83 @@ +{ + "source": "Screenshot 2026-11-03 at 12.01.36 PM.png", + "clock": "2026-11-03T17:01:36Z", + "provenance": "Screenshot-shaped acceptance data, not a live backend snapshot. Titles/authors/heads were read from GitHub at 17:04Z. Relationships follow the screenshot, including dashboard-only links under #16404. Stage/activity projections are deterministic test inputs; #16437 is also exercised as a PR-only view variant. Passing a fixture is not published-preview proof.", + "rows": [ + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16404, "stage": 40, "url": "https://github.com/hivecommons/hive/issues/16404", + "title": "[scanner] native-queue-policy cannot pass when the DCO app hits its 250-commit ceiling (forward-merge PRs)", + "linked_prs": [ + { + "number": 16442, "stage": 85, "base_ref": "v5", "author": "thatguywob", "author_kind": "clanker", "url": "https://github.com/hivecommons/hive/pull/16442", + "title": "🐛 fix(ci): report unavailable DCO enumeration without weakening admission", + "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", + "decision_needed": { "question": "Should this admission-workflow change land?", "blocker": "Workflow/admission policy edits need a maintainer's sign-off." }, + "ci_activity": { "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", "state": "passing", "caption": "CI passed", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", "state": "changes_requested", "caption": "Review findings · human decision · adjudicator", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }, + { + "number": 16378, "stage": 71, "display_column": 30, "base_ref": "v6", "author": "clubanderson", "author_kind": "human", "url": "https://github.com/hivecommons/hive/pull/16378", + "title": "🌱 Top up v6 with the latest v5 snapshot", + "head": "670776c942dbed8c3e9d82cc5593599071675e67", + "caption": "Waiting for @clubanderson · not observed coding", + "reason": "CI failed: native-queue-policy; waits for a new author commit.", + "code_activity": { "head": "670776c942dbed8c3e9d82cc5593599071675e67", "state": "waiting_owner", "caption": "Waiting for @clubanderson · not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "clubanderson", "since": "2026-11-03T16:49:36Z", "next": "re-review" }, + "rework": { "state": "pushed", "actor": "clubanderson", "since": "2026-11-03T16:49:36Z" } + } + ] + }, + { + "repo": "hivecommons/hotshot", "kind": "issue", "number": 343, "stage": 40, "url": "https://github.com/hivecommons/hotshot/issues/343", + "title": "[scanner] injection-failure runbook omits injection.iterm2 events; runbook-events guard regex cannot validate them", + "linked_prs": [{ + "number": 344, "stage": 60, "base_ref": "main", "author": "hivecommons-hive", "author_kind": "hive", "url": "https://github.com/hivecommons/hotshot/pull/344", + "title": "📖 docs: document injection.iterm2 runbook events and widen the runbook-events guard", + "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", + "push": { "state": "pushed", "login": "hivecommons-hive[bot]", "sha": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "since": "2026-11-03T16:01:36Z", "next": "re-review" }, + "ci_activity": { "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "state": "queued", "caption": "CI queued", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "state": "approved", "caption": "Review approved", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }] + }, + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16438, "stage": 40, "url": "https://github.com/hivecommons/hive/issues/16438", + "title": "Boot from ConfigMap seed silently drops safety gates present in the prior runtime overlay", + "linked_prs": [ + { + "number": 16446, "stage": 72, "display_column": 30, "base_ref": "v5", "author": "thatguywob", "author_kind": "clanker", "url": "https://github.com/hivecommons/hive/pull/16446", + "title": "🐛 fix: warn before boot recovery drops safety gates", + "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", + "caption": "Waiting for @thatguywob · not observed coding", + "code_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "waiting_owner", "caption": "Waiting for @thatguywob · not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "thatguywob", "since": "2026-11-03T16:55:36Z", "next": "re-review" }, + "rework": { "state": "acknowledged", "actor": "thatguywob", "since": "2026-11-03T16:55:36Z" }, + "ci_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "failing", "caption": "CI failing · test", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "queued", "caption": "Review queued · unassigned", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }, + { + "number": 16449, "stage": 71, "display_column": 30, "base_ref": "v5", "author": "clubanderson", "author_kind": "human", "url": "https://github.com/hivecommons/hive/pull/16449", + "title": "🐛 fix(config): warn, report and optionally refuse when a seed boot drops a safety gate the previous runtime overlay carried", + "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", + "caption": "Waiting for @clubanderson · not observed coding", + "reason": "CI failed: build-and-test; waits for a new author commit.", + "code_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "waiting_owner", "caption": "Waiting for @clubanderson · not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "clubanderson", "since": "2026-11-03T16:57:36Z", "next": "re-review" }, + "rework": { "state": "requested", "actor": "clubanderson", "since": "2026-11-03T16:57:36Z" }, + "ci_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "failing", "caption": "CI failing · golangci-lint", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "queued", "caption": "Review queued · unassigned", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + } + ] + }, + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16420, "stage": 20, "url": "https://github.com/hivecommons/hive/issues/16420", + "title": "[v6] 🐛 standby tile counts an item for a lane that dispatch then refuses (lane split mismatch)", + "operator_action_count": 1 + }, + { + "repo": "hivecommons/hive", "kind": "pr", "number": 16437, "stage": 90, "base_ref": "v6", "url": "https://github.com/hivecommons/hive/pull/16437", + "title": "📖 docs: complete standby readiness prerequisites", "author": "thatguywob", "author_kind": "clanker", + "head": "13b859a8d5e8e434d6f708c75321265241493ac6", + "manual_merge": true, "human_merge_reason_text": "untrusted author" + } + ] +} diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js b/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js new file mode 100644 index 0000000000..9f517aec10 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js @@ -0,0 +1,101 @@ +// Dedicated preview only: evaluate (<file contents>)({ dedicatedPreview: true }). +// Exercises pointer/focus/keyboard UI, never clicks a row/decision action. +(async ({ dedicatedPreview = false } = {}) => { + if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); + const tolerance = 1; + const hoverSettleMS = 200; + const failures = []; + const assert = (ok, message) => { if (!ok) failures.push(message); }; + const triggers = [...document.querySelectorAll('#activity-monitor-panel .ham-chevron-decision .ham-decision-trigger')]; + const nativeStage = trigger => Number(trigger.closest('[data-ham-stage]')?.dataset.hamStage); + const gate = triggers.find(trigger => nativeStage(trigger) === 80 && trigger.querySelector('.ham-seg-t')); + if (!gate) throw new Error('Preview fixture must include native stage 80 with a gate caption and claim-conflict decision'); + const other = triggers.find(trigger => trigger !== gate && nativeStage(trigger) !== 80); + const targets = other ? [gate, other] : [gate]; + const help = document.querySelector('#activity-monitor-panel .ham-chevron-info.config-info'); + if (!help) throw new Error('Preview fixture must include an ordinary chevron tooltip to test mutual exclusion'); + const originalFocus = document.activeElement; + const scrollParents = new Map(); + for (const target of [...targets, help]) { + for (let parent = target.parentElement; parent; parent = parent.parentElement) { + if (!scrollParents.has(parent) && (parent.scrollHeight > parent.clientHeight || parent.scrollWidth > parent.clientWidth)) { + scrollParents.set(parent, { left: parent.scrollLeft, top: parent.scrollTop }); + } + } + } + const frame = () => new Promise(requestAnimationFrame); + const close = () => document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' })); + const portalOpen = () => { + const portal = document.getElementById('config-tooltip-portal'); + return portal && !portal.hidden && getComputedStyle(portal).display !== 'none'; + }; + const hit = (element, label) => { + const box = element.getBoundingClientRect(); + assert(box.width > 0 && box.height > 0 && box.left >= -tolerance && box.right <= innerWidth + tolerance && + box.top >= -tolerance && box.bottom <= innerHeight + tolerance, label + ' is wholly reachable in the viewport'); + const actual = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + assert(actual === element || element.contains(actual), label + ' is not intercepted by a tooltip or other overlay'); + }; + const inspectDialog = (trigger, mode) => { + const dialogs = [...document.querySelectorAll('.ham-decision-pop')]; + assert(dialogs.length === 1, mode + ': exactly one decision dialog'); + assert(!portalOpen(), mode + ': no competing shared-tooltip portal'); + assert(trigger.getAttribute('aria-expanded') === 'true', mode + ': native trigger owns the dialog'); + const dialog = dialogs[0]; + if (!dialog) return null; + assert(dialog.getAttribute('role') === 'dialog', mode + ': dialog semantics retained'); + const actions = [...dialog.querySelectorAll('.ham-decision-act')]; + assert(actions.length > 0, mode + ': decision actions remain present'); + for (const action of actions) hit(action, mode + ': ' + action.textContent.trim()); + const details = dialog.querySelector('.ham-decision-details'); + assert(!!details?.querySelector('summary'), mode + ': full overflow details have a keyboard-accessible disclosure'); + const fullTip = trigger.dataset.hamTip || ''; + // The existing dialog deduplicates sentences and normalizes separators. + const words = fullTip.toLowerCase().match(/[\p{L}\p{N}_@/#-]+/gu) || []; + const dialogWords = new Set(dialog.textContent.toLowerCase().match(/[\p{L}\p{N}_@/#-]+/gu) || []); + assert(words.length > 0 && words.every(word => dialogWords.has(word)), mode + ': unclamped caption/head/reasons survive in the sole dialog'); + return dialog; + }; + try { + for (const trigger of targets) { + close(); + trigger.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await frame(); + await frame(); + hit(trigger, 'decision trigger'); + assert(!trigger.closest('.config-info') && !trigger.closest('.ham-chevron-info').querySelector('.config-tooltip'), 'decision has no generic tooltip ancestor/source'); + help.focus({ preventScroll: true }); + assert(portalOpen(), 'ordinary tooltip is open before testing decision takeover'); + trigger.dispatchEvent(new PointerEvent('pointerover', { bubbles: true, pointerType: 'mouse' })); + trigger.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + assert(!portalOpen(), 'pointer decision opening immediately cancels the previous shared tooltip'); + await new Promise(resolve => setTimeout(resolve, hoverSettleMS)); + inspectDialog(trigger, 'pointer hover'); + close(); + trigger.blur(); + trigger.focus({ preventScroll: true }); + inspectDialog(trigger, 'keyboard focus'); + for (const key of ['ArrowDown', 'Enter', ' ']) { + // The real delegated key handler moves focus into the dialog; no + // synthetic native default or action-button activation is assumed. + trigger.focus({ preventScroll: true }); + trigger.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })); + const dialog = inspectDialog(trigger, 'keyboard ' + JSON.stringify(key)); + assert(!!dialog?.contains(document.activeElement), 'keyboard entry focuses the existing dialog actions'); + } + const dialog = document.querySelector('.ham-decision-pop'); + const summary = dialog?.querySelector('.ham-decision-details > summary'); + summary?.focus({ preventScroll: true }); + assert(!!summary && document.activeElement === summary, 'overflow disclosure is keyboard reachable'); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); + } + } finally { + close(); + originalFocus?.focus?.({ preventScroll: true }); + close(); + for (const [el, position] of scrollParents) el.scrollTo({ ...position, behavior: 'instant' }); + await frame(); + } + if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, tested: targets.length, failures })); + return { viewport: innerWidth, tested: targets.length, failures }; +}) diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js new file mode 100644 index 0000000000..14b2300a93 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -0,0 +1,314 @@ +// Dedicated preview only: evaluate (<file contents>)({ dedicatedPreview: true }). +// Scrolls every header control into view for hit-testing, then restores scroll. +// Never run in the user's live tab; never activates controls or changes rows. +(async ({ dedicatedPreview = false } = {}) => { + if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); + const tolerance = 1; + const failures = []; + const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, singleLineRows: 0, clampedRows: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; + const near = (a, b) => Math.abs(a - b) <= tolerance; + const visible = el => el && el.getClientRects().length && getComputedStyle(el).display !== 'none'; + const rect = el => el.getBoundingClientRect(); + const assert = (ok, label) => { if (!ok) failures.push(label); }; + const settleScroll = async (control, name) => { + const maxFrames = 12; + const requiredStableFrames = 2; + let previous = '', stable = 0; + for (let frame = 0; frame < maxFrames; frame++) { + await new Promise(requestAnimationFrame); + const box = rect(control), viewport = window.visualViewport; + const next = JSON.stringify([box.x, box.y, scrollX, scrollY, + viewport?.offsetLeft, viewport?.offsetTop, viewport?.scale]); + stable = next === previous ? stable + 1 : 0; + if (stable >= requiredStableFrames) return; + previous = next; + } + assert(false, name + 'control/visual viewport must settle before its mandatory hit-test'); + }; + const inspectControl = async (control, toolbar, name) => { + coverage.controlTargets++; + assert(visible(control), name + 'expected header control is not hidden'); + if (!visible(control)) return; // Already a failure, never an untested success. + assert(!control.closest('[inert]'), name + 'controls remain focusable/clickable'); + const contained = () => { + const box = rect(control), bounds = rect(toolbar); + assert(box.width > 0 && box.height > 0 && box.left >= Math.max(0, bounds.left) - tolerance && + box.right <= Math.min(innerWidth, bounds.right) + tolerance, name + 'entire header control stays horizontally inside the toolbar and viewport'); + return box; + }; + contained(); // Horizontal overflow must fail even if scrolling could hide it. + const scrollParents = []; + for (let parent = control.parentElement; parent; parent = parent.parentElement) { + if (parent.scrollHeight > parent.clientHeight || parent.scrollWidth > parent.clientWidth) { + scrollParents.push({ el: parent, left: parent.scrollLeft, top: parent.scrollTop }); + } + } + try { + control.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await settleScroll(control, name); + const box = contained(); + assert(box.top >= -tolerance && box.bottom <= innerHeight + tolerance, name + 'entire control is vertically reachable after deliberate scrolling'); + const hit = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + coverage.hitTested++; + assert(hit === control || control.contains(hit), name + 'every control center hits that control, not an overlay or offscreen null: ' + + JSON.stringify({ control: control.className, box: box.toJSON(), hit: hit?.className || hit?.tagName || null, + viewport: window.visualViewport?.toJSON?.() || { offsetLeft: window.visualViewport?.offsetLeft, + offsetTop: window.visualViewport?.offsetTop, width: window.visualViewport?.width, + height: window.visualViewport?.height, scale: window.visualViewport?.scale } })); + } finally { + for (const { el, left, top } of scrollParents) el.scrollTo({ left, top, behavior: 'instant' }); + await new Promise(requestAnimationFrame); + } + }; + const rows = [...document.querySelectorAll('#activity-monitor-section .ham-row, #activity-monitor-section .ham-sub')]; + const references = new Map(); + for (const [index, row] of rows.entries()) { + const header = row.querySelector(':scope > .ham-row-head > .ham-head-cols'); + const strip = row.querySelector(':scope > .ham-strip-row > ol[aria-label="Pipeline progress"]'); + if (!visible(header) || !visible(strip)) continue; + const lead = header.querySelector('.ham-head-lead'); + // A row without PR refs still has the PR cell (ham-head-tools) as the + // home of its chips; only a cell with refs counts as PR metadata here. + const prCell = header.querySelector('.ham-head-pr'); + const pr = prCell && !prCell.classList.contains('ham-head-tools') ? prCell : null; + const badges = header.querySelector('.ham-badges'); + const columns = [...strip.children]; + // The renderer emits this boundary from its private canonical lane path. + const prStart = Number(header.style.getPropertyValue('--ham-pr-start')) - 1; + const lastLane = columns.length - 2; + const name = 'row ' + index + ' '; + if (row.matches('.ham-sub')) coverage.nested++; + else if (row.dataset.hamKind === 'pr') coverage.prOnly++; + else if (pr) coverage.linked++; + else coverage.issueOnly++; + if (row.matches('.ham-preparation-member')) coverage.preparation++; + if ([...row.querySelectorAll(':scope > .ham-current-stage, :scope > .ham-human-context')] + .some(context => /superseded/i.test(context.textContent))) coverage.superseded++; + if (row.matches('.ham-row') && row.querySelectorAll(':scope > .ham-sub').length > 1) coverage.multiIssue++; + // Height is deliberately absent from the cross-row signature; within-row + // uniformity and the one-line height contract are asserted separately + // below. + const signature = columns.map(cell => ({ left: rect(cell).left - rect(strip).left, width: rect(cell).width })); + const stripLeft = rect(strip.parentElement).left; + // Recorded preparation roots retain the existing rail gutter. Compare + // like gutters across rows; header-to-lane checks below remain exact. + const gutter = row.closest('.ham-row.ham-train') ? 'train' : 'ordinary'; + if (!references.has(gutter)) references.set(gutter, { signature, left: stripLeft }); + const reference = references.get(gutter); + assert(near(stripLeft, reference.left), name + 'root/nested progress containers with the same rail gutter share one horizontal origin'); + for (const [lane, box] of signature.entries()) { + assert(near(box.left, reference.signature[lane].left) && near(box.width, reference.signature[lane].width), name + 'physical lane ' + lane + ' aligns across issue, PR-only and multi-PR rows'); + } + const flow = [...row.children].filter(child => visible(child) && !['absolute', 'fixed'].includes(getComputedStyle(child).position)); + const rowGap = parseFloat(getComputedStyle(row).rowGap) || 0; + for (let child = 1; child < flow.length; child++) { + const previous = flow[child - 1], next = flow[child]; + const spacing = rowGap + (parseFloat(getComputedStyle(previous).marginBottom) || 0) + (parseFloat(getComputedStyle(next).marginTop) || 0); + const measured = rect(next).top - rect(previous).bottom; + assert(measured >= -tolerance && measured <= spacing + tolerance, name + 'no overlap or unexplained vertical gap between successive content/sub-rows: ' + + JSON.stringify({ previous: previous.className, next: next.className, measured, allowed: spacing })); + } + if (matchMedia('(min-width: 1101px)').matches) { + assert(near(rect(lead).left, rect(columns[0]).left), name + 'issue starts at Open'); + assert(near(rect(lead).right, rect(columns[prStart - 1]).right), name + 'issue ends at Claimed'); + if (pr) { + assert(near(rect(pr).left, rect(columns[prStart]).left), name + 'PR starts at PR in progress'); + assert(near(rect(pr).right, rect(columns[lastLane]).right), name + 'PR ends at Merge gate'); + } + if (visible(badges) && badges.children.length) { + // Chips ride the PR line (or wrap under its metadata), never a + // line of their own between the title block and the chevrons. + assert(rect(badges).top >= rect(prCell).top - tolerance && rect(badges).bottom <= rect(prCell).bottom + tolerance, name + 'badges inside the PR cell'); + const metadata = [...prCell.children].filter(child => child !== badges && visible(child)); + if (metadata.length) { + const metaTop = Math.min(...metadata.map(child => rect(child).top)); + assert(rect(badges).bottom > metaTop + tolerance, name + 'badges share the PR metadata line or wrap under it, never a line above'); + } else { + assert(near(rect(badges).top, rect(header).top), name + 'badges on the title line'); + } + } + assert(near(rect(strip.parentElement).top - rect(header).bottom, rowGap), name + 'chevrons sit directly under the title block (row gap only)'); + } else if (pr && visible(lead)) { + assert(rect(pr).top >= rect(lead).bottom - tolerance, name + 'narrow PR below issue'); + } + for (const slot of [lead, pr, badges]) { + if (!visible(slot)) continue; + const bounds = rect(slot); + for (const child of slot.querySelectorAll('.ham-title, .ham-pr-title, .ham-badge, .ham-pr-ref, button')) { + if (!visible(child)) continue; + const box = rect(child); + assert(box.left >= bounds.left - tolerance && box.right <= bounds.right + tolerance, name + child.className + ' within its header slot'); + if (child.clientWidth) assert(child.scrollWidth <= child.clientWidth + tolerance, name + child.className + ' no horizontal clipping'); + } + } + if (badges) { + if (badges.children.length) { + assert(visible(badges), name + 'nonempty action/history toolbar is not hidden'); + coverage.controls++; + // The chips are the trailing, right-anchored flex item of the PR + // cell: they end where the PR span ends (Merge gate), sit beside + // the issue metadata rather than under it, and never overprint the + // PR metadata they follow (wrapping under it when space runs out). + const toolbar = badges.parentElement; + const desktop = matchMedia('(min-width: 1101px)').matches; + const expectedRight = desktop ? rect(toolbar).right : rect(header).right; + assert(near(rect(badges).right, expectedRight), name + 'controls are right-anchored at the end of the PR span, not in an issue-side column'); + if (desktop) assert(rect(badges).left >= rect(lead).right - tolerance, name + 'toolbar does not intersect issue metadata'); + else assert(rect(toolbar).top >= rect(lead).bottom - tolerance, name + 'narrow toolbar below issue metadata'); + for (const child of toolbar.children) { + if (child === badges || !visible(child)) continue; + const box = rect(child), chips = rect(badges); + const apart = box.right <= chips.left + tolerance || box.left >= chips.right - tolerance || box.bottom <= chips.top + tolerance || box.top >= chips.bottom - tolerance; + assert(apart, name + 'toolbar does not intersect PR metadata: ' + JSON.stringify({ child: child.className, box, chips })); + } + for (const control of badges.querySelectorAll('button, a, [tabindex]')) { + if (!control.closest('.config-tooltip')) await inspectControl(control, toolbar, name); + } + } + const chips = [...badges.children].filter(visible).map(rect); + for (let a = 0; a < chips.length; a++) for (let b = a + 1; b < chips.length; b++) { + const overlapX = Math.min(chips[a].right, chips[b].right) - Math.max(chips[a].left, chips[b].left); + const overlapY = Math.min(chips[a].bottom, chips[b].bottom) - Math.max(chips[a].top, chips[b].top); + assert(overlapX <= tolerance || overlapY <= tolerance, name + 'badges do not overlap'); + } + } + const heights = columns.map(cell => rect(cell).height); + assert(Math.max(...heights) - Math.min(...heights) <= tolerance, name + 'all physical chevrons have uniform height'); + // Compact height: captions are clamped to one line, so every row is + // exactly one text line plus the chevron's own padding and border + // (~20px) — the pre-hivecommons/hive#16454 density. Icon-only rows + // share the same one-line floor. + const lineWidth = parseFloat(getComputedStyle(strip).getPropertyValue('--line-width')) || 0; + const cellBudget = (cell, lines, border) => { + const style = getComputedStyle(cell); + return lines * parseFloat(style.lineHeight) + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + + (border === undefined ? parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth) : border); + }; + let rowLines = 0, expectedHeight = cellBudget(columns[0], 1, 2 * lineWidth); + for (const cell of columns) { + for (const copy of cell.querySelectorAll('.ham-chevron-copy, .cue-acting-cap')) { + if (!visible(copy)) continue; + const lines = Math.max(1, Math.round(rect(copy).height / parseFloat(getComputedStyle(copy).lineHeight))); + rowLines = Math.max(rowLines, lines); + expectedHeight = Math.max(expectedHeight, cellBudget(cell, lines)); + } + } + assert(rowLines <= 1, name + 'captions are clamped to a single line: ' + JSON.stringify({ lines: rowLines })); + assert(near(Math.max(...heights), expectedHeight), name + 'chevron height is one text line + padding, not a two-line box: ' + + JSON.stringify({ measured: Math.max(...heights), expected: expectedHeight })); + coverage.singleLineRows++; + if (strip.querySelector('.ham-chevron-copy') && [...strip.querySelectorAll('.ham-chevron-copy')].some(c => visible(c) && c.scrollHeight > rect(c).height + tolerance)) coverage.clampedRows++; + const ci = strip.querySelector('[data-track="ci"]'); + const review = strip.querySelector('[data-track="review"]'); + const current = columns.filter(cell => !cell.classList.contains('cap') && + (cell.classList.contains('active') || cell.classList.contains('ham-current'))); + const delegated = row.matches('.ham-row') && row.querySelector(':scope > .ham-sub ol[aria-label="Pipeline progress"]'); + assert(current.length > 0 || !!delegated, name + 'every actionable row owns a visible current-phase location or delegates to drawn PR children'); + if (current.length) coverage.currentRows++; + if (ci?.dataset.activityState === 'queued' && review?.dataset.activityState === 'approved') coverage.queuedApproved++; + for (const cell of columns) { + if (cell.dataset.activityState) coverage.states[cell.dataset.activityState] = (coverage.states[cell.dataset.activityState] || 0) + 1; + if (cell.dataset.routeState?.split(' ').includes('active')) { + assert(cell.classList.contains('ham-current'), name + 'current phase remains highlighted independently of work'); + const style = getComputedStyle(cell); + assert(Number(style.opacity) >= 0.9 && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent', name + 'queued/unknown/assigned/completed current tracks retain a visible steady fill: ' + JSON.stringify({ cls: cell.className, track: cell.dataset.track, state: cell.dataset.activityState, bg: style.backgroundColor, opacity: style.opacity, label: cell.getAttribute('aria-label')?.slice(0, 80) })); + } + if (cell.dataset.track) { + // CI / Review lanes are chevrons like their neighbours: same notch + // polygon, padding and height, state expressed by fill, not a box. + const style = getComputedStyle(cell); + const peer = columns.find(other => other !== cell && !other.dataset.track && !other.classList.contains('cap') && other !== columns[0]); + const peerStyle = getComputedStyle(peer); + assert(style.clipPath !== 'none' && style.clipPath === peerStyle.clipPath, name + 'activity track keeps the chevron notch polygon: ' + JSON.stringify({ track: style.clipPath, peer: peerStyle.clipPath })); + assert(style.borderTopWidth === '0px' && style.borderLeftWidth === '0px' && style.borderRadius === peerStyle.borderRadius, name + 'activity track is not a bordered box'); + assert(style.paddingLeft === peerStyle.paddingLeft && style.paddingRight === peerStyle.paddingRight && style.paddingTop === peerStyle.paddingTop, name + 'activity track shares chevron padding'); + assert(near(rect(cell).height, rect(peer).height), name + 'activity track shares chevron height'); + } + if (cell.dataset.displayState === 'unknown') { + coverage.unknown++; + // #16493: a track in the current phase always carries count words + // ("CI ?/? · no checks reported yet"); only a not-started track is + // the glyph alone. + const words = cell.querySelector('.ham-track-state')?.innerText.trim() || ''; + if (cell.classList.contains('todo')) assert(words === '', name + 'not-started track is icon-only'); + // A settled verdict (passed / failed, approved / changes requested) + // is the glyph alone in its colour; its count words ride in the + // tooltip and accessible label. + else if (cell.dataset.verdict) assert(words === '' && /\b(CI|Review): (CI|Review)\b/.test(cell.getAttribute('aria-label') || ''), name + 'settled verdict is the glyph alone with its words in the label: ' + JSON.stringify(words)); + else assert(/^(CI|Review)\b/.test(words), name + 'lit unknown track carries count words, never a bare glyph: ' + JSON.stringify(words)); + assert(!!cell.querySelector('svg'), name + 'unknown track retains the column glyph'); + assert(!cell.hasAttribute('data-motion'), name + 'unknown cannot animate as observed work'); + } + const info = cell.querySelector('.ham-chevron-info'); + if (info?.classList.contains('ham-chevron-decision')) { + const button = info.querySelector('.ham-decision-trigger'); + assert(!!button && button.getAttribute('aria-haspopup') === 'dialog', name + 'decision retains its native keyboard/pointer trigger'); + assert(!info.matches('.config-info, [tabindex]') && !info.querySelector('.config-tooltip') && !button?.closest('.config-info'), name + 'decision dialog is the sole hover/focus detail surface'); + assert(!!button?.dataset.hamTip, name + 'decision dialog receives full unclamped overflow details'); + } else if (info) { + const tip = document.getElementById(info.getAttribute('aria-describedby')); + assert(info.tabIndex === 0 && !!tip && tip.getAttribute('role') === 'tooltip', name + 'full details are keyboard/hover accessible'); + assert(!!info.getAttribute('aria-label'), name + 'full accurate accessible label is retained'); + } + for (const copy of cell.querySelectorAll('.ham-chevron-copy, .cue-acting-cap')) { + if (!visible(copy)) continue; + const style = getComputedStyle(copy); + const lineHeight = parseFloat(style.lineHeight); + const bounds = rect(copy); + assert(style.whiteSpace === 'normal' && style.overflowWrap === 'anywhere', name + 'text wraps, including unbroken handles'); + assert(bounds.height <= lineHeight + tolerance, name + 'maximum one visible text line'); + if (copy.scrollHeight > bounds.height + tolerance) coverage.wrapped++; + assert(bounds.left >= rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft) - tolerance, name + 'text clears the left chevron notch'); + assert(bounds.right <= rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight) + tolerance, name + 'text clears the right chevron point'); + // Centred as before the two-line budget: the glyphs sit centred in + // their copy box (a stretched copy with start-aligned text fails + // here), and the copy together with its reserved icons sits centred + // in the chevron's content box, both horizontally and vertically. + const content = { left: rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft), right: rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight), + top: rect(cell).top + parseFloat(getComputedStyle(cell).paddingTop), bottom: rect(cell).bottom - parseFloat(getComputedStyle(cell).paddingBottom) }; + const range = document.createRange(); + range.selectNodeContents(copy); + const glyphs = [...range.getClientRects()].filter(line => line.width > 0 && line.top >= bounds.top - tolerance && line.bottom <= bounds.bottom + tolerance); + const glyphTolerance = parseFloat(style.fontSize) / 2; // a trailing wrap space, never a ragged-left line + if (glyphs.length) { + const text = { left: Math.min(...glyphs.map(line => line.left)), right: Math.max(...glyphs.map(line => line.right)) }; + assert(Math.abs((text.left + text.right) / 2 - (bounds.left + bounds.right) / 2) <= glyphTolerance, name + 'caption text is horizontally centred within its copy box: ' + + JSON.stringify({ text, copy: { left: bounds.left, right: bounds.right } })); + } + // A `display: contents` wrapper (.ham-active-ico-wrap) has no box of + // its own: its children are the flex items that take space, so the + // union measures them, not the box-less wrapper. + const boxes = el => getComputedStyle(el).display === 'contents' ? [...el.children].flatMap(boxes) : [el]; + const group = copy.parentElement === info + ? [...info.children].flatMap(boxes).filter(child => visible(child) && !child.classList.contains('config-tooltip')).map(rect) + : [bounds]; + const union = { left: Math.min(...group.map(box => box.left)), right: Math.max(...group.map(box => box.right)), + top: Math.min(...group.map(box => box.top)), bottom: Math.max(...group.map(box => box.bottom)) }; + assert(Math.abs((union.left + union.right) / 2 - (content.left + content.right) / 2) <= tolerance, name + 'caption and icons are horizontally centred in the chevron: ' + + JSON.stringify({ union, content })); + assert(Math.abs((union.top + union.bottom) / 2 - (content.top + content.bottom) / 2) <= tolerance, name + 'caption and icons are vertically centred in the chevron: ' + + JSON.stringify({ union, content })); + const icons = info ? [...info.querySelectorAll(':scope > svg, :scope > .ham-active-ico-wrap svg, :scope > .ham-gate-ico svg')].filter(visible) : []; + for (const icon of icons) { + const box = rect(icon); + assert(box.right <= bounds.left + tolerance || box.left >= bounds.right - tolerance, name + 'text does not overlap reserved icons'); + } + } + } + const progressTop = rect(strip).top; + for (const slot of [lead, pr, badges]) { + if (visible(slot)) assert(rect(slot).bottom <= progressTop + tolerance, name + 'header above progress tracks'); + } + } + assert(coverage.issueOnly > 0 && coverage.linked > 0 && coverage.prOnly > 0, 'preview must contain issue-only, linked, and PR-only fixtures'); + assert(coverage.multiIssue > 0 && coverage.nested >= 2, 'preview must contain a real multi-PR issue with independent nested rows'); + assert(coverage.preparation >= 2 && coverage.superseded > 0, 'preview must contain recorded/unverified preparation fronts and an actionable superseded-human-decision row'); + for (const state of ['queued', 'unknown', 'assigned', 'approved', 'waiting', 'failing', 'passing', 'running']) { + assert(coverage.states[state] > 0, 'preview must exercise current-head activity state ' + state); + } + assert(coverage.unknown > 0 && coverage.queuedApproved > 0 && coverage.wrapped > 0 && coverage.controls > 0, 'preview must include unknown, queued-CI/approved-review, long clamped text and action/history controls'); + assert(coverage.singleLineRows > 0 && coverage.clampedRows > 0, 'preview must include a row whose caption overflows its one-line clamp (long text stays a one-line chevron)'); + assert(coverage.controlTargets > 0 && coverage.controlTargets === coverage.hitTested, 'every relevant header control must be hit-tested, never skipped as offscreen'); + if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, coverage, failures })); + return { viewport: innerWidth, coverage, failures }; +}) diff --git a/src/pkg/escalation/abandoned_red_test.go b/src/pkg/escalation/abandoned_red_test.go new file mode 100644 index 0000000000..82eb897b07 --- /dev/null +++ b/src/pkg/escalation/abandoned_red_test.go @@ -0,0 +1,91 @@ +package escalation + +import ( + "path/filepath" + "testing" + "time" +) + +// The claim-release valve must not let a covered issue go while the hive is +// still re-engaging the covering PR: hivecommons/hive#16475 fell from +// 040-covered-by-pr to 010-actionable ten minutes after #16492 went red, with +// the reaper's first re-engagement for that same head landing a minute later +// (hivecommons/hive#16522). +func TestAbandonedRed(t *testing.T) { + newStore := func(t *testing.T) (*Store, *time.Time) { + t.Helper() + s := Load(filepath.Join(t.TempDir(), "ledger.json")) + now := time.Now().UTC() + s.SetClock(func() time.Time { return now }) + s.ObserveRed([]Observation{{Repo: "org/repo", Number: 1, HeadSHA: "sha1", Red: true}}) + return s, &now + } + + t.Run("stale inside the re-engagement budget keeps the claim", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + if !s.StaleRed("org/repo", 1, "sha1") { + t.Fatal("precondition: head must read stale") + } + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head the reaper is still re-engaging must not release its issue") + } + s.RecordReEngagement("org/repo", 1) + *now = now.Add(ReEngageCooldown + time.Minute) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("one delivered re-engagement is the fix loop working, not giving up") + } + }) + + t.Run("fresh red is never abandoned", func(t *testing.T) { + s, _ := newStore(t) + s.MarkEscalated("org/repo", 1) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head younger than RedPRStaleAfter must not release, even escalated") + } + }) + + t.Run("escalated to a human releases", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + s.MarkEscalated("org/repo", 1) + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head handed to a human has left the fix loop") + } + }) + + t.Run("spent re-engagement budget releases", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + for i := 0; i < MaxReEngagements; i++ { + s.RecordReEngagement("org/repo", 1) + } + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head with no re-engagements left has been given up on") + } + }) + + t.Run("unreachable owner releases after the whole window", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(ClaimReleaseAfter - time.Minute) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("still inside the re-engagement window") + } + *now = now.Add(2 * time.Minute) + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head red for the whole re-engagement window with nobody reachable must release") + } + }) + + t.Run("a moved head resets the verdict", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(ClaimReleaseAfter + time.Minute) + s.ObserveRed([]Observation{{Repo: "org/repo", Number: 1, HeadSHA: "sha2", Red: true}}) + if s.AbandonedRed("org/repo", 1, "sha2") { + t.Fatal("a new red head is a fix attempt: the clock and the budget start over") + } + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head the store no longer tracks is not stale") + } + }) +} diff --git a/src/pkg/escalation/escalation.go b/src/pkg/escalation/escalation.go index 15fda8c6f1..63ab2c6632 100644 --- a/src/pkg/escalation/escalation.go +++ b/src/pkg/escalation/escalation.go @@ -1137,6 +1137,38 @@ func (s *Store) StaleRed(repo string, number int, headSHA string) bool { return s.now().Sub(e.FirstRedAt) >= RedPRStaleAfter } +// ClaimReleaseAfter is how long a red head may sit unchanged before the +// claim-release valve lets the covered issue go even though no re-engagement +// was ever delivered (an owner the fix loop could not reach). It is the +// whole re-engagement window — MaxReEngagements spaced by ReEngageCooldown — +// so an issue is never offered for a second PR while the first is still +// inside the hive's own repair budget. +const ClaimReleaseAfter = time.Duration(MaxReEngagements) * ReEngageCooldown + +// AbandonedRed reports whether the hive has stopped repairing the PR's +// CURRENT red head SHA: the head is StaleRed AND the fix loop has given up +// on it — the PR was escalated to a human, the re-engagement budget for +// this head is spent, or the head has been red for ClaimReleaseAfter with +// nobody reachable to re-engage. It is the predicate the claim-release +// valve (FilterClaimedIssues, "Fix #3") must use instead of StaleRed: a +// red head that is merely stale is still being re-engaged by the reaper +// and the merge watcher, and releasing its issue then stages the issue +// 010-actionable while the covering PR reads 070-fixing — one piece of +// work with two owners (hivecommons/hive#16522). +func (s *Store) AbandonedRed(repo string, number int, headSHA string) bool { + s.mu.Lock() + defer s.mu.Unlock() + e := s.entries[Key(repo, number)] + if e == nil || e.CurRedSHA == "" || headSHA == "" || e.CurRedSHA != headSHA || e.FirstRedAt.IsZero() { + return false + } + redFor := s.now().Sub(e.FirstRedAt) + if redFor < RedPRStaleAfter { + return false + } + return e.Escalated || e.ReEngagements >= MaxReEngagements || redFor >= ClaimReleaseAfter +} + // TryReEngage atomically decides whether the re-engagement paths (#2/#4) may // dispatch another fix for the PR's current red head SHA, and if so records the // attempt. It returns true at most MaxReEngagements times per red SHA: the cap diff --git a/src/pkg/fleetreport/fleetreport.go b/src/pkg/fleetreport/fleetreport.go index b959da48e5..605dace3ff 100644 --- a/src/pkg/fleetreport/fleetreport.go +++ b/src/pkg/fleetreport/fleetreport.go @@ -886,6 +886,12 @@ func IsGitHubUpstreamUnavailable(s string) bool { // exact-message exclusions matched in the function body below. func IsBenignMessage(msg string) bool { m := strings.ToLower(msg) + // The bounded rebase loop hands an unresolved conflict to a person after + // its attempt cap. Repeated polls of that same handoff are expected, not + // a runtime defect (#16510). Keep other rebase failures reportable. + if strings.TrimSpace(m) == "rebase attempts exhausted; leaving the conflict to a person" { + return true + } // A moved held branch requires fresh review: this is the hold guard // enforcing merge safety, not a runtime defect (#16100). Match only the // successful refusal; provenance, comment and re-hold failures stay reportable. diff --git a/src/pkg/fleetreport/runtime_test.go b/src/pkg/fleetreport/runtime_test.go index 299bca8feb..4b04eb6c2e 100644 --- a/src/pkg/fleetreport/runtime_test.go +++ b/src/pkg/fleetreport/runtime_test.go @@ -941,6 +941,26 @@ func TestIsBenignMessageInferenceModelNotConfigured(t *testing.T) { } } +func TestIsBenignMessageRebaseAttemptsExhausted(t *testing.T) { + for _, msg := range []string{ + "rebase attempts exhausted; leaving the conflict to a person", + " REBASE ATTEMPTS EXHAUSTED; LEAVING THE CONFLICT TO A PERSON ", + } { + if !IsBenignMessage(msg) { + t.Errorf("expected rebase handoff %q not benign", msg) + } + } + for _, msg := range []string{ + "rebase failed", + "rebase attempt state could not be persisted", + "review dispatch exhausted; holding PR for a human", + } { + if IsBenignMessage(msg) { + t.Errorf("failure %q wrongly benign", msg) + } + } +} + func TestIsBenignMessageKnowledgePrimerBytecap(t *testing.T) { const msg = "knowledge primer: dropped facts over the byte cap" if !IsBenignMessage(msg) { diff --git a/src/pkg/fleetreport/slogfeed/slogfeed.go b/src/pkg/fleetreport/slogfeed/slogfeed.go index 82aaaecef0..594dc8fdc8 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed.go @@ -114,7 +114,7 @@ func Key(msg string) string { } func (h *Handler) feed(r slog.Record) { - if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) { + if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) || automergeMergeGuardSkip(r) { return } class := fleetreport.ClassUnclassifiedRepeated @@ -211,6 +211,32 @@ func inferenceBlockedStall(r slog.Record) bool { return blocked } +// automergeMergeGuardSkip reports whether r is an automerge sweep lane +// (queued, trusted-author or contributor) declining to refresh a PR's base +// while a merge to that destination is already in flight (reason +// base-refresh:merge-guard). The guard is self-limiting and the PR is retried +// next tick (hivecommons/hive#16520). Any other sweep skip stays reportable. +func automergeMergeGuardSkip(r slog.Record) bool { + switch strings.TrimSpace(r.Message) { + case "automerge sweep skipped PR", + "trusted-author automerge sweep skipped PR", + "contributor-lane automerge sweep skipped PR": + default: + return false + } + reason, err := "", "" + r.Attrs(func(a slog.Attr) bool { + switch a.Key { + case "reason": + reason = a.Value.String() + case "error": + err = a.Value.String() + } + return true + }) + return reason == "base-refresh:merge-guard" && strings.Contains(err, "destination merge already in progress") +} + // failClosedStatus500 reports whether r is one of the two gates that fail // closed when GitHub answers the combined-status read with a 500: the // merge-eligible lane gate and the trusted-author automerge sweep skip. The PR @@ -257,6 +283,24 @@ func hubHeartbeatUnavailable(r slog.Record) bool { return match } +// hubHeartbeatCachedFallback is the outcome notice for a bounded collector +// timeout: sending stale stats, a minimal liveness beat, skipping a beat before +// identity is known, or dropping the fresh agent overlay is the liveness +// safeguard working as designed (#16507, #16516). Keep the WARN in local logs, +// but do not file a second defect for the fallback itself. The collector +// timeout and its slow-section breakdown, collector panics, and heartbeat send +// failures remain reportable. +func hubHeartbeatCachedFallback(r slog.Record) bool { + switch strings.TrimSpace(r.Message) { + case "hub heartbeat collect timed out — sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out with no cached payload — sending MINIMAL liveness beat (identity only, no stats) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out and hive identity not yet known — skipping this beat; loop keeps ticking so liveness stays green", + "hub heartbeat fresh stats collect timed out; sending stale cached stats without fresh agent overlay": + return true + } + return false +} + // reviewCommentCapped reports whether r is the review-request watcher noting // that the per-head review cap suppressed a duplicate comment while the // verdict was still recorded. That is the cap working as designed, not a diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index 37d240a089..6254db65ae 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -64,6 +64,31 @@ func TestHandlerSkipsBenignAndExplicitClasses(t *testing.T) { } } +// #16510: polling an exhausted rebase episode must keep warning locally +// without turning the intentional handoff into a repeated runtime defect. +func TestRebaseAttemptsExhaustedLogsWithoutFleetReport(t *testing.T) { + logger, seen, out := newFeed(t) + const msg = "rebase attempts exhausted; leaving the conflict to a person" + for i := 0; i < 10; i++ { + logger.Warn(msg, "repo", "projectbluefin/fsdk-containers", "number", 491, + "head", "c0ad5df0927de888c373ccf9b5caead751ef9a6f", "attempts", 2, + "max", 2, "timed_out", 2, "mergeable_state", "dirty") + } + if len(*seen) != 0 { + t.Fatalf("expected rebase handoff produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 10 { + t.Fatalf("wrapped handler saw %d records, want 10", n) + } + if !strings.Contains(out.String(), msg) || !strings.Contains(out.String(), `"timed_out":2`) { + t.Fatal("local logs lost the warning or its diagnostics") + } + logger.Warn("rebase failed", "error", "unexpected failure") + if len(*seen) != 1 || (*seen)[0].class != fleetreport.ClassUnclassifiedRepeated { + t.Fatalf("rebase failure must remain reportable: %+v", *seen) + } +} + func TestHandlerWithAttrsCarriesBoundAttrsIntoDiagnostics(t *testing.T) { logger, seen, _ := newFeed(t) logger.With("agent", "quality").WithGroup("req").Warn("ledger write failed", "path", "/data/x.json") @@ -699,6 +724,41 @@ func TestFailClosedStatus500LogsWithoutFleetReport(t *testing.T) { } } +// #16520: the base-refresh merge guard is a self-limiting skip, not a defect. +func TestAutomergeMergeGuardSkipLogsWithoutFleetReport(t *testing.T) { + guard := []any{"repo", "hive", "pr", 16511, "reason", "base-refresh:merge-guard", "error", "destination merge already in progress"} + cases := []struct { + name string + msg string + args []any + want int + }{ + {"merge guard", "automerge sweep skipped PR", guard, 0}, + {"trusted lane merge guard", "trusted-author automerge sweep skipped PR", guard, 0}, + {"contributor lane merge guard", "contributor-lane automerge sweep skipped PR", guard, 0}, + {"other reason", "automerge sweep skipped PR", []any{"repo", "hive", "pr", 16511, "reason", "base-refresh", "error", "update branch: 422 conflict"}, 8}, + {"guard reason other error", "automerge sweep skipped PR", []any{"repo", "hive", "pr", 16511, "reason", "base-refresh:merge-guard", "error", "boom"}, 8}, + {"other message", "self-authored automerge sweep skipped PR", guard, 8}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logger, seen, out := newFeed(t) + for i := 0; i < 8; i++ { + logger.Warn(tc.msg, tc.args...) + } + if tc.want == 0 && len(*seen) != 0 { + t.Errorf("produced observations: %+v", *seen) + } + if tc.want != 0 && len(*seen) == 0 { + t.Errorf("must remain reportable") + } + if n := strings.Count(out.String(), "\n"); n != 8 { + t.Errorf("wrapped handler saw %d records, want 8", n) + } + }) + } +} + // #15789: a hub that is restarting answers the heartbeat 5xx and the spoke // retries on the next beat; auth rejections stay reportable. func TestHubHeartbeatUnavailableLogsWithoutFleetReport(t *testing.T) { @@ -725,6 +785,52 @@ func TestHubHeartbeatUnavailableLogsWithoutFleetReport(t *testing.T) { } } +// #16507: using last-good stats after a bounded collect timeout is the +// liveness safeguard working, not another defect distinct from the timeout. +func TestHubHeartbeatCachedFallbackLogsWithoutFleetReport(t *testing.T) { + for _, msg := range []string{ + "hub heartbeat collect timed out — sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out with no cached payload — sending MINIMAL liveness beat (identity only, no stats) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out and hive identity not yet known — skipping this beat; loop keeps ticking so liveness stays green", + "hub heartbeat fresh stats collect timed out; sending stale cached stats without fresh agent overlay", + } { + t.Run(msg, func(t *testing.T) { + logger, seen, out := newFeed(t) + for i := 0; i < 8; i++ { + logger.Warn(msg) + } + if len(*seen) != 0 { + t.Fatalf("outcome notice produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 8 { + t.Errorf("wrapped handler saw %d records, want 8", n) + } + if !strings.Contains(out.String(), msg) { + t.Error("outcome notice missing from local logs") + } + }) + } + + // Preserve the underlying timeout diagnostics and actual heartbeat failures. + for _, failure := range []string{ + "hub heartbeat collect timed out; loop keeps ticking so liveness stays green", + "hub heartbeat collect budget exceeded — slowest collectors (in-flight = still running at timeout)", + "hub heartbeat collect panicked", + "hub heartbeat fresh stats collect panicked", + "hub heartbeat fresh stats collect timed out", + "hub heartbeat failed", + "hub heartbeat rejected", + } { + t.Run(failure, func(t *testing.T) { + logger, seen, _ := newFeed(t) + logger.Warn(failure) + if len(*seen) != 1 || (*seen)[0].message != failure { + t.Fatalf("heartbeat failure must remain reportable: %+v", *seen) + } + }) + } +} + // #16100: branch drift is an expected safety refusal, even when an own-only // write-back gate leaves the snapshot in place and it repeats every poll. func TestHoldGuardDriftLogsWithoutFleetReport(t *testing.T) { diff --git a/src/pkg/github/advisory.go b/src/pkg/github/advisory.go index 90a99de08d..ae280099f5 100644 --- a/src/pkg/github/advisory.go +++ b/src/pkg/github/advisory.go @@ -15,8 +15,8 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/crux/logscrub" "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/issueshape" "github.com/hivecommons/hive/pkg/effects" + "github.com/hivecommons/hive/pkg/issueshape" ) const ( @@ -497,6 +497,30 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i commentID := existing.id var author string + if commentID > 0 && !writeThrough { + // Per-anchor unchanged guard (#16439). The listed body the #5507 + // suppression compares against can lag the last PATCH (the comment + // list is eventually consistent), so at steady state the digest was + // still re-edited with identical material content every cycle. + // Compare the pending material fingerprint with the one this process + // last WROTE to this exact anchor and skip the PATCH when they match; + // the periodic write-through still forces a real write. + anchorKey := fmt.Sprintf("%s@%d", key, commentID) + pendingFP := materialDigestFingerprint(digest) + c.advisoryMu.Lock() + unchanged := c.advisoryDigestAnchorHashes[anchorKey] == pendingFP + if unchanged { + c.advisoryDigestHashes = ensureStringMap(c.advisoryDigestHashes) + c.advisoryDigestHashes[key] = digestHash + c.advisoryDigestSkips[key]++ + } + c.advisoryMu.Unlock() + if unchanged { + c.logger.Debug("advisory digest material content unchanged for anchor — skipping edit", + slog.String("repo", repo), slog.Int("issue", issueNum), slog.Int("comment_id", commentID)) + return nil + } + } if commentID > 0 { edited, _, err := c.client.Issues.EditComment(ctx, owner, repoName, int64(commentID), &gh.IssueComment{ Body: gh.Ptr(digest), @@ -528,6 +552,7 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i return fmt.Errorf("posting advisory digest to %s#%d: %w", repo, issueNum, c.classifyDigestWriteError(ctx, owner, repoName, err)) } author = comment.GetUser().GetLogin() + commentID = int(comment.GetID()) } // Audit the FIRST post and every advisoryDigestAuditInterval-th one, not the @@ -547,6 +572,18 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i // over from any real write. c.advisoryDigestHashes[key] = digestHash c.advisoryDigestSkips[key] = 0 + if commentID > 0 { + // Persist the anchor this write landed on and its material + // fingerprint (#16439): the next cycle re-pins to it past any + // foreign-authored digest comment and skips the PATCH when the + // rendered content has not materially changed. + if c.advisoryDigestAnchors == nil { + c.advisoryDigestAnchors = make(map[string]int) + } + c.advisoryDigestAnchors[key] = commentID + c.advisoryDigestAnchorHashes = ensureStringMap(c.advisoryDigestAnchorHashes) + c.advisoryDigestAnchorHashes[fmt.Sprintf("%s@%d", key, commentID)] = materialDigestFingerprint(digest) + } c.advisoryDigestPosts[key]++ count := c.advisoryDigestPosts[key] c.advisoryMu.Unlock() @@ -659,7 +696,7 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string PerPage: advisoryDigestCommentsPerPage, }, } - var botAuthored digestComment + var scan digestScan pages := 0 for { comments, resp, err := c.client.Issues.ListComments(ctx, owner, repo, issueNum, opts) @@ -667,15 +704,15 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string // A partial scan that already found a usable fallback still // beats creating a duplicate, so surface the error but keep // whatever the earlier pages turned up. - return botAuthored, err + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), err } pages++ - found, done := c.scanDigestPage(owner, repo, issueNum, comments, &botAuthored) + found, done := c.scanDigestPage(comments, &scan) if done { - return found, nil + return c.resolveDigestScan(owner, repo, issueNum, found, &scan), nil } if resp == nil || resp.NextPage == 0 { - return botAuthored, nil + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), nil } if pages >= advisoryDigestScanMaxPages { c.logger.Warn("advisory digest comment scan hit its page cap — treating the digest as absent, which will CREATE a new one", @@ -683,19 +720,33 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string slog.Int("issue", issueNum), slog.Int("pages_scanned", pages), slog.Int("comments_scanned", pages*advisoryDigestCommentsPerPage)) - return botAuthored, nil + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), nil } opts.Page = resp.NextPage } } +// digestScan carries state across the pages of one digest-comment scan. +type digestScan struct { + // botAuthored is the newest bot-authored-but-not-provably-ours digest + // comment, kept as a fallback when no exact match turns up. + botAuthored digestComment + // foreign is the newest digest comment this App can never edit (human + // authored), recorded so the resolution can report it ONCE per issue + // together with the action taken (#16439) instead of warning on every + // cycle the comment is seen. + foreign digestComment + foreignAuthor string +} + // scanDigestPage applies the authorship rules to one page of comments. It // returns (comment, true) when it has found the definitive digest to edit and // the scan can stop, or (_, false) to continue to the next page. A -// bot-authored-but-not-provably-ours comment is remembered in botAuthored as a -// fallback rather than ending the scan, so a later page can still yield an -// exact match. -func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh.IssueComment, botAuthored *digestComment) (digestComment, bool) { +// bot-authored-but-not-provably-ours comment is remembered in scan.botAuthored +// as a fallback rather than ending the scan, so a later page can still yield +// an exact match. A foreign-authored digest comment is NEVER selected: it is +// only noted in scan.foreign so the resolution can log it. +func (c *Client) scanDigestPage(comments []*gh.IssueComment, scan *digestScan) (digestComment, bool) { for _, comment := range comments { if !strings.HasPrefix(comment.GetBody(), advisoryDigestPrefix) { continue @@ -718,8 +769,8 @@ func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh // a misconfigured slug would create a duplicate every cycle. // "First" is now the NEWEST such comment, since the scan runs // newest-first. - if !botAuthored.found() { - *botAuthored = digestCommentFrom(comment) + if !scan.botAuthored.found() { + scan.botAuthored = digestCommentFrom(comment) } continue } @@ -728,18 +779,56 @@ func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh // hard-forbids an App from editing a foreign-authored comment (403 // "Resource not accessible by integration") no matter what the // installation grants, so adopting it wedges the digest forever - // (kalantar-msb/soft-reflective#1). Skip it; if no bot-authored digest - // comment exists a fresh App-authored one is created and every later + // (kalantar-msb/soft-reflective#1). Never select it; the scan goes on + // to re-pin to an App-authored digest further down the issue, and if + // there is none a fresh App-authored one is created and every later // cycle edits THAT one, so nothing is duplicated per cycle. - c.logger.Warn("skipping advisory digest comment not authored by this App — an installation token can never edit it", - slog.String("repo", owner+"/"+repo), - slog.Int("issue", issueNum), - slog.Int64("comment_id", comment.GetID()), - slog.String("author", login)) + if !scan.foreign.found() { + scan.foreign = digestCommentFrom(comment) + scan.foreignAuthor = login + } } return digestComment{}, false } +// resolveDigestScan finalizes one scan: it reports a foreign-authored digest +// comment ONCE per issue per process at Warn — with the action taken — and +// at Debug thereafter (#16439). Before the fix the Warn fired on every cycle +// the human comment was listed (~every 5 minutes on +// torch-spyre/spyre-inference#406) and never settled, because the comment +// stays on the issue forever. +func (c *Client) resolveDigestScan(owner, repo string, issueNum int, chosen digestComment, scan *digestScan) digestComment { + if !scan.foreign.found() { + return chosen + } + action := "creating a fresh App-authored digest comment" + if chosen.found() { + action = fmt.Sprintf("re-pinned to App-authored digest comment %d", chosen.id) + } + key := fmt.Sprintf("%s/%s#%d", owner, repo, issueNum) + c.advisoryMu.Lock() + warned := c.advisoryForeignDigestWarned[key] + if c.advisoryForeignDigestWarned == nil { + c.advisoryForeignDigestWarned = make(map[string]bool) + } + c.advisoryForeignDigestWarned[key] = true + c.advisoryMu.Unlock() + attrs := []any{ + slog.String("repo", owner+"/"+repo), + slog.Int("issue", issueNum), + slog.Int("comment_id", scan.foreign.id), + slog.String("author", scan.foreignAuthor), + slog.String("action", action), + } + const msg = "skipping advisory digest comment not authored by this App — an installation token can never edit it" + if warned { + c.logger.Debug(msg, attrs...) + } else { + c.logger.Warn(msg, attrs...) + } + return chosen +} + // digestCommentFrom projects the fields the post path needs out of a forge // comment. UpdatedAt is preferred over CreatedAt: the digest comment is EDITED // in place, so the last write — not the original creation — is what the diff --git a/src/pkg/github/advisory_foreign_anchor_test.go b/src/pkg/github/advisory_foreign_anchor_test.go new file mode 100644 index 0000000000..8aebc45f0b --- /dev/null +++ b/src/pkg/github/advisory_foreign_anchor_test.go @@ -0,0 +1,162 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "sync" + "testing" +) + +// countingHandler is a slog.Handler that counts records per level. +type countingHandler struct { + mu sync.Mutex + counts map[slog.Level]int + msgs []string +} + +func (h *countingHandler) Enabled(context.Context, slog.Level) bool { return true } +func (h *countingHandler) Handle(_ context.Context, r slog.Record) error { + h.mu.Lock() + defer h.mu.Unlock() + if h.counts == nil { + h.counts = map[slog.Level]int{} + } + h.counts[r.Level]++ + h.msgs = append(h.msgs, r.Message) + return nil +} +func (h *countingHandler) WithAttrs([]slog.Attr) slog.Handler { return h } +func (h *countingHandler) WithGroup(string) slog.Handler { return h } + +// digestAnchorMux is digestCommentMux with a per-PATCH counter and a listed +// body that is served unchanged regardless of PATCHes, modelling the +// eventually-consistent comment list. +func digestAnchorMux(org, repo string, comments []map[string]any, patches map[int64]int, created *int) *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/issues/10/comments", org, repo), func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "GET": + json.NewEncoder(w).Encode(comments) + case "POST": + *created++ + json.NewEncoder(w).Encode(map[string]any{"id": 9999, "user": map[string]any{"login": "hive-app[bot]"}}) + } + }) + mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/issues/comments/", org, repo), func(w http.ResponseWriter, r *http.Request) { + if r.Method == "PATCH" { + var id int64 + fmt.Sscanf(r.URL.Path, fmt.Sprintf("/repos/%s/%s/issues/comments/%%d", org, repo), &id) + patches[id]++ + json.NewEncoder(w).Encode(map[string]any{"id": id, "user": map[string]any{"login": "hive-app[bot]"}}) + } + }) + return mux +} + +// A human-authored digest comment NEWER than the App's own (the +// torch-spyre/spyre-inference#406 shape in #16439): the App re-pins to its +// own older comment rather than creating a duplicate, and the foreign-anchor +// warning is logged once per issue per process with the action taken — later +// cycles demote it to Debug. +func TestPostAdvisoryDigest_ForeignAnchorRepinsToAppCommentWarnsOnce(t *testing.T) { + org, repo := "torch-spyre", "spyre-inference" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 5061265231, "body": advisoryDigestPrefix + " — human", "user": map[string]any{"login": "joerunde", "type": "User"}}, + {"id": 4000, "body": advisoryDigestPrefix + " — ours (stale)", "user": map[string]any{"login": "hive-app[bot]", "type": "Bot"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + h := &countingHandler{} + c.logger = slog.New(h) + + for i := 0; i < 3; i++ { + body := fmt.Sprintf("%s — findings v%d", advisoryDigestPrefix, i) + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, body); err != nil { + t.Fatalf("cycle %d: %v", i, err) + } + } + if patches[4000] != 3 { + t.Errorf("expected the App's own comment to be edited on each changed cycle, got %d PATCHes", patches[4000]) + } + if patches[5061265231] != 0 || created != 0 { + t.Errorf("wrong write path: patchedForeign=%d created=%d", patches[5061265231], created) + } + if got := h.counts[slog.LevelWarn]; got != 1 { + t.Errorf("foreign-anchor warning logged %d times, want exactly once; msgs=%v", got, h.msgs) + } + if c.advisoryDigestAnchors["torch-spyre/spyre-inference#10"] != 4000 { + t.Errorf("anchor not persisted: %v", c.advisoryDigestAnchors) + } +} + +// With no App-authored digest on the issue a fresh one is created, and the +// created comment becomes the persisted anchor. +func TestPostAdvisoryDigest_ForeignAnchorCreatesAndPersistsAnchor(t *testing.T) { + org, repo := "torch-spyre", "spyre-inference" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 5061265231, "body": advisoryDigestPrefix + " — human", "user": map[string]any{"login": "joerunde", "type": "User"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + h := &countingHandler{} + c.logger = slog.New(h) + + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, advisoryDigestPrefix+" — new"); err != nil { + t.Fatalf("PostAdvisoryDigest: %v", err) + } + if created != 1 || len(patches) != 0 { + t.Errorf("expected exactly one CREATE and no PATCH, got created=%d patches=%v", created, patches) + } + if c.advisoryDigestAnchors["torch-spyre/spyre-inference#10"] != 9999 { + t.Errorf("created comment not persisted as anchor: %v", c.advisoryDigestAnchors) + } + if h.counts[slog.LevelWarn] != 1 { + t.Errorf("want one Warn, got %d", h.counts[slog.LevelWarn]) + } +} + +// Identical material content re-rendered with a fresh timestamp is not +// PATCHed again, even when the listed body still shows an older digest (the +// comment list lagging the last edit). +func TestPostAdvisoryDigest_UnchangedAnchorBodySkipsEdit(t *testing.T) { + org, repo := "testorg", "testrepo" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 222, "body": advisoryDigestPrefix + " — older content", "user": map[string]any{"login": "hive-app[bot]", "type": "Bot"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + first := advisoryDigestPrefix + " — 2026-08-31 04:00 UTC\n**Findings:** 2\n- a\n- b" + second := advisoryDigestPrefix + " — 2026-08-31 04:05 UTC\n**Findings:** 2\n- a\n- b" + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, first); err != nil { + t.Fatalf("first: %v", err) + } + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, second); err != nil { + t.Fatalf("second: %v", err) + } + if patches[222] != 1 { + t.Errorf("expected exactly one PATCH for identical material content, got %d", patches[222]) + } + if created != 0 { + t.Errorf("unexpected CREATE: %d", created) + } + third := advisoryDigestPrefix + " — 2026-08-31 04:10 UTC\n**Findings:** 3\n- a\n- b\n- c" + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, third); err != nil { + t.Fatalf("third: %v", err) + } + if patches[222] != 2 { + t.Errorf("changed material content must PATCH again, got %d", patches[222]) + } +} diff --git a/src/pkg/github/automerge/automerge_adopt_now_test.go b/src/pkg/github/automerge/automerge_adopt_now_test.go index b59dba64b4..cdf29ad8a6 100644 --- a/src/pkg/github/automerge/automerge_adopt_now_test.go +++ b/src/pkg/github/automerge/automerge_adopt_now_test.go @@ -113,3 +113,54 @@ func TestAdoptNowOfflineWordingAndHoldStops(t *testing.T) { t.Fatalf("offline wording: %s", comments[0]) } } + +// An operator may take over anyone's PR, a hive owner's included: the +// person-authored rule (hivecommons/hive#15202) holds for the hive's own +// initiative and for an adoption/supersede request, but an explicit Adopt +// now adopts, consumes the forced mark and leaves no "queued" behind. +func TestAdoptNowTakesOverOwnerAuthoredPR(t *testing.T) { + policy := adoptPolicy() + policy.OwnerAuthor = func(login string) bool { return login == "mallory" } + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, policy) + defer done() + h.sink.presence = &ContributorPresence{Registered: true, Online: false} + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + store := h.e.stageStoreOrShared() + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + + // Control: the request label alone is refused for an owner's PR. + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 0 { + t.Fatalf("request adopted an owner's PR: pulls=%v", h.adopt.pulls) + } + if rec, _ := store.Get(key); rec.AdoptionBlocked("aaa") != "author-is-person" { + t.Fatalf("refusal not recorded: %+v", rec) + } + + store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 1 { + t.Fatalf("Adopt now did not supersede an owner's PR: pulls=%v added=%v", h.adopt.pulls, h.api.added) + } + comments := adoptionComments(h.api) + if len(comments) != 1 || !strings.Contains(comments[0], "by=@clubanderson reason=operator-forced") { + t.Fatalf("adoption comments = %v", h.api.comments) + } + rec, _ := store.Get(key) + if rec.AdoptedHead != "aaa" || rec.AdoptedBy != 90 || rec.AdoptReason != AdoptReasonOperatorForced { + t.Fatalf("record after Adopt now: %+v", rec) + } + if _, forced := rec.AdoptionForced(); forced || rec.AdoptionBlocked("aaa") != "" { + t.Fatalf("forced mark or person block survived the adoption: %+v", rec) + } + // hivecommons/hive#16489: adoption/supersede label is consumed and removed + // after the forced adoption is recorded. + if !containsLabel(h.api.removed, "adoption/supersede") { + t.Fatalf("request label kept after the forced adoption was consumed: removed=%v", h.api.removed) + } +} diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index e0372e74bd..db283293db 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -239,7 +239,9 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { h.adopt.superseders[89] = map[string]any{"number": 89, "state": "closed", "merged": false} h.adopt.mu.Unlock() res := observe() - if h.adopt.commentReads != 1 { + // One read for the marker scan, one for the 085 entry-comment upsert + // (hivecommons/hive#16433) that precedes posting the entry. + if h.adopt.commentReads != 2 { t.Fatalf("comment reads = %d", h.adopt.commentReads) } if len(h.adopt.pulls) != 1 || len(h.adopt.prEdits) != 0 { @@ -261,7 +263,7 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { if added := h.addedLabels(); len(added) != 1 || added[0] != "stage/074-adopted-by-hive" { t.Fatalf("074 after marker recovery: added=%v removed=%v", h.api.added, h.api.removed) } - if h.adopt.commentReads != 1 { + if h.adopt.commentReads != 2 { t.Fatalf("comments re-read: %d", h.adopt.commentReads) } } @@ -320,7 +322,10 @@ func TestAdoptionMarkerSettledOrAbsentIsNotRecovered(t *testing.T) { h.adopt.mu.Unlock() observe() observe() - if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 1 { + // The marker scan reads once per head; the 085 entry-comment upsert + // reads once more before the entry is posted, and not again for the + // same head and cause (hivecommons/hive#16433). + if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 2 { t.Fatalf("settled marker recovered: pulls=%d reads=%d", len(h.adopt.pulls), h.adopt.commentReads) } rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index add03c7163..13a36110c4 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -792,16 +792,23 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: adoption due but blocked by label", "repo", obs.Display, "pr", obs.Number, "label", l) return 0, nil } - if personAuthored(obs, policy) { + person := personAuthored(obs, policy) + if person && !forced { // A person's own PR (hivecommons/hive#15202): no contributor hive - // can be offline for it, and neither an operator request nor a - // forced adoption changes who should fix it. Recorded so the - // tracker row says why. + // can be offline for it, and an operator's adoption request does + // not change who should fix it. Recorded so the tracker row says + // why. Only an explicit Adopt now (forced) takes it over. store.NoteAdoptionBlocked(key, obs.HeadSHA, stagelabels.AdoptBlockedAuthorPerson, now) c.info("stage labels: adoption refused, a person pushed this PR themselves; asking the author instead", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "author_kind", obs.AuthorKind.String(), "reason", reason, "requested", requested, "forced", forced) return 0, nil } if forced { + if person { + // An operator may take over anyone's PR, owners and + // maintainers included: the click is the decision, logged + // with the actor so the takeover stays attributable. + c.info("stage labels: operator-forced adoption over a person-authored PR", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "author_kind", obs.AuthorKind.String(), "head", obs.HeadSHA, "by", forcedBy) + } c.info("stage labels: operator forced adoption; maintainer policy, admission and presence bypassed", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "by", forcedBy, "online", presence.Online, "policy", policy.maintainerPolicy()) } else if c.adoptionRefusedByAdmission(ctx, store, key, obs, requested, now) { return 0, nil @@ -1722,7 +1729,9 @@ func (c *Engine) authorMaintainsRepo(ctx context.Context, obs stageObservation, // personAuthored: the PR was pushed by a person — author/human, or one of // this hive's owners — rather than by a clanker or a registered contributor -// relay. Such a PR is never adopted (hivecommons/hive#15202). +// relay. Such a PR is never adopted on the hive's own initiative +// (hivecommons/hive#15202); only an operator's explicit Adopt now takes it +// over. func personAuthored(obs stageObservation, policy StageLabelPolicy) bool { if obs.AuthorKind == authorkind.Human { return true diff --git a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go index ed195c64ed..69aaf11b1a 100644 --- a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go +++ b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go @@ -1,6 +1,7 @@ package automerge import ( + "slices" "strings" "testing" "time" @@ -37,6 +38,14 @@ func hiveFixingPR(number int, head string, labels ...string) *gh.PullRequest { return pr } +// hiveFixingPRNoIssue is a hive PR that closes no issue: nothing to +// re-author for, so exhaustion parks it for a person. +func hiveFixingPRNoIssue(number int, head string, labels ...string) *gh.PullRequest { + pr := hiveFixingPR(number, head, labels...) + pr.Body = gh.Ptr("Tidy the widget.\n\n— hive: backend=pi model=gpt-6\n") + return pr +} + func decisionComments(api *stageAPI) []string { var out []string for _, c := range api.comments { @@ -54,7 +63,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // Attempts left: the PR stays on its fixing stage. status[90] = review.FixDispatchStatus{Attempts: 3} - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) if rec, _ := o.e.stageStoreOrShared().Get(key); rec.Stage != stagelabels.Fixing { t.Fatalf("with attempts left = %s (%q)", rec.Stage, rec.Reason) } @@ -62,7 +71,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} o.api.reset() o.clock.advance(time.Minute) - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) rec, _ := o.e.stageStoreOrShared().Get(key) if rec.Stage != stagelabels.NeedsDecision || rec.Reason != stagelabels.FixerExhaustedReason(6) { t.Fatalf("after exhaustion = %s (%q)", rec.Stage, rec.Reason) @@ -74,7 +83,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { if len(comments) != 1 { t.Fatalf("decision comments = %d, want 1: %q", len(comments), comments) } - for _, want := range []string{"gave up after 6 attempts", "last reviewer finding: handler drops the error from Close()", "Re-author from scratch", "Hand it to a person", "Close as not planned"} { + for _, want := range []string{"gave up after 6 attempts", "last reviewer finding: handler drops the error from Close()", "Give direction", "Hand it to a person", "Close as not planned"} { if !strings.Contains(comments[0], want) { t.Fatalf("decision comment lacks %q:\n%s", want, comments[0]) } @@ -85,7 +94,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // Same head, next pass: no second comment. o.clock.advance(5 * time.Minute) - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) if got := decisionComments(o.api); len(got) != 1 { t.Fatalf("decision comments after second pass = %d, want 1", len(got)) } @@ -95,7 +104,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // A fix in flight on a new head is a fixing stage again. status[90] = review.FixDispatchStatus{Active: true, Agent: "fixer", Attempts: 1} - o.observeSelf(hiveFixingPR(90, "ddd", "stage/085-needs-decision"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ddd", "stage/085-needs-decision"), contributorLaneReasonChangesRequested) if rec, _ := o.e.stageStoreOrShared().Get(key); rec.Stage != stagelabels.Fixing { t.Fatalf("new head with an active fix = %s (%q)", rec.Stage, rec.Reason) } @@ -113,3 +122,117 @@ func TestFixerExhaustedIgnoresContributorPR(t *testing.T) { t.Fatalf("decision comments on a contributor PR = %d", len(got)) } } + +// Owner on #16456: "we should not need a re-author pill on a hive agent's +// PR." The first exhaustion of a hive PR re-authors it automatically — +// marker label on the issue, note, superseded label, close, store record, +// reason re-authoring:<issue> — and never parks at 085. The second +// exhaustion for the same issue parks with the remaining answers only. +func TestFixerExhaustedHivePRReauthorsItselfOnce(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + key := stageKey("acme", "widget", 90) + setStagePRTruth(12) + + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec, _ := o.e.stageStoreOrShared().Get(key) + if rec.Stage != stagelabels.Fixing || rec.Reason != stagelabels.ReauthoringReason(12) { + t.Fatalf("first exhaustion = %s (%q), want 070 re-authoring:12", rec.Stage, rec.Reason) + } + if !rec.Reauthored() || rec.ReauthorIssue != 12 || rec.ReauthorHead != "ccc" || rec.ReauthorAttempts != 6 || !rec.ReauthorNoted { + t.Fatalf("store record = %+v", rec) + } + if got := decisionComments(o.api); len(got) != 0 { + t.Fatalf("decision comment posted on an auto re-author: %q", got) + } + var notes []string + for _, c := range o.api.comments { + if strings.HasPrefix(c, reauthorMarker) { + notes = append(notes, c) + } + } + if len(notes) != 1 || !strings.Contains(notes[0], "gave up on this PR after 6 attempts") || !strings.Contains(notes[0], "fresh PR for #12 from the current `v5`") { + t.Fatalf("re-author notes = %q", notes) + } + added := o.addedLabels() + for _, want := range []string{stagelabels.LabelReauthored, "hive/superseded"} { + if !slices.Contains(added, want) { + t.Fatalf("labels added %q lack %q", added, want) + } + } + if !slices.Contains(o.adopt.prEdits, "90:closed") { + t.Fatalf("PR edits = %q, want 90 closed", o.adopt.prEdits) + } + if got := o.e.stageStoreOrShared().ReauthoredFor("acme/widget", 12); got != 90 { + t.Fatalf("ReauthoredFor(12) = %d, want 90", got) + } + + // The fresh PR for the same issue exhausts its fixer too: parked at + // 085 naming the earlier re-author; no second re-author, no re-author + // option in the comment. + setStagePRTruth(12, stagelabels.LabelReauthored) + o.api.reset() + o.adopt.prEdits = nil + o.clock.advance(time.Hour) + status[91] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(91, "ddd", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec91, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 91)) + if rec91.Stage != stagelabels.NeedsDecision || rec91.Reason != stagelabels.FixerExhaustedReason(6) || rec91.Reauthored() { + t.Fatalf("second exhaustion = %s (%q) reauthored=%v, want 085 fixer-exhausted:6", rec91.Stage, rec91.Reason, rec91.Reauthored()) + } + if len(o.adopt.prEdits) != 0 { + t.Fatalf("second exhaustion closed a PR: %q", o.adopt.prEdits) + } + comments := decisionComments(o.api) + if len(comments) != 1 { + t.Fatalf("decision comments = %d, want 1: %q", len(comments), comments) + } + for _, want := range []string{"re-author of #90", "Give direction", "Hand it to a person", "Close as not planned"} { + if !strings.Contains(comments[0], want) { + t.Fatalf("decision comment lacks %q:\n%s", want, comments[0]) + } + } + if strings.Contains(comments[0], "Re-author from scratch") || strings.Contains(comments[0], "adoption/supersede") { + t.Fatalf("decision comment still offers re-authoring:\n%s", comments[0]) + } +} + +// Only the issue's marker label (store lost): still no second re-author. +func TestFixerExhaustedMarkerLabelAloneBlocksReauthor(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + setStagePRTruth(12, stagelabels.LabelReauthored) + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 90)) + if rec.Stage != stagelabels.NeedsDecision || rec.Reauthored() || len(o.adopt.prEdits) != 0 { + t.Fatalf("marker label ignored: %s (%q) edits=%q", rec.Stage, rec.Reason, o.adopt.prEdits) + } +} + +// A retry pass while the close is pending reuses the stored re-author +// target instead of reading the closing issue again (hivecommons/hive#16586). +func TestFixerExhaustedRetryPassSkipsIssueGetWhenStoreHasTarget(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + setStagePRTruth(12) + + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + if rec, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 90)); !rec.Reauthored() { + t.Fatalf("first pass did not record the re-author: %+v", rec) + } + if o.api.issueGets[12] == 0 { + t.Fatal("first pass never read issue 12") + } + + o.api.mu.Lock() + o.api.issueGets = nil + o.api.mu.Unlock() + o.clock.advance(time.Hour) + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + if got := o.api.issueGets[12]; got != 0 { + t.Fatalf("retry pass read issue 12 %d times, want 0", got) + } +} diff --git a/src/pkg/github/automerge/automerge_hive_reauthor.go b/src/pkg/github/automerge/automerge_hive_reauthor.go new file mode 100644 index 0000000000..1e82005c86 --- /dev/null +++ b/src/pkg/github/automerge/automerge_hive_reauthor.go @@ -0,0 +1,149 @@ +package automerge + +import ( + "context" + "fmt" + "net/http" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/authorkind" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Automatic re-author of the hive's own exhausted PR. +// +// Owner on #16456 (a hive PR parked at 085 with "Re-author ▸" after six +// fixer attempts): "we should not need a re-author pill on a hive agent's +// PR." A hive-authored PR whose fixer gave up is the hive's to redo, not +// a person's to click: the pass closes it as superseded and leaves the +// issue for the next kick to open a fresh PR from the current base. It +// is bounded to ONE automatic re-author per issue — the durable marker is +// stagelabels.LabelReauthored on the issue plus the stage store record — +// so a second exhaustion parks at 085 with the remaining answers (give +// direction, hand to a person, close as not planned); re-authoring is +// never offered as a human choice on a hive PR. Rewrites a person asks +// for on a CONTRIBUTOR's PR stay `decide:adopt`. + +// reauthorMarker stamps the close note on the superseded hive PR. +const reauthorMarker = "<!-- hive:reauthor" + +// reauthorTarget is what autoReauthorTarget decided for an exhausted PR. +type reauthorTarget struct { + // Issue is the issue the fresh PR is for; 0 when the PR closes none. + Issue int + // PriorPR is the hive PR already re-authored for Issue (the marker is + // set), 0 when this would be the first; -1 when only the label says + // so and the store has no record of which PR. + PriorPR int +} + +// reauthorRecord is what a pass that re-authored a PR writes on the store +// once the key is observed. +type reauthorRecord struct { + issue, attempts int + noted bool +} + +// eligible reports whether the PR is re-authored automatically now. +func (t reauthorTarget) eligible() bool { return t.Issue > 0 && t.PriorPR == 0 } + +// hiveOwnPR reports whether obs is a PR the hive App itself opened — the +// only PR the hive re-authors on its own. +func (c *Engine) hiveOwnPR(obs stageObservation) bool { + if obs.AuthorKind == authorkind.Hive { + return true + } + app := c.transport.AppBotLogin() + return app != "" && normalizeBotLogin(obs.Author) == normalizeBotLogin(app) +} + +// autoReauthorTarget reads the exhausted PR's closing issue and whether +// that issue has been re-authored before (store record, else the issue's +// marker label). Issue 0 means nothing to re-author for. +func (c *Engine) autoReauthorTarget(ctx context.Context, store *stagelabels.Store, obs stageObservation) reauthorTarget { + if !c.hiveOwnPR(obs) { + return reauthorTarget{} + } + refs := hgithub.ClosingIssueRefs(obs.Body, obs.Owner+"/"+obs.Repo) + if len(refs) == 0 { + return reauthorTarget{} + } + t := reauthorTarget{Issue: refs[0]} + if prior := store.ReauthoredFor(obs.Owner+"/"+obs.Repo, t.Issue); prior > 0 && prior != obs.Number { + t.PriorPR = prior + return t + } + issue, _, err := c.gh.Issues.Get(ctx, obs.Owner, obs.Repo, t.Issue) + if err != nil { + // Unknown marker state: do not re-author on a guess. + c.warn("stage labels: re-author marker unreadable; parking the exhausted PR for a person", "repo", obs.Display, "pr", obs.Number, "issue", t.Issue, "error", err) + t.PriorPR = -1 + return t + } + for _, l := range issue.Labels { + if strings.EqualFold(l.GetName(), stagelabels.LabelReauthored) { + t.PriorPR = -1 + return t + } + } + return t +} + +// reauthorExhaustedHivePR closes the hive's exhausted PR as superseded so +// the issue returns to the queue for a fresh PR. Order: marker label on +// the issue first (durable before anything else, so a crash can never +// re-author twice), note, superseded label, close. Returns the number of +// comments posted and whether the note is out; the caller records both +// on the store once the pass has observed the key (MarkReauthored / +// MarkReauthorNoted), so the next pass neither re-labels nor re-notes. +func (c *Engine) reauthorExhaustedHivePR(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, fixer review.FixDispatchStatus, issue int, now time.Time) (comments int, noted bool, err error) { + logArgs := []any{"repo", obs.Display, "pr", obs.Number, "issue", issue, "head", obs.HeadSHA, "attempts", fixer.Attempts} + rec, _ := store.Get(key) + noted = rec.ReauthorNoted + if !rec.Reauthored() { + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, obs.Owner, obs.Repo, issue, []string{stagelabels.LabelReauthored}); err != nil { // writeback:gated + c.warn("stage labels: re-author marker label failed; parking the exhausted PR for a person", append(logArgs, "error", err)...) + return 0, false, err + } + c.info("stage labels: hive PR's fixer exhausted; re-authoring it for the issue from the current base", logArgs...) + } + body := reauthorCloseComment(obs, issue, fixer.Attempts) + item := writebackItemForObservation(obs) + item.HiveAuthored = true + if d := c.writebackAllowed(obs.Display, item, writeback.KindSupersessionClose, body); !d.Allowed { + c.info("stage labels: re-author close withheld by the write-back gate", append(logArgs, "writeback_reason", d.Reason)...) + return 0, noted, nil + } + if !noted { + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + c.warn("stage labels: re-author close note failed", append(logArgs, "error", err)...) + return 0, false, err + } + // The note is out: the close below may be retried, the note never. + noted, comments = true, 1 + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, obs.Owner, obs.Repo, obs.Number, []string{hgithub.SupersededLabel}); err != nil { // writeback:gated + c.warn("stage labels: re-author superseded label failed", append(logArgs, "label", hgithub.SupersededLabel, "error", err)...) + } + } + if _, _, err := c.gh.PullRequests.Edit(ctx, obs.Owner, obs.Repo, obs.Number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { // writeback:gated + if isGitHubStatus(err, http.StatusForbidden) || isGitHubStatus(err, http.StatusNotFound) { + c.warn("stage labels: cannot close re-authored PR (permission); left open with the note", append(logArgs, "error", err)...) + return comments, noted, nil + } + c.warn("stage labels: closing re-authored PR failed; retried next pass", append(logArgs, "error", err)...) + return comments, noted, err + } + return comments, noted, nil +} + +// reauthorCloseComment is the one note the superseded hive PR gets. +func reauthorCloseComment(obs stageObservation, issue, attempts int) string { + base := nonEmpty(obs.BaseRef, "the base branch") + return fmt.Sprintf("%s issue=%d head=%s -->\n**Re-authoring:** the hive's fixer gave up on this PR after %d attempts on `%s`. Closing it as superseded; the hive opens a fresh PR for #%d from the current `%s` on its next cycle. Nothing from this branch is merged.\n", + reauthorMarker, issue, obs.HeadSHA, attempts, shortSHA(obs.HeadSHA), issue, base) +} diff --git a/src/pkg/github/automerge/automerge_human_paths.go b/src/pkg/github/automerge/automerge_human_paths.go index 3f7a29655c..08025015a2 100644 --- a/src/pkg/github/automerge/automerge_human_paths.go +++ b/src/pkg/github/automerge/automerge_human_paths.go @@ -89,8 +89,9 @@ func (c *Engine) currentHumanMergePinOnly(repo string) (config.PinOnlyException, // and stays held (#16326). Once the diff is accepted, every commit behind the // head must itself be provably the trusted author's: the PR author login only // says who opened the PR, and any principal with write access can push onto -// that branch afterwards. The sweep lanes and /approve share this helper so -// they never disagree. +// that branch afterwards. Finally each new action SHA must resolve in its +// upstream repository, not merely somewhere in its fork network. The sweep +// lanes and /approve share this helper so they never disagree. func (c *Engine) humanMergePinOnlyExempt(ctx context.Context, owner, repo string, pr *gh.PullRequest, files []intent.ChangedFile, matches []string) (bool, string) { if len(matches) == 0 || pr == nil { return false, "" @@ -108,13 +109,87 @@ func (c *Engine) humanMergePinOnlyExempt(ctx context.Context, owner, repo string if reported := pr.GetChangedFiles(); reported <= 0 || reported != len(files) { return false, "complete changed-file list not proven" } - if ok, why := intent.ClassifyPinOnly(files, matches, policy.Spec()); !ok { + ok, why, pins := intent.ClassifyPinOnlyActions(files, matches, policy.Spec()) + if !ok { return false, why } if why := c.pinOnlyCommitsTrusted(ctx, owner, repo, pr, policy); why != "" { return false, why } - return true, "all changes are approved pin replacements by verified trusted-author commits" + if why := c.pinOnlyActionPinsUpstream(ctx, pins); why != "" { + return false, why + } + return true, "all changes are approved pin replacements by verified trusted-author commits, anchored upstream" +} + +// pinOnlyMaxTagDepth bounds annotated-tag dereferencing (a tag of a tag). +const pinOnlyMaxTagDepth = 3 + +// pinOnlyActionPinsUpstream returns "" when every accepted action-sha pin is +// a commit of its upstream action repository. GitHub resolves a `uses:` SHA +// through the whole fork network, so a 40-hex commit pushed to any fork of +// owner/repo is a valid pin; the classifier sees syntax only. A pin with a +// version comment must be exactly what tags/<version> (dereferenced through +// annotated tags) points at; one without must be an ancestor of the upstream +// default branch. Any API error, 404 or mismatch fails closed with a reason. +// Image digests are content-addressed and need no such anchor. +func (c *Engine) pinOnlyActionPinsUpstream(ctx context.Context, pins []intent.ActionPin) string { + if len(pins) == 0 { + return "" + } + ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") + for _, pin := range pins { + if why := c.pinOnlyActionPinUpstream(ctx, pin); why != "" { + return fmt.Sprintf("action %s@%s: %s", pin.Repo, stagelabels.ShortSHA(pin.SHA), why) + } + } + return "" +} + +func (c *Engine) pinOnlyActionPinUpstream(ctx context.Context, pin intent.ActionPin) string { + owner, repo, ok := strings.Cut(pin.Repo, "/") + if !ok || owner == "" || repo == "" || pin.SHA == "" { + return "upstream repository or commit unknown" + } + if pin.Version != "" { + ref, _, err := c.gh.Git.GetRef(ctx, owner, repo, "tags/"+pin.Version) + if err != nil { + return fmt.Sprintf("tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj := ref.GetObject() + for depth := 0; obj.GetType() == "tag"; depth++ { + if depth == pinOnlyMaxTagDepth { + return fmt.Sprintf("tag %s nests too deeply", pin.Version) + } + tag, _, err := c.gh.Git.GetTag(ctx, owner, repo, obj.GetSHA()) + if err != nil { + return fmt.Sprintf("annotated tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj = tag.GetObject() + } + if obj.GetType() != "commit" || !strings.EqualFold(obj.GetSHA(), pin.SHA) { + return fmt.Sprintf("upstream tag %s does not point at the pinned commit", pin.Version) + } + return "" + } + upstream, _, err := c.gh.Repositories.Get(ctx, owner, repo) + if err != nil { + return fmt.Sprintf("upstream repository could not be read: %v", err) + } + branch := upstream.GetDefaultBranch() + if branch == "" { + return "upstream default branch unknown" + } + // base=pin, head=default: "ahead" or "identical" means the pinned commit + // is an ancestor of (reachable from) the upstream default branch. + cmp, _, err := c.gh.Repositories.CompareCommits(ctx, owner, repo, pin.SHA, branch, &gh.ListOptions{PerPage: 1}) + if err != nil { + return fmt.Sprintf("pinned commit could not be compared with upstream %s: %v", branch, err) + } + if status := cmp.GetStatus(); status != "ahead" && status != "identical" { + return fmt.Sprintf("pinned commit is not on upstream %s (compare status %q)", branch, status) + } + return "" } func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { @@ -130,10 +205,6 @@ func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { return false } -// pinOnlyCommitsMaxPages bounds the commit listing; GitHub serves at most 250 -// commits for a PR, and a pin bump has one or two. -const pinOnlyCommitsMaxPages = 3 - // pinOnlyCommitsTrusted returns "" when every commit of pr is attributed to a // trusted author, was committed by a trusted login or by GitHub itself // (web-flow), carries a signature GitHub verified, and the current head is @@ -153,21 +224,12 @@ func (c *Engine) pinOnlyCommitsTrusted(ctx context.Context, owner, repo string, return "PR head SHA unknown" } ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") - opts := &gh.ListOptions{PerPage: 100} - var all []*gh.RepositoryCommit - for page := 0; ; page++ { - if page == pinOnlyCommitsMaxPages { - return "PR commit list too long to verify" - } - commits, resp, err := c.gh.PullRequests.ListCommits(ctx, owner, repo, pr.GetNumber(), opts) - if err != nil { - return fmt.Sprintf("PR commits could not be listed: %v", err) - } - all = append(all, commits...) - if resp == nil || resp.NextPage == 0 { - break - } - opts.Page = resp.NextPage + all, complete, err := hgithub.ListPRRepositoryCommits(ctx, c.gh, owner, repo, pr.GetNumber()) + if err != nil { + return fmt.Sprintf("PR commits could not be listed: %v", err) + } + if !complete { + return "PR commit list too long to verify" } if len(all) == 0 { return "PR has no commits to verify" @@ -217,7 +279,8 @@ func pinOnlyTrustedCommitter(policy config.PinOnlyException, login string) bool // ticks) and returns autoMergeReasonHumanMergePath, unless the repo's enabled // auto_merge.human_merge_pin_only exception qualifies the PR (trusted author, // complete list, every changed line a pin replacement, every commit a -// verified trusted-author commit) and returns ("", nil). +// verified trusted-author commit, every action SHA anchored in its upstream +// repository) and returns ("", nil). func (c *Engine) humanMergePathGate(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest) (string, error) { patterns := c.currentHumanMergePaths(owner + "/" + repo) if len(patterns) == 0 { diff --git a/src/pkg/github/automerge/automerge_human_paths_test.go b/src/pkg/github/automerge/automerge_human_paths_test.go index fcf4192cfc..748c05b4e9 100644 --- a/src/pkg/github/automerge/automerge_human_paths_test.go +++ b/src/pkg/github/automerge/automerge_human_paths_test.go @@ -36,8 +36,13 @@ type humanPathFront struct { commits []map[string]any commitsStatus int commitsHits int - labels []string - comments []string + // upstream serves GET /repos/actions/checkout<suffix> by suffix: a map + // value is the JSON body, an int a status code, a missing suffix 404. + // nil serves tags/v5 as a lightweight tag at testPinNewSHA. + upstream map[string]any + upstreamHits int + labels []string + comments []string } // testPinCommit is one PR commit as the gate sees it: author login, committer @@ -89,6 +94,20 @@ func newHumanPathFront(t *testing.T, backend string, f *humanPathFront) *httptes commits = []map[string]any{testPinCommit("sha7", "renovate-bot", true)} } json.NewEncoder(w).Encode(commits) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/actions/checkout"): + f.upstreamHits++ + upstream := f.upstream + if upstream == nil { + upstream = map[string]any{"/git/ref/tags/v5": testPinRef("commit", testPinNewSHA)} + } + switch v := upstream[strings.TrimPrefix(r.URL.Path, "/repos/actions/checkout")].(type) { + case nil: + w.WriteHeader(http.StatusNotFound) + case int: + w.WriteHeader(v) + default: + json.NewEncoder(w).Encode(v) + } case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/issues/7/labels": var labels []string _ = json.NewDecoder(r.Body).Decode(&labels) @@ -368,8 +387,9 @@ func TestSetHumanMergePathsNilEngine(t *testing.T) { // Pin-only exception (#16266): fixtures for calling humanMergePathGate on a PR // whose files carry patches. var ( + testPinNewSHA = strings.Repeat("b", 40) testPinOldLine = " - uses: actions/checkout@" + strings.Repeat("a", 40) + " # v4" - testPinNewLine = " - uses: actions/checkout@" + strings.Repeat("b", 40) + " # v5" + testPinNewLine = " - uses: actions/checkout@" + testPinNewSHA + " # v5" ) func testPinFile(name string) map[string]any { @@ -377,6 +397,19 @@ func testPinFile(name string) map[string]any { "patch": "@@ -3 +3 @@\n-" + testPinOldLine + "\n+" + testPinNewLine} } +// testPinFileNoComment is a pin bump without a version comment, which the +// gate anchors on the upstream default branch instead of a tag. +func testPinFileNoComment(name string) map[string]any { + strip := func(line string) string { return line[:strings.Index(line, " #")] } + return map[string]any{"filename": name, "status": "modified", "additions": 1, "deletions": 1, + "patch": "@@ -3 +3 @@\n-" + strip(testPinOldLine) + "\n+" + strip(testPinNewLine)} +} + +// testPinRef is a git ref (or annotated tag) object pointing at sha. +func testPinRef(kind, sha string) map[string]any { + return map[string]any{"object": map[string]any{"type": kind, "sha": sha}} +} + func pinOnlyFor(repo string, ex config.PinOnlyException) func(string) (config.PinOnlyException, bool) { return func(r string) (config.PinOnlyException, bool) { if strings.EqualFold(r, repo) { @@ -401,11 +434,15 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { entries []map[string]any commits []map[string]any commitsStatus int + upstream map[string]any wantHold bool wantHits int // wantCommitHits is how often the commit list is read: only a diff // the classifier accepts costs that call. wantCommitHits int + // wantUpstreamHits is how many upstream action reads were made: only + // after the diff and every commit are accepted. + wantUpstreamHits int }{ {name: "paths unconfigured: no fetch, no hold", pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}}, {name: "exception unconfigured: held as before", paths: humanPathsFor("acme/widget", testHumanMergePattern), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, wantHold: true, wantHits: 1}, @@ -432,6 +469,30 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { commits: []map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1}, {name: "trusted pure pin, commit list unavailable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, commitsStatus: http.StatusBadGateway, wantHold: true, wantHits: 1, wantCommitHits: 1}, + {name: "upstream tag points elsewhere: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("commit", strings.Repeat("c", 40))}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "upstream tag missing (fork-network SHA): held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "upstream annotated tag dereferenced to the pin: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("tag", "t2"), "/git/tags/t2": testPinRef("commit", testPinNewSHA)}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 3}, + {name: "upstream annotated tag points elsewhere: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("commit", strings.Repeat("c", 40))}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "upstream annotated tag unreadable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1")}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "upstream tag chain too deep: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("tag", "t1")}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 4}, + {name: "no version comment, pin on upstream default branch: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "ahead"}}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, pin is upstream default head: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "identical"}}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, pin diverged from upstream default: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "diverged"}}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, compare fails: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": http.StatusBadGateway}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, upstream default branch unknown: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{}}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "no version comment, upstream repository unreadable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, {name: "trusted pin plus non-pin line: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{{ "filename": workflow, "status": "modified", "additions": 2, "deletions": 1, "patch": "@@ -3 +3,2 @@\n-" + testPinOldLine + "\n+" + testPinNewLine + "\n+ - run: curl evil | sh", @@ -452,7 +513,7 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { w.WriteHeader(http.StatusNotFound) })) defer backend.Close() - front := &humanPathFront{fileEntries: tc.entries, commits: tc.commits, commitsStatus: tc.commitsStatus} + front := &humanPathFront{fileEntries: tc.entries, commits: tc.commits, commitsStatus: tc.commitsStatus, upstream: tc.upstream} srv := newHumanPathFront(t, backend.URL, front) defer srv.Close() @@ -476,6 +537,13 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { if front.commitsHits != tc.wantCommitHits { t.Fatalf("commit list hits = %d, want %d", front.commitsHits, tc.wantCommitHits) } + wantUpstream := tc.wantUpstreamHits + if wantUpstream == 0 && !tc.wantHold && tc.upstream == nil && tc.wantCommitHits > 0 { + wantUpstream = 1 // the default lightweight tags/v5 read + } + if front.upstreamHits != wantUpstream { + t.Fatalf("upstream hits = %d, want %d", front.upstreamHits, wantUpstream) + } if !tc.wantHold { if reason != "" || len(front.labels) != 0 || len(front.comments) != 0 { t.Fatalf("reason = %q, labels = %v, comments = %d; want no hold", reason, front.labels, len(front.comments)) diff --git a/src/pkg/github/automerge/automerge_stage_dco.go b/src/pkg/github/automerge/automerge_stage_dco.go index 4a540cfb0d..9729023de2 100644 --- a/src/pkg/github/automerge/automerge_stage_dco.go +++ b/src/pkg/github/automerge/automerge_stage_dco.go @@ -7,6 +7,7 @@ import ( "strings" gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -104,18 +105,10 @@ func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key str } } } - opts := &gh.ListOptions{PerPage: 100} - var all []*gh.RepositoryCommit - for page := 0; page < stageDCOMaxPages; page++ { - commits, resp, err := c.gh.PullRequests.ListCommits(ctx, obs.Owner, obs.Repo, obs.Number, opts) - if err != nil { - return dcoStats{}, fmt.Errorf("listing commits for %s#%d: %w", obs.Display, obs.Number, err) - } - all = append(all, commits...) - if resp == nil || resp.NextPage == 0 { - break - } - opts.Page = resp.NextPage + // A list cut off at GitHub's cap is judged as read, as before. + all, _, err := hgithub.ListPRRepositoryCommits(ctx, c.gh, obs.Owner, obs.Repo, obs.Number) + if err != nil { + return dcoStats{}, err } return dcoCommitStatsDetailedForAuthor(all, c.transport.AppBotLogin(), obs.Author), nil } diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index d893d090d5..9765f5ec64 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -774,6 +774,22 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 0, nil } } + // One entry comment per PR and stage, edited in place + // (hivecommons/hive#16433): a later head or cause rewrites the hive's + // existing 085 / 090 comment with an "updated" line instead of posting + // another copy, which emailed everyone again to say the same thing. + if existing := c.findOwnEntryComment(ctx, obs, stagelabels.EntryCommentMarker(route.Stage)); existing != nil { + updated := stagelabels.EntryCommentUpdated(body, c.now()) + // Rewrites the comment the gate admitted when it was posted; an edit notifies nobody. + if _, _, err := c.gh.Issues.EditComment(ctx, obs.Owner, obs.Repo, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(updated)}); err != nil { // writeback:gated + c.warn("stage labels: entry comment edit failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) + return 0, err + } + store.MarkEntryCommentedCause(key, obs.HeadSHA, cause) + store.MarkEntryCommentedDecisionKey(key, decisionKey) + c.info("stage labels: entry comment updated in place", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "reasons", route.Reasons) + return 0, nil + } if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { c.warn("stage labels: entry comment failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) return 0, err @@ -784,6 +800,33 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 1, nil } +// findOwnEntryComment returns the hive's existing entry comment carrying +// marker on the PR, or nil. Only a comment the hive's App login wrote +// counts: anyone can type the marker, and the hive must never edit a +// stranger's comment. A list failure reads as "none", so the entry is +// posted rather than lost. +func (c *Engine) findOwnEntryComment(ctx context.Context, obs stageObservation, marker string) *gh.IssueComment { + if marker == "" || c == nil || c.transport == nil { + return nil + } + app := normalizeBotLogin(c.transport.AppBotLogin()) + if app == "" { + return nil + } + comments, err := c.listIssueComments(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + c.warn("stage labels: could not list comments for the entry upsert", "repo", obs.Display, "pr", obs.Number, "error", err) + return nil + } + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || normalizeBotLogin(cm.GetUser().GetLogin()) != app { + continue + } + return cm + } + return nil +} + // workflowApprovalSnippet appends the self-contained ok-to-test workflow, // rendered for this hive's own App login, to the 085 entry when held runs // stayed `action_required` past the grace period (the repository most likely @@ -822,12 +865,12 @@ func (c *Engine) fixDispatchStatusFor(obs stageObservation, pass *stageengine.PR // fixerExhaustedRoute is the 085 route (and so the entry comment, once per // head) for a hive PR whose fixer gave up (hivecommons/hive#15744). -func (c *Engine) fixerExhaustedRoute(obs stageObservation, fixer review.FixDispatchStatus) stagelabels.Route { +func (c *Engine) fixerExhaustedRoute(obs stageObservation, fixer review.FixDispatchStatus, reauthoredFrom int) stagelabels.Route { v := obs.Detail.Verdict if !obs.Detail.VerdictKnown { v = c.contributorLaneVerdictFor(obs.Owner+"/"+obs.Repo, obs.Number, obs.HeadSHA) } - return stagelabels.FixerExhaustedRoute(obs.HeadSHA, fixer.Attempts, fixerExhaustedSummary(v, obs.LaneReason)) + return stagelabels.FixerExhaustedRoute(obs.HeadSHA, fixer.Attempts, fixerExhaustedSummary(v, obs.LaneReason), reauthoredFrom) } // fixerExhaustedSummary is the reviewer's one-line reason the fixer kept diff --git a/src/pkg/github/automerge/automerge_stage_human_test.go b/src/pkg/github/automerge/automerge_stage_human_test.go index 097f05025e..e92034179c 100644 --- a/src/pkg/github/automerge/automerge_stage_human_test.go +++ b/src/pkg/github/automerge/automerge_stage_human_test.go @@ -876,3 +876,61 @@ func TestApplyStageLabelsHumanPRNeverAskedSupersededCloser(t *testing.T) { t.Fatalf("calls=%v result=%+v added=%v", spy.calls, res, api.added) } } + +// TestEntryCommentUpsertsExistingComment: when the hive's 085 entry comment +// is still on the PR, a re-entry on a new head rewrites it in place with an +// "Updated" line instead of posting a second copy (hivecommons/hive#16433). +// A comment carrying the marker but written by someone else is left alone. +func TestEntryCommentUpsertsExistingComment(t *testing.T) { + api := &stageAPI{labels: map[string]string{}, statefulComments: true} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)} + verdict := &ContributorLaneVerdict{Configured: true, Verdict: "requires_human"} + e, store := humanStageEngine(t, srv.URL, clock, verdict, 0) + ctx := context.Background() + sweep := func(head string, labels ...string) { + t.Helper() + api.reset() + pr := stagePR(14, labels...) + pr.Head.SHA = gh.Ptr(head) + pr.Body = gh.Ptr("Fixes the widget.\n\n— hive: backend=pi model=gpt-6\n") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonNoVerdict, false, nil) + e.noteStageVerdict("acme", "widget", 14, *verdict) + e.noteStageRole("acme", "widget", 14, stagelabels.RoleContributor) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + } + key := stageKey("acme", "widget", 14) + + // A stranger's comment carrying the marker must never be edited. + api.issueComments = map[int][]map[string]any{14: {{"id": int64(5), "body": stagelabels.DecisionCommentMarker + "\nforged", "user": map[string]any{"login": "mallory"}}}} + + sweep("sha", "role/contributor", "author/human", "stage/050-review-pending") + if len(api.comments) != 1 || !strings.HasPrefix(api.comments[0], stagelabels.DecisionCommentMarker) { + t.Fatalf("first entry comments = %q", api.comments) + } + if len(api.commentEdits) != 0 { + t.Fatalf("a stranger's marker comment was edited: %q", api.commentEdits) + } + + store.Observe(key, stagelabels.ReviewPending, "review-requested") + clock.advance(time.Hour) + sweep("sha2", "role/contributor", "author/human", "stage/050-review-pending") + if got := stageOf(t, store, 14); got != stagelabels.NeedsDecision { + t.Fatalf("stage=%v want 085", got) + } + if len(api.comments) != 0 { + t.Fatalf("new head must edit the existing entry comment, not post another: %q", api.comments) + } + if len(api.commentEdits) != 1 || !strings.HasPrefix(api.commentEdits[0], stagelabels.DecisionCommentMarker) || !strings.Contains(api.commentEdits[0], "<sub>Updated 2026-10-20 13:00 UTC.</sub>") { + t.Fatalf("entry comment edits = %q", api.commentEdits) + } + if rec, _ := store.Get(key); !rec.EntryCommented || rec.EntryCommentedHead != "sha2" { + t.Fatalf("record after the in-place update: %+v", rec) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 0bb065ba68..85abb954ba 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -992,6 +992,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) obs.Reason = replacement.Reason } fixer, fixerKnown := c.fixDispatchStatusFor(obs, pass) + var reauthored reauthorRecord pass.FixerExcluded = fixerKnown && fixer.Excluded() if replacement, ok := stageengine.PreserveStageOnStaleDecisionAnswer(prevRec, hadPrev, obs, verdict, pass.FixerExcluded); ok { verdict = replacement @@ -1245,16 +1246,39 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) } if !verdict.Terminal && verdict.Stage == fixingStage(obs) && fixerKnown && fixer.Exhausted() { // The hive's own PR whose fix dispatcher refuses another - // fix (re-engagement cap spent, hivecommons/hive#15744): - // a person decides (re-author / hand over / close as not - // planned) instead of the row reading "Fixing" with - // nobody on it for hours (#15308). - verdict.Stage = stagelabels.NeedsDecision - verdict.Rank = stageRankOwned - obs.Reason = stagelabels.FixerExhaustedReason(fixer.Attempts) - pass.FixerExhausted = fixer.Attempts - route := c.fixerExhaustedRoute(obs, fixer) - obs.Route = &route + // fix (re-engagement cap spent, hivecommons/hive#15744). + // First time for its issue: the hive re-authors it itself + // (closes it as superseded, a fresh PR opens from the + // current base) — a hive agent's PR needs no re-author + // pill. Already re-authored once, or no issue to redo: + // a person decides (give direction / hand over / close + // as not planned) instead of the row reading "Fixing" + // with nobody on it for hours (#15308). + var target reauthorTarget + if prev, ok := store.Get(key); ok && prev.Reauthored() { + target = reauthorTarget{Issue: prev.ReauthorIssue} + } else { + target = c.autoReauthorTarget(ctx, store, obs) + } + if target.eligible() && policy.Adoption && !obs.Merged { + n, noted, err := c.reauthorExhaustedHivePR(ctx, store, key, obs, fixer, target.Issue, now) + result.Comments += n + if err != nil && firstErr == nil { + firstErr = err + } + if err == nil { + reauthored = reauthorRecord{issue: target.Issue, attempts: fixer.Attempts, noted: noted} + } + obs.Reason = stagelabels.ReauthoringReason(target.Issue) + pass.Reauthoring = target.Issue + } else { + verdict.Stage = stagelabels.NeedsDecision + verdict.Rank = stageRankOwned + obs.Reason = stagelabels.FixerExhaustedReason(fixer.Attempts) + pass.FixerExhausted = fixer.Attempts + route := c.fixerExhaustedRoute(obs, fixer, max(target.PriorPR, 0)) + obs.Route = &route + } } if step := c.sharedCIRecoveryUnauthorized(ctx, obs); step != "" && verdict.Stage != stagelabels.None { pass.RecoveryUnauthorized = step @@ -1265,6 +1289,12 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) obs.Route = &route } tr = store.Observe(key, verdict.Stage, obs.Reason) + if reauthored.issue > 0 { + store.MarkReauthored(key, reauthored.issue, obs.HeadSHA, reauthored.attempts, now) + if reauthored.noted { + store.MarkReauthorNoted(key) + } + } // hivecommons/hive#12502: remember the author so the dashboard can // list "PRs returned to this contributor" from the store alone. store.NoteAuthor(key, obs.Author) diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index d55ec2c08b..b3c34ac9fa 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -36,7 +36,9 @@ type stageAPI struct { creates []string lists int gets int - url string + // issueGets counts GET /issues/N per number. + issueGets map[int]int + url string // commits is what GET /pulls/N/commits answers (one message per // commit); a PR not listed has no commits, so its DCO state stays // unknown and the test's label expectations are unaffected. @@ -121,6 +123,10 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/issues/") && !strings.Contains(strings.TrimPrefix(path, "/repos/acme/widget/issues/"), "/"): n, _ := strconv.Atoi(strings.TrimPrefix(path, "/repos/acme/widget/issues/")) api.gets++ + if api.issueGets == nil { + api.issueGets = map[int]int{} + } + api.issueGets[n]++ stagePRTruthMu.Lock() labels := make([]map[string]string, 0) for _, l := range stagePRTruth[n] { diff --git a/src/pkg/github/automerge/pr_approve_command_test.go b/src/pkg/github/automerge/pr_approve_command_test.go index fd7edb244d..3324a046c6 100644 --- a/src/pkg/github/automerge/pr_approve_command_test.go +++ b/src/pkg/github/automerge/pr_approve_command_test.go @@ -128,9 +128,11 @@ func TestPRApproveReplyPinOnlyMatchesSweep(t *testing.T) { name, patch string trusted []string commits []*gh.RepositoryCommit + tagSHA string // upstream tags/v5 target; "" means testPinNewSHA want string }{ {name: "trusted pure pin", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: verifiedHead, want: "releases that hold on the current head"}, + {name: "upstream tag points elsewhere", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: verifiedHead, tagSHA: strings.Repeat("c", 40), want: "requires a person to merge manually"}, {name: "untrusted author", patch: pin, trusted: []string{"someone-else"}, want: "requires a person to merge manually"}, {name: "missing patch", trusted: []string{testHiveAppBotLogin}, want: "requires a person to merge manually"}, {name: "head commit pushed by another login", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: []*gh.RepositoryCommit{ @@ -160,6 +162,12 @@ func TestPRApproveReplyPinOnlyMatchesSweep(t *testing.T) { t.Errorf("commit list read for a diff the classifier refuses") } json.NewEncoder(w).Encode(tc.commits) + case "/repos/actions/checkout/git/ref/tags/v5": + sha := tc.tagSHA + if sha == "" { + sha = testPinNewSHA + } + json.NewEncoder(w).Encode(testPinRef("commit", sha)) default: t.Errorf("unexpected read: %s", r.URL.Path) w.WriteHeader(http.StatusNotFound) diff --git a/src/pkg/github/ci_failure_signal.go b/src/pkg/github/ci_failure_signal.go index 52fe9d2792..ea74c33464 100644 --- a/src/pkg/github/ci_failure_signal.go +++ b/src/pkg/github/ci_failure_signal.go @@ -250,19 +250,74 @@ func (s *CIFailureSignalStore) filter(keep func(CIFailureSignal) bool) []CIFailu // Forget drops every signal for repo#number (the PR merged, closed, or its // head moved on to a new SHA that is not this one). func (s *CIFailureSignalStore) Forget(repo string, number int) { + canon := canonicalPRDetailRepo(repo) + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == canon && sig.Number == number + }) +} + +func (s *CIFailureSignalStore) forgetMatching(match func(CIFailureSignal) bool) { if s == nil { return } s.mu.Lock() defer s.mu.Unlock() - canon := canonicalPRDetailRepo(repo) for k, sig := range s.signals { - if k.repo == canon && sig.Number == number { + if match(sig) { delete(s.signals, k) } } } +// forgetGreenHead removes only this observed head, preserving failures from a +// newer head that may have arrived while enrichment was in progress. +func (s *CIFailureSignalStore) forgetGreenHead(repo string, number int, head string) { + canon := canonicalPRDetailRepo(repo) + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == canon && sig.Number == number && strings.EqualFold(sig.HeadSHA, head) + }) +} + +// forgetResolvedWebhook drops resolved checks even when the detail cache has +// already been invalidated by the failure delivery. A suite success only +// resolves that suite's signal; other producers may still have failing checks. +func (s *CIFailureSignalStore) forgetResolvedWebhook(event string, p webhookEventPayload) { + repo := canonicalPRDetailRepo(p.Repository.FullName) + if hint := webhookItemHint(event, p); hint != nil && hint.IsPR && hint.Closed() { + s.Forget(repo, hint.Number) + return + } + if event == "pull_request" && p.Action == "synchronize" && p.PullRequest != nil && p.PullRequest.Head.SHA != "" { + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == repo && sig.Number == p.PullRequest.Number && !strings.EqualFold(sig.HeadSHA, p.PullRequest.Head.SHA) + }) + return + } + head, check := "", "" + switch event { + case "check_run": + if p.CheckRun != nil && p.Action == "completed" && p.CheckRun.Conclusion == "success" { + head, check = p.CheckRun.HeadSHA, p.CheckRun.Name + } + case "check_suite": + if p.CheckSuite != nil && p.Action == "completed" && p.CheckSuite.Conclusion == "success" { + head, check = p.CheckSuite.HeadSHA, "check suite" + if app := strings.TrimSpace(p.CheckSuite.App.Name); app != "" { + check = app + " check suite" + } + } + case "status": + if p.State == "success" { + head, check = p.SHA, p.Context + } + } + if strings.TrimSpace(head) != "" { + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == repo && strings.EqualFold(sig.HeadSHA, strings.TrimSpace(head)) && strings.TrimSpace(sig.Check) == strings.TrimSpace(check) + }) + } +} + // Snapshot is the /api/status view. func (s *CIFailureSignalStore) Snapshot() CIFailureSignalsStatus { if s == nil { diff --git a/src/pkg/github/ci_failure_signal_test.go b/src/pkg/github/ci_failure_signal_test.go index 9e5de4a4a8..9791575107 100644 --- a/src/pkg/github/ci_failure_signal_test.go +++ b/src/pkg/github/ci_failure_signal_test.go @@ -1,6 +1,7 @@ package github import ( + "fmt" "log/slog" "net/http" "net/http/httptest" @@ -11,6 +12,47 @@ import ( gh "github.com/google/go-github/v72/github" ) +func TestHandleWebhookEvent_ForgetsResolvedCIFailures(t *testing.T) { + for _, tc := range []struct { + name, event, content string + remaining int + }{ + {"green check", "check_run", `"action":"completed","check_run":{"head_sha":"old","name":"build","conclusion":"success"}`, 4}, + {"green status", "status", `"sha":"old","context":"build","state":"success"`, 4}, + {"green suite", "check_suite", `"action":"completed","check_suite":{"head_sha":"old","conclusion":"success","app":{"name":"Actions"}}`, 4}, + {"pending", "status", `"sha":"old","context":"build","state":"pending"`, 5}, + {"closed", "pull_request", `"action":"closed","pull_request":{"number":7,"state":"closed"}`, 1}, + {"merged", "pull_request", `"action":"closed","pull_request":{"number":7,"merged":true}`, 1}, + {"new head", "pull_request", `"action":"synchronize","pull_request":{"number":7,"head":{"sha":"new"}}`, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := setupWebhookCacheTest(t) + t.Cleanup(ResetCIFailureSignalsForTest(nil)) + t.Cleanup(ResetCIEvidenceForTest(nil)) + store := CIFailureSignals() + for _, sig := range []CIFailureSignal{ + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "build"}, + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "lint"}, + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "Actions check suite"}, + {Repo: "org/repo", Number: 7, HeadSHA: "new", Check: "build"}, + {Repo: "org/repo", Number: 8, HeadSHA: "other", Check: "build"}, + } { + store.Record(sig) + } + payload := []byte(fmt.Sprintf(`{"repository":{"full_name":"org/repo"},%s}`, tc.content)) + if _, err := c.HandleWebhookEvent(tc.event, payload); err != nil { + t.Fatal(err) + } + if got := store.Snapshot().Count; got != tc.remaining { + t.Fatalf("signals remaining=%d, want %d", got, tc.remaining) + } + if got := store.ForPR("org/repo", 8); len(got) != 1 { + t.Fatalf("unrelated PR signals changed: %+v", got) + } + }) + } +} + func TestWebhookCIFailure_EventsAndConclusions(t *testing.T) { cases := []struct { name string @@ -74,14 +116,7 @@ func TestWebhookCIFailure_EventsAndConclusions(t *testing.T) { } } -type checkRunPayload = struct { - HeadSHA string `json:"head_sha"` - Name string `json:"name"` - Conclusion string `json:"conclusion"` - DetailsURL string `json:"details_url"` - HTMLURL string `json:"html_url"` - PullRequests []webhookPRRef `json:"pull_requests"` -} +type checkRunPayload = webhookCheckRunPayload type checkSuitePayload = struct { HeadSHA string `json:"head_sha"` diff --git a/src/pkg/github/claimed_by_label.go b/src/pkg/github/claimed_by_label.go index 1d3b080403..8595c2746b 100644 --- a/src/pkg/github/claimed_by_label.go +++ b/src/pkg/github/claimed_by_label.go @@ -92,23 +92,45 @@ func (c *Client) humanClaimReleased(ctx context.Context, owner, repo string, num return false, err } var bodies []string + // The claim ledger (claims.LedgerMarker) is one comment rewritten per + // transition: once released it carries only the release marker, the + // human claim it ended no longer appears anywhere. A ledger whose + // current state is a human release is a released human claim. + ledgerReleasedHuman := false for _, comment := range comments { if !c.isTrustedAppBotCommentAuthor(comment) { continue } body := comment.GetBody() - if _, ok := issueclaim.ParseReleaseMarker(body); ok { + if rel, ok := issueclaim.ParseReleaseMarker(body); ok { bodies = append(bodies, body) + if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = humanClaimKind(rel.Kind) + } + continue + } + marker, ok := issueclaim.ParseMarker(body) + if !ok { continue } - if marker, ok := issueclaim.ParseMarker(body); ok && - (strings.EqualFold(marker.Kind, string(claims.KindHuman)) || - strings.EqualFold(marker.Kind, string(claims.KindContributor)) || strings.EqualFold(marker.Kind, string(claims.KindExternal))) { + if humanClaimKind(marker.Kind) { bodies = append(bodies, body) + } else if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = claims.LedgerHumanReleased(body) } } latest, found := issueclaim.Latest(bodies, 0) - return found && latest.Released, nil + if !found { + return ledgerReleasedHuman, nil + } + return latest.Released, nil +} + +// humanClaimKind reports whether kind names a human principal: a person, a +// relay contributor or an external bot acting for one. +func humanClaimKind(kind string) bool { + return strings.EqualFold(kind, string(claims.KindHuman)) || + strings.EqualFold(kind, string(claims.KindContributor)) || strings.EqualFold(kind, string(claims.KindExternal)) } // RemoveClaimedByLabel removes the claimed-by label(s) derived from claim: diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 20ba19c925..db728bbea2 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -65,6 +65,10 @@ type Client struct { graphQLPRBatchEnabled func() bool graphQLPRBatchPageSize func() int prBatchMu sync.Mutex + // ciRefetch coalesces the check-run re-reads CI webhook deliveries ask + // for on heads no listing has covered (webhook_ci_evidence.go). + ciRefetchOnce sync.Once + ciRefetch *ciRefetcher prBatchCheckRuns map[prBatchCheckRunKey][]*gh.CheckRun prBatchCheckObservedAt map[prBatchCheckRunKey]time.Time prBatchReviews map[string]map[int]prReviewState @@ -533,6 +537,20 @@ type Client struct { // issues:write) still surface within ~an hour instead of never. Guarded by // advisoryMu. advisoryDigestSkips map[string]int + // advisoryDigestAnchors memoizes, per "owner/repo#issue", the ID of the + // App-authored digest comment the last successful write landed on + // (#16439). It is the pin the digest returns to when a foreign-authored + // digest comment sits newer on the issue, and the key for the per-anchor + // last-written material fingerprint in advisoryDigestAnchorHashes, which + // lets an unchanged re-render skip the PATCH even when the listed body is + // stale. Guarded by advisoryMu. + advisoryDigestAnchors map[string]int + advisoryDigestAnchorHashes map[string]string + // advisoryForeignDigestWarned records, per "owner/repo#issue", that the + // "digest comment not authored by this App" condition has already been + // logged at Warn in this process; later cycles log it at Debug (#16439). + // Guarded by advisoryMu. + advisoryForeignDigestWarned map[string]bool // hiveIdentity records which accounts count as "this hive" for the // self-authorization gate (pr_self_authorization.go, #5117). It is optional // — the gate recognises the App bot without it — and exists so an issue @@ -2675,6 +2693,12 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { incidents := map[string]bool{} for i := range prs { reported := c.enrichPRCI(ctx, &prs[i]) + // Unreported checks may be workflow runs waiting on GitHub's + // approve-workflows gate (dependabot, forks); only a pending head + // pays for the extra listing (hivecommons/hive#16599). + if prs[i].CIStatus == "pending" && prs[i].CIActivity != nil { + prs[i].CIActivity.WorkflowApproval = c.workflowRunsAwaitingApproval(ctx, prs[i].Repo, prs[i].HeadSHA) + } if prs[i].CIStatus == "failure" { if texts, ok := c.redPRCommentTexts(ctx, &prs[i]); ok { prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], texts, incidents) @@ -2683,6 +2707,14 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { } } facts.attach(ctx, &prs[i], reported) + // The listing is the head's complete observation; checks delivered + // by webhook since then are laid over it (hivecommons/hive#16521). + owner, name := c.splitRepo(prs[i].Repo) + if prs[i].CIStatus == "success" { + CIFailureSignals().forgetGreenHead(owner+"/"+name, prs[i].Number, prs[i].HeadSHA) + } + sharedCIEvidence().recordListed(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) + prs[i].CIActivity = sharedCIEvidence().merged(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) } c.enrichBaseBranchRed(ctx, prs) } @@ -4977,6 +5009,10 @@ type RepoWorkPR struct { Reason string `json:"reason,omitempty"` // BaseRef is the target branch, retained for the covering-PR chip. BaseRef string `json:"base_ref,omitempty"` + // HeadSHA is the PR's head commit from the list payload, so the activity + // monitor can match webhook-delivered CI evidence to a sidelined row + // (hivecommons/hive#16521). + HeadSHA string `json:"head_sha,omitempty"` // LinkedIssues mirrors PullRequest.LinkedIssues so a sidelined PR can // still stand under the issue its `Fixes #N` names in the activity // monitor. Stamped by EnrichReviewSignalsAndWorkPRs, not by the @@ -5008,6 +5044,7 @@ func (c *Client) repoWorkPR(repo string, pr *gh.PullRequest, labels []string, hi UpdatedAt: pr.GetUpdatedAt().Time, URL: pr.GetHTMLURL(), BaseRef: prBaseRef(pr), + HeadSHA: prHeadSHA(pr), Bucket: bucket, Reason: reason, // The list payload carries the body, so the soft issue links cost diff --git a/src/pkg/github/coverage90_test.go b/src/pkg/github/coverage90_test.go index 321c0ff0ed..1a951e9728 100644 --- a/src/pkg/github/coverage90_test.go +++ b/src/pkg/github/coverage90_test.go @@ -159,6 +159,10 @@ func TestEnrichCIStatus_ActionRequired(t *testing.T) { } func TestEnrichCIStatus_AllDoneSuccess(t *testing.T) { + t.Cleanup(ResetCIFailureSignalsForTest(nil)) + store := CIFailureSignals() + store.Record(CIFailureSignal{Repo: "org/repo", Number: 1, HeadSHA: "abc123", Check: "build"}) + store.Record(CIFailureSignal{Repo: "org/repo", Number: 1, HeadSHA: "new-head", Check: "build"}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]interface{}{ "total_count": 1, @@ -175,6 +179,9 @@ func TestEnrichCIStatus_AllDoneSuccess(t *testing.T) { if prs[0].CIStatus != "success" { t.Errorf("CIStatus = %q, want success", prs[0].CIStatus) } + if remaining := store.ForPR("org/repo", 1); len(remaining) != 1 || remaining[0].HeadSHA != "new-head" { + t.Fatalf("green enrichment must forget only the observed head: %+v", remaining) + } } func TestEnrichCIStatus_StillRunning(t *testing.T) { diff --git a/src/pkg/github/issue_marker_comment.go b/src/pkg/github/issue_marker_comment.go new file mode 100644 index 0000000000..cc7f926e0c --- /dev/null +++ b/src/pkg/github/issue_marker_comment.go @@ -0,0 +1,77 @@ +package github + +import ( + "context" + "fmt" + "strings" + + gh "github.com/google/go-github/v72/github" +) + +// IssueMarkerCommentResult reports what EditIssueMarkerComment did. +type IssueMarkerCommentResult struct { + // Found is set when a comment carrying the marker already existed; + // Previous is its body before the edit. + Found bool + Previous string + // Created is set when the body was posted as a new comment. + Created bool + // Edited is set when the existing comment was rewritten. + Edited bool +} + +// EditIssueMarkerComment finds the hive's own comment on repo#number that +// carries marker, asks render for the body that should replace it (render +// receives the previous body, or "" when none exists) and edits it in +// place; when no such comment exists the rendered body is posted as a new +// comment through the per-issue comment budget. An empty rendered body is +// a no-op, as is an unchanged one. +// +// Editing notifies nobody, which is the point: the claim ledger +// (hivecommons/hive#16433) replaces one comment per claim transition with +// one comment per issue. Only a comment one of the hive's own accounts +// wrote is edited; when the hive cannot name its accounts, any author is +// accepted, the same fallback the sentinel's marker reads use. +func (c *Client) EditIssueMarkerComment(ctx context.Context, repo string, number int, marker string, render func(previous string) string) (IssueMarkerCommentResult, error) { + if c == nil { + return IssueMarkerCommentResult{}, ErrNoGitHubClient + } + if render == nil { + return IssueMarkerCommentResult{}, fmt.Errorf("editing marker comment on %s#%d: no renderer", repo, number) + } + owner, repoName := c.splitRepo(repo) + comments, err := c.listIssueComments(ctx, owner, repoName, number) + if err != nil { + return IssueMarkerCommentResult{}, err + } + var existing *gh.IssueComment + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || !c.markerAuthorTrusted(cm.GetUser()) { + continue + } + existing = cm + break + } + if existing == nil { + body := render("") + if strings.TrimSpace(body) == "" { + return IssueMarkerCommentResult{}, nil + } + if err := c.CreateIssueCommentBudgeted(ctx, owner+"/"+repoName, number, body); err != nil { + return IssueMarkerCommentResult{}, err + } + return IssueMarkerCommentResult{Created: true}, nil + } + res := IssueMarkerCommentResult{Found: true, Previous: existing.GetBody()} + body := render(res.Previous) + if strings.TrimSpace(body) == "" || body == res.Previous { + return res, nil + } + // Rewrites a comment the hive already owns; an edit notifies nobody. + if _, _, err := c.client.Issues.EditComment(ctx, owner, repoName, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return res, fmt.Errorf("editing marker comment on %s/%s#%d: %w", owner, repoName, number, err) + } + c.noteCommentEdited() + res.Edited = true + return res, nil +} diff --git a/src/pkg/github/issue_marker_comment_test.go b/src/pkg/github/issue_marker_comment_test.go new file mode 100644 index 0000000000..04a9637a24 --- /dev/null +++ b/src/pkg/github/issue_marker_comment_test.go @@ -0,0 +1,88 @@ +package github + +import ( + "context" + "strings" + "testing" +) + +// The first write creates the marker comment; later writes edit it in +// place, hand the renderer the previous body, and skip the edit when the +// renderer returns the same or an empty body. +func TestEditIssueMarkerCommentCreatesThenEdits(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := testClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + ctx := context.Background() + const marker = "<!-- hive:test-ledger -->" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("first render got previous %q", prev) + } + return marker + "\nv1" + }) + if err != nil || !res.Created || res.Found || res.Edited { + t.Fatalf("first write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if !strings.HasSuffix(prev, "v1") { + t.Fatalf("second render got previous %q", prev) + } + return marker + "\nv2" + }) + if err != nil || !res.Found || !res.Edited || res.Created { + t.Fatalf("second write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { return prev }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("unchanged body must not edit: %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return " " }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("empty body must not edit: %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 1 || len(s.comments) != 1 { + t.Fatalf("creates=%d edits=%d comments=%d, want 1/1/1", s.creates, s.edits, len(s.comments)) + } + if got := s.comments[0]["body"]; got != marker+"\nv2" { + t.Fatalf("comment body = %q", got) + } +} + +// A marker comment by someone other than the hive is never edited: the +// hive posts its own instead. An empty first render posts nothing. +func TestEditIssueMarkerCommentIgnoresForeignAuthorAndEmptyBody(t *testing.T) { + s := &statusCommentServer{} + s.comments = append(s.comments, map[string]any{"id": 9, "body": "<!-- hive:test-ledger -->\nforged", "user": map[string]any{"login": "mallory", "type": "User"}}) + srv := s.start(t) + c := testClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + ctx := context.Background() + const marker = "<!-- hive:test-ledger -->" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "" }) + if err != nil || res.Found || res.Created { + t.Fatalf("empty first render = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("forged comment must not be offered as previous: %q", prev) + } + return marker + "\nours" + }) + if err != nil || !res.Created { + t.Fatalf("write past forged comment = %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 0 { + t.Fatalf("creates=%d edits=%d, want 1/0", s.creates, s.edits) + } + + if _, err := (*Client)(nil).EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "x" }); err == nil { + t.Fatal("nil client must error") + } + if _, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, nil); err == nil { + t.Fatal("nil renderer must error") + } +} diff --git a/src/pkg/github/issue_request_label.go b/src/pkg/github/issue_request_label.go index b58311a2a0..df0525eaf0 100644 --- a/src/pkg/github/issue_request_label.go +++ b/src/pkg/github/issue_request_label.go @@ -257,34 +257,41 @@ func verifiedOpenResendHint(add, remove, bad []string) string { // the agent what to do instead: follow the decision, or — when it reserves // the work for people — add `needs-human` and unclaim. A lookup failure is // returned so the caller retries rather than reading "unknown" as allowed. -func (c *Client) reparkDecisionRefusal(ctx context.Context, repo string, number int, add []string) (string, bool, error) { +// +// superseded is true when the park is allowed through on that newer, +// different decision: the issue still wears `approved-direction` for the +// old one, and the stage engine must read the ack as stale +// (FactSink.ReparkedOnNewDecision) rather than as a standing decision the +// agent is standing down on (hivecommons/hive#16579), or the park never +// lands. +func (c *Client) reparkDecisionRefusal(ctx context.Context, repo string, number int, add []string) (reason string, refused, superseded bool, err error) { if number <= 0 || !containsDecisionParkLabel(add, c.needsDecisionLabel()) { - return "", false, nil + return "", false, false, nil } owner, name := c.splitRepo(repo) issue, _, err := c.client.Issues.Get(ctx, owner, name, number) if err != nil { - return "", false, fmt.Errorf("checking issue park labels: %w", err) + return "", false, false, fmt.Errorf("checking issue park labels: %w", err) } labels := extractLabels(issue.Labels) if !labelPresent(labels, HumanAckLabel) { - return "", false, nil + return "", false, false, nil } comments, err := c.listIssueComments(ctx, owner, name, number) if err != nil { - return "", false, err + return "", false, false, err } decision, at, ok := c.lastRecordedUnparkDecision(comments) if !ok { - return "", false, nil + return "", false, false, nil } if hasNewerDifferentDecisionCommand(comments, at, decision) { - return "", false, nil + return "", false, true, nil } return fmt.Sprintf("a maintainer already decided on %s#%d (recorded by Hive: %q) and `%s` is applied; "+ "re-parking it on `%s` asks for a decision that has been given. Follow the decision. "+ "If it reserves the work for people, add `%s` through this relay and `/unclaim` instead.", - repo, number, decision, HumanAckLabel, c.needsDecisionLabel(), issueNeedsHumanLabel), true, nil + repo, number, decision, HumanAckLabel, c.needsDecisionLabel(), issueNeedsHumanLabel), true, false, nil } func containsDecisionParkLabel(labels []string, configured string) bool { diff --git a/src/pkg/github/issue_request_label_test.go b/src/pkg/github/issue_request_label_test.go index df2ad3491c..3ed557d1cf 100644 --- a/src/pkg/github/issue_request_label_test.go +++ b/src/pkg/github/issue_request_label_test.go @@ -660,7 +660,9 @@ func TestReservedLabelRefusal_ResendHintOnlyForVerifiedOpenWithHiveRemovals(t *t // With `approved-direction` applied and Hive's own un-park reply recording // the decision, the re-park is refused and the agent is told to add // `needs-human` and unclaim instead. A newer `/hive decision` with different -// text means direction is changing, and the park goes through. +// text means direction is changing, and the park goes through — as a +// ReparkedOnNewDecision fact, so the stale ack does not read as a standing +// decision that would hold the issue out of 045 (hivecommons/hive#16579). func TestIssueRequestWatcher_LabelRefusesReparkOnRecordedDecision(t *testing.T) { const decision = "Agents stand down; owner/Console owners handle this" reply := unparkWireComment{ @@ -696,9 +698,15 @@ func TestIssueRequestWatcher_LabelRefusesReparkOnRecordedDecision(t *testing.T) resp := readIssueResultFile(t, reqPath) if tc.wantAdded { - if !resp.OK || len(rec.added[12680]) != 1 { + if !resp.OK || len(rec.added[12680]) != 1 || rec.added[12680][0] != NeedsDecisionStageLabel { t.Fatalf("expected the park to go through, resp=%+v added=%v", resp, rec.added[12680]) } + // Direction is changing, so the old `approved-direction` + // is stale: the park re-derives 045 with it cleared rather + // than standing down on the old decision (#16579). + if got := strings.Join(rec.removed[12680], ","); !strings.Contains(got, HumanAckLabel) { + t.Fatalf("expected the stale %s cleared with the re-park, removed=%v", HumanAckLabel, rec.removed[12680]) + } return } if resp.OK || len(rec.added[12680]) != 0 { @@ -729,11 +737,11 @@ func TestReparkDecisionRefusalRecognizesRetiredDecisionLabels(t *testing.T) { server, _ := newUnparkServer(t, "org", "repo", []unparkWireIssue{issue}, nil) c := newTestClient(t, server, "org", []string{"repo"}) - reason, refused, err := c.reparkDecisionRefusal(context.Background(), "org/repo", 12680, []string{label}) + reason, refused, superseded, err := c.reparkDecisionRefusal(context.Background(), "org/repo", 12680, []string{label}) if err != nil { t.Fatalf("reparkDecisionRefusal: %v", err) } - if !refused || !strings.Contains(reason, "already decided") || !strings.Contains(reason, issueNeedsHumanLabel) { + if !refused || superseded || !strings.Contains(reason, "already decided") || !strings.Contains(reason, issueNeedsHumanLabel) { t.Fatalf("label %q refused=%v reason=%q, want recorded-decision refusal", label, refused, reason) } }) diff --git a/src/pkg/github/issue_request_watcher.go b/src/pkg/github/issue_request_watcher.go index 4e2835db86..8694e44a6c 100644 --- a/src/pkg/github/issue_request_watcher.go +++ b/src/pkg/github/issue_request_watcher.go @@ -766,10 +766,12 @@ func (c *Client) handleOneIssueRequest(ctx context.Context, path string, nowFn f } case "label": // A re-park on a decision a maintainer already gave is refused; a - // failed lookup takes the retry path like the claim gate. + // failed lookup takes the retry path like the claim gate. One let + // through on a newer, different decision is submitted as such so + // the stale `approved-direction` does not read as a standing one. var reason string - var refused bool - reason, refused, err = c.reparkDecisionRefusal(ctx, req.Repo, req.Number, addLabels) + var refused, superseded bool + reason, refused, superseded, err = c.reparkDecisionRefusal(ctx, req.Repo, req.Number, addLabels) if err != nil { break } @@ -804,7 +806,11 @@ func (c *Client) handleOneIssueRequest(ctx context.Context, path string, nowFn f err = c.StageFacts().Unparked(ctx, c.IssueStageRef(req.Repo, req.Number), req.Agent) } if err == nil && parkLabel != "" { - err = c.StageFacts().Parked(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + if superseded { + err = c.StageFacts().ReparkedOnNewDecision(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + } else { + err = c.StageFacts().Parked(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + } if err == nil { err = c.verifyIssueParkLanded(ctx, req.Repo, req.Number, parkLabel) } diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 9f48ae28ec..58ed93c120 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -520,7 +520,11 @@ func (c *Client) tryUnparkIssue(ctx context.Context, displayRepo, owner, repo st if menu.releaseStep != nil || c.issueOwnerStepProposed(issue, comments) { c.rememberIssueOwnerStep(displayRepo, number, menu.releaseStep) } - if !labelDriven { + // A held issue (hivecommons/hive#16591) has nothing open to decide: no + // "What to reply" notice and no prose hint, but every command it does + // get is still answered. + held := isHeldAfterDecision(issueLabelNames(issue.Labels)) + if !labelDriven && !held { if err := c.ensureUnparkNoticeComment(ctx, owner, repo, issue, comments, releasePolicy.enabled); err != nil { return false, err } @@ -610,6 +614,9 @@ func (c *Client) tryUnparkIssue(ctx context.Context, displayRepo, owner, repo st return true, nil case unparkCommandNone: // Prose assent, no command. Say what to type; do not act on it. + if held { + return false, nil + } if err := c.postUnparkReply(ctx, owner, repo, number, candidate.GetID(), unparkProseHintReply); err != nil { return false, err } @@ -792,7 +799,7 @@ func (c *Client) unparkLabelDrivenCommand(ctx context.Context, displayRepo, owne // The engine re-derives the stage from the labels left behind, so a kept // park label (a person's or a lifecycle bot's `needs-human`) re-parks the // issue at the same stage (hivecommons/hive#12715). - stayingStage := unparkStageThatStays(displayRepo, number, labels, removed, stageLabels) + stayingStage := unparkStageThatStays(displayRepo, number, labels, removed, stageLabels, acknowledge) if acknowledge && !labelPresent(labels, HumanAckLabel) { if _, _, err := c.client.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{HumanAckLabel}); err != nil { return false, fmt.Errorf("adding %s to %s/%s#%d: %w", HumanAckLabel, owner, repo, number, err) @@ -831,13 +838,21 @@ func (c *Client) unparkLabelDrivenCommand(ctx context.Context, displayRepo, owne } // unparkStageThatStays returns the stage label among stageLabels that the -// issue still derives once the un-park has removed removed and applied -// approved-direction, or "" when the park lifts. -func unparkStageThatStays(displayRepo string, number int, labels, removed, stageLabels []string) string { +// issue still derives once the un-park has removed removed and, when +// acknowledge is set, applied approved-direction, or "" when the park +// lifts. The ack is only counted when it is really applied: a kept +// `needs-human` withholds it, and the engine reads a plain `needs-human` +// as a 045 park but a `needs-human` beside the ack as held human work +// (hivecommons/hive#16579), so seeding the ack unconditionally would +// misreport a kept park as lifted. +func unparkStageThatStays(displayRepo string, number int, labels, removed, stageLabels []string, acknowledge bool) string { if len(stageLabels) == 0 { return "" } - after := []string{HumanAckLabel} + var after []string + if acknowledge { + after = append(after, HumanAckLabel) + } for _, label := range labels { if !labelPresent(removed, label) && !labelPresent(stageLabels, label) { after = append(after, label) @@ -1741,3 +1756,14 @@ func renderUnparkFixedReply(actor, note string, removed []string) string { b.WriteString("; any `hold` label is left exactly as it was.\n\nIf this was closed by mistake, the reporter or a maintainer can comment `/reopen`.") return b.String() } + +// isHeldAfterDecision reports an issue held after a human decision: +// `needs-human` beside the approval label and without a stage/045 park label. +// Nothing is open to decide on it, so the sweep stops offering `/hive approve` +// / `/hive decision` (hivecommons/hive#16591) while still answering any +// command a maintainer posts. +func isHeldAfterDecision(labels []string) bool { + return hasIssueNeedsHumanLabel(labels) && labelPresent(labels, HumanAckLabel) && + !labelPresent(labels, NeedsDecisionStageLabel) && !labelPresent(labels, legacyIssueNeedsDecisionStageLabel) && + !labelPresent(labels, issueNeedsDecisionLabel) && !labelPresent(labels, issueNeedsDirectionLabel) +} diff --git a/src/pkg/github/issue_unpark_command_test.go b/src/pkg/github/issue_unpark_command_test.go index 60701b91e0..8d77b9429f 100644 --- a/src/pkg/github/issue_unpark_command_test.go +++ b/src/pkg/github/issue_unpark_command_test.go @@ -1419,3 +1419,89 @@ func TestParseUnparkCommandKeepsDecisionTextAfterFirstLine(t *testing.T) { t.Fatalf("single-line decision = %+v", single) } } + +func heldIssue(number int, comments ...unparkWireComment) unparkWireIssue { + issue := parkedIssue(number, comments...) + issue.Labels = []wireLabel{{Name: "needs-human"}, {Name: HumanAckLabel}, {Name: "hold"}} + return issue +} + +func TestIsHeldAfterDecision(t *testing.T) { + if !isHeldAfterDecision([]string{"needs-human", HumanAckLabel}) { + t.Fatal("needs-human + approved-direction without a park stage is held") + } + if isHeldAfterDecision([]string{"needs-human", HumanAckLabel, NeedsDecisionStageLabel}) { + t.Fatal("a stage/045 park label means something is still open to decide") + } + if isHeldAfterDecision([]string{"needs-human"}) { + t.Fatal("needs-human alone is parked, not held") + } + if !hasIssueParkingLabel([]string{"needs-human", HumanAckLabel}) { + t.Fatal("a held issue stays in the sweep so its commands are still answered") + } +} + +func TestSweepIssueUnparkCommandsHeldIssueGetsNoNoticeOrProseHint(t *testing.T) { + issues := []unparkWireIssue{ + heldIssue(61), + heldIssue(62, humanComment(71, "maintainer", "sounds good, go ahead")), + } + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if result.Seen != 2 || len(result.Unparked) != 0 || result.Replies != 0 { + t.Fatalf("seen=%d unparked=%+v replies=%d", result.Seen, result.Unparked, result.Replies) + } + for _, n := range []int{61, 62} { + if len(rec.posted[n]) != 0 { + t.Fatalf("held issue %d must not be re-offered a decision, got %v", n, rec.posted[n]) + } + } + if len(rec.edited) != 0 { + t.Fatalf("no notice to edit on a held issue, got %v", rec.edited) + } +} + +func TestSweepIssueUnparkCommandsHeldIssueStillAnswersDecision(t *testing.T) { + issues := []unparkWireIssue{heldIssue(63, humanComment(72, "maintainer", "/hive decision ship it as is"))} + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(result.Unparked) != 1 || result.Unparked[0].Number != 63 || result.Unparked[0].Decision != "ship it as is" { + t.Fatalf("a /hive decision on a held issue must still be answered, got %+v", result.Unparked) + } + if len(rec.posted[63]) != 1 || !strings.Contains(rec.posted[63][0], "Decision: ship it as is") { + t.Fatalf("expected exactly the acceptance reply, got %v", rec.posted[63]) + } + if strings.Contains(rec.posted[63][0], unparkNoticeMarker) { + t.Fatalf("the notice must not be posted on a held issue: %v", rec.posted[63]) + } + if strings.Contains(strings.Join(rec.removed[63], ","), "hold") { + t.Fatalf("hold must never be removed, got %v", rec.removed[63]) + } +} + +func TestSweepIssueUnparkCommandsHeldIssueStillAnswersHelp(t *testing.T) { + issues := []unparkWireIssue{heldIssue(64, humanComment(73, "maintainer", "/hive help"))} + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if result.Replies != 1 || len(rec.posted[64]) != 1 { + t.Fatalf("expected one help reply, replies=%d posted=%v", result.Replies, rec.posted[64]) + } + if strings.Contains(rec.posted[64][0], unparkNoticeMarker) { + t.Fatalf("the help reply must be the only comment, got %v", rec.posted[64]) + } +} diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index 359676a7c3..5412ec4a31 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -27,6 +27,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "main.(*repoForgeRouter).CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "main.liveTriageCommenter.CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "github.(*Client).UpsertIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, + "github.(*Client).EditIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, "github.(*clientStatusForge).CreateComment": {Class: NotificationClassStatus, Passthrough: true}, "mergelane.(*RESTGitHub).CreateIssueComment": {Class: NotificationClassStatus, Passthrough: true}, "worksource.(*forgeWorkSource).AddComment": {Class: NotificationClassAttention, Passthrough: true}, diff --git a/src/pkg/github/pr_ci_activity.go b/src/pkg/github/pr_ci_activity.go index 9ca1ba6200..52ee5be70b 100644 --- a/src/pkg/github/pr_ci_activity.go +++ b/src/pkg/github/pr_ci_activity.go @@ -21,6 +21,9 @@ type PRCIActivity struct { Checks []PRActivityCheck `json:"checks,omitempty"` StatusesKnown bool `json:"statuses_known"` StatusesObservedAt *time.Time `json:"statuses_observed_at,omitempty"` + // WorkflowApproval names workflow runs on this head that GitHub holds + // behind its approve-workflows gate; nil when none were observed. + WorkflowApproval *PRWorkflowApproval `json:"workflow_approval,omitempty"` } type PRActivityCheck struct { diff --git a/src/pkg/github/pr_commits.go b/src/pkg/github/pr_commits.go index fddb29fd32..1fc937e4bf 100644 --- a/src/pkg/github/pr_commits.go +++ b/src/pkg/github/pr_commits.go @@ -97,22 +97,30 @@ func (c *Client) ListPRCommits(ctx context.Context, repo string, number int) ([] // commits, oldest first, nils dropped — for callers that need the parents, // the git identities, or the signature verification. func (c *Client) listPRRepositoryCommits(ctx context.Context, owner, repoName string, number int) ([]*gh.RepositoryCommit, error) { + out, _, err := ListPRRepositoryCommits(ctx, c.client, owner, repoName, number) + return out, err +} + +// ListPRRepositoryCommits lists a PR's raw commits, oldest first, nils +// dropped, reading at most maxPRCommitPages pages of 100. complete is false +// when GitHub still offered a further page at that cap, so a caller that must +// see every commit can fail closed instead of judging a truncated list. +func ListPRRepositoryCommits(ctx context.Context, client *gh.Client, owner, repoName string, number int) (commits []*gh.RepositoryCommit, complete bool, err error) { opts := &gh.ListOptions{PerPage: 100} - var out []*gh.RepositoryCommit for page := 0; page < maxPRCommitPages; page++ { - commits, resp, err := c.client.PullRequests.ListCommits(ctx, owner, repoName, number, opts) + batch, resp, err := client.PullRequests.ListCommits(ctx, owner, repoName, number, opts) if err != nil { - return nil, fmt.Errorf("listing commits for %s/%s#%d: %w", owner, repoName, number, err) + return nil, false, fmt.Errorf("listing commits for %s/%s#%d: %w", owner, repoName, number, err) } - for _, rc := range commits { + for _, rc := range batch { if rc != nil { - out = append(out, rc) + commits = append(commits, rc) } } - if resp.NextPage == 0 { - break + if resp == nil || resp.NextPage == 0 { + return commits, true, nil } opts.Page = resp.NextPage } - return out, nil + return commits, false, nil } diff --git a/src/pkg/github/pr_commits_test.go b/src/pkg/github/pr_commits_test.go index 545fe3096e..ee2b4fff20 100644 --- a/src/pkg/github/pr_commits_test.go +++ b/src/pkg/github/pr_commits_test.go @@ -81,6 +81,41 @@ func TestListPRCommitsPaginatesWithinBound(t *testing.T) { } } +// The exported lister reports a list cut off at the page cap as incomplete, +// so callers that must see every commit (the pin-only exception) fail closed; +// a list that ends on its own is complete. +func TestListPRRepositoryCommitsReportsTruncationAtCap(t *testing.T) { + for _, tc := range []struct { + name string + endless bool + wantPages int + wantComplete bool + }{ + {name: "ends within cap", wantPages: 2, wantComplete: true}, + {name: "next page past cap", endless: true, wantPages: maxPRCommitPages, wantComplete: false}, + } { + t.Run(tc.name, func(t *testing.T) { + pages := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + pages++ + if tc.endless || pages == 1 { + w.Header().Set("Link", `<http://`+r.Host+r.URL.Path+`?page=`+strconv.Itoa(pages+1)+`>; rel="next"`) + } + json.NewEncoder(w).Encode([]any{map[string]any{"sha": "sha-" + strconv.Itoa(pages)}, nil}) + })) + defer server.Close() + c := NewClientForTest(server.URL, "acme", []string{"widget"}, nil) + got, complete, err := ListPRRepositoryCommits(context.Background(), c.client, "acme", "widget", 7) + if err != nil { + t.Fatalf("ListPRRepositoryCommits: %v", err) + } + if pages != tc.wantPages || len(got) != tc.wantPages || complete != tc.wantComplete { + t.Fatalf("pages=%d commits=%d complete=%v, want %d pages, nils dropped, complete=%v", pages, len(got), complete, tc.wantPages, tc.wantComplete) + } + }) + } +} + func TestListPRCommitsNilClientAndAPIError(t *testing.T) { var nilClient *Client if _, err := nilClient.ListPRCommits(context.Background(), "widget", 7); err == nil { diff --git a/src/pkg/github/pr_status_comment_test.go b/src/pkg/github/pr_status_comment_test.go index b235a3c421..300a72480d 100644 --- a/src/pkg/github/pr_status_comment_test.go +++ b/src/pkg/github/pr_status_comment_test.go @@ -28,6 +28,7 @@ type statusCommentServer struct { creates int edits int deletes []string + reviews int } var issuePathRe = regexp.MustCompile(`^/repos/[^/]+/[^/]+/issues/(\d+)$`) @@ -44,6 +45,9 @@ func (s *statusCommentServer) start(t *testing.T) *httptest.Server { _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "user": map[string]any{"login": "alice", "type": "User"}, "labels": []any{}}) case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments"): _ = json.NewEncoder(w).Encode(s.comments) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/reviews"): + s.reviews++ + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "state": "APPROVED"}) case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): var body map[string]string _ = json.NewDecoder(r.Body).Decode(&body) @@ -264,6 +268,73 @@ func TestReviewRequestWatcher_QuietModeSuppressesNoFindingsReview(t *testing.T) } } +// Quiet mode: a narrated clean review from a plain reviewer lane ("Read the +// tree … Looks correct to me. No findings.") whose verdict approves with no +// findings is suppressed like the one-line acknowledgement, and its body is +// folded into the PR's status comment — created once, then edited in place +// when the second lane reports — instead of being submitted as a review. +func TestReviewRequestWatcher_QuietModeSuppressesNarratedCleanReview(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := reviewTestClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + c.SetNotificationsQuiet(func() bool { return true }) + dir := withReviewDir(t) + oldLinks := ReviewLinksPath + ReviewLinksPath = filepath.Join(t.TempDir(), "review-links.json") + t.Cleanup(func() { ReviewLinksPath = oldLinks }) + withVerdictDispatchState(t, review.DispatchState{Pending: []review.PendingReview{ + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveCorrectness, Agent: "reviewer"}, + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveSecurity, Agent: "reviewer-2"}, + }}) + + submit := func(agent, perspective, event, verdict, body string) ReviewResponse { + t.Helper() + path, err := WriteReviewRequest(dir, ReviewRequest{Repo: "o/r", Number: 5, Event: event, Agent: agent, Body: body, Report: validVerdictJSON(t, "o/r", 5, perspective, verdict)}) + if err != nil { + t.Fatal(err) + } + c.ProcessReviewRequestsOnce(context.Background()) + raw, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".result.json") + if err != nil { + t.Fatal(err) + } + var resp ReviewResponse + _ = json.Unmarshal(raw, &resp) + return resp + } + + narrated := "Read the tree at `c7c8dfb`: the retry loop bounds its attempts. Looks correct to me.\n\nNo findings." + resp := submit("reviewer", "correctness", "approve", "approve", narrated) + if !resp.OK || resp.State != ReviewEventRecordVerdict || resp.Note != reviewNoFindingsSuppressedNote { + t.Fatalf("narrated clean review must be recorded, not posted: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 0 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the verdict folded into one new status comment", s.reviews, s.creates, s.edits) + } + body, _ := s.comments[0]["body"].(string) + if !strings.Contains(body, "**Reviewed** by `reviewer` — no findings.") || !strings.Contains(body, "Looks correct to me.") { + t.Fatalf("status comment must carry the verdict and the reviewer's notes: %q", body) + } + + if resp := submit("reviewer-2", "security", "approve", "approve", "Checked the token handling; no findings from security."); !resp.OK || resp.State != ReviewEventRecordVerdict { + t.Fatalf("second lane must be recorded too: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 1 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the second lane to edit the status comment", s.reviews, s.creates, s.edits) + } + body, _ = s.comments[0]["body"].(string) + if !strings.Contains(body, "by `reviewer` —") || !strings.Contains(body, "by `reviewer-2` —") { + t.Fatalf("both lanes must share the status comment: %q", body) + } + + // A body that says "no findings" while the verdict disagrees is a + // real review and still goes out. + if resp := submit("reviewer", "correctness", "request_changes", "changes_requested", "No findings on the happy path, but `main.go:12` drops the error."); !resp.OK || s.reviews != 1 { + t.Fatalf("a non-approving verdict must still post: %+v reviews=%d", resp, s.reviews) + } +} + func TestMaxReviewsPerHeadQuietMode(t *testing.T) { c := testClient(t, "http://127.0.0.1:0") c.SetReviewCadenceLimits(func() bool { return false }, func() int { return 0 }) diff --git a/src/pkg/github/prclaims.go b/src/pkg/github/prclaims.go index 60fd3d5f4d..7cefdde5fe 100644 --- a/src/pkg/github/prclaims.go +++ b/src/pkg/github/prclaims.go @@ -1850,11 +1850,13 @@ func (l *ClaimLedger) Save() error { } // RedStaleFunc reports whether the claiming PR (prRepo, prNumber) is red on a -// required check AND stale (its red head SHA unchanged past the staleness -// threshold). Fix #3 uses it to DECIDE NOT to suppress a claimed issue: a -// healthy claiming PR (green/pending, or a freshly-changed head) still -// suppresses its issue, but a red+stale one releases the issue so the work can -// be re-taken. It is supplied by the caller so this package stays free of the +// required check AND abandoned (its red head SHA unchanged past the staleness +// threshold and the hive's fix loop done with it: escalated, re-engagement +// budget spent, or red for the whole re-engagement window). Fix #3 uses it to +// DECIDE NOT to suppress a claimed issue: a healthy claiming PR (green/pending, +// or a freshly-changed head) or one the reaper is still re-engaging keeps +// suppressing its issue, but an abandoned red one releases the issue so the +// work can be re-taken (hivecommons/hive#16522). It is supplied by the caller so this package stays free of the // escalation-store dependency; a nil func means "never release" (old behavior). // GENERIC: the predicate keys only off check state + commit staleness. type RedStaleFunc func(prRepo string, prNumber int) bool diff --git a/src/pkg/github/protection_facts.go b/src/pkg/github/protection_facts.go index 9a9bbf7f8b..bc7b95fe96 100644 --- a/src/pkg/github/protection_facts.go +++ b/src/pkg/github/protection_facts.go @@ -181,6 +181,38 @@ func (pc *protectionCollector) attach(ctx context.Context, pr *PullRequest, repo pr.Protection = &f } +// attachRequiredChecks stamps the base branch's required-check policy onto +// pr.CIActivity exactly as attach does, plus the commit statuses an any-App +// or unreported required context needs, without the protection facts: it +// is the webhook CI re-read's half (webhook_ci_evidence.go), where no +// mergeability or review decision is being collected. +func (pc *protectionCollector) attachRequiredChecks(ctx context.Context, pr *PullRequest) { + if pc == nil || pc.c == nil || pr == nil || pr.CIActivity == nil || pr.BaseRef == "" { + return + } + req := pc.requiredChecks(ctx, pr.Repo, pr.BaseRef) + a := pr.CIActivity + a.setRequired(req.set, req.known) + a.RequiredChecks = req.bindings + a.RequiredSource = req.source + a.RequiredKnown = req.known && req.source != "config" && observedRequiredBindings(req.set, req.bindings) + if !req.known { + return + } + needsStatuses := a.NeedsCommitStatusEvidence() + for name := range req.set { + if len(a.ChecksForRequired(name)) == 0 { + needsStatuses = true + } + } + if !needsStatuses { + return + } + if collected, known := pc.c.commitStatuses(ctx, pr.Repo, pr.HeadSHA); known { + a.addCommitStatuses(collected, time.Now().UTC()) + } +} + // commitStatuses retains state and identity, not just context presence. // A failed, incomplete or explicitly wrong-head listing is unknown. func (c *Client) commitStatuses(ctx context.Context, repo, sha string) ([]*gh.RepoStatus, bool) { diff --git a/src/pkg/github/review_queue.go b/src/pkg/github/review_queue.go index bef6092295..ae6e339cb3 100644 --- a/src/pkg/github/review_queue.go +++ b/src/pkg/github/review_queue.go @@ -341,7 +341,9 @@ func ReviewQueueKey(fullRepo string, number int) string { return strings.ToLower(fmt.Sprintf("%s#%d", fullRepo, number)) } -func reviewQueueFullRepo(repo, org string) string { +// ReviewQueueFullRepo qualifies a bare repo name with org for queue identities. +// It trims whitespace and leaves empty or already-qualified repo names unchanged. +func ReviewQueueFullRepo(repo, org string) string { repo = strings.TrimSpace(repo) org = strings.TrimSpace(org) if repo == "" || strings.Contains(repo, "/") || org == "" { @@ -379,7 +381,7 @@ func BuildReviewQueue(prs []PullRequest, opts ReviewQueueOptions) []ReviewQueueE seen := make(map[string]bool, len(prs)) entries := make([]ReviewQueueEntry, 0, len(prs)) for _, pr := range prs { - full := reviewQueueFullRepo(pr.Repo, opts.Org) + full := ReviewQueueFullRepo(pr.Repo, opts.Org) if full == "" || pr.Number <= 0 { continue } @@ -642,7 +644,7 @@ func ReviewQueueFromActionable(actionable *ActionableResult, opts ReviewQueueOpt held[k] = v } for _, pr := range actionable.PRs.Held { - held[ReviewQueueKey(reviewQueueFullRepo(pr.Repo, opts.Org), pr.Number)] = true + held[ReviewQueueKey(ReviewQueueFullRepo(pr.Repo, opts.Org), pr.Number)] = true } opts.Held = held if opts.RedMain == nil { @@ -668,7 +670,7 @@ func StampReviewQueue(actionable *ActionableResult, opts ReviewQueueOptions) []R } stamp := func(prs []PullRequest) { for i := range prs { - e, ok := byKey[ReviewQueueKey(reviewQueueFullRepo(prs[i].Repo, opts.Org), prs[i].Number)] + e, ok := byKey[ReviewQueueKey(ReviewQueueFullRepo(prs[i].Repo, opts.Org), prs[i].Number)] if !ok { continue } diff --git a/src/pkg/github/review_request_watcher.go b/src/pkg/github/review_request_watcher.go index ea582bb3de..e85ce6526c 100644 --- a/src/pkg/github/review_request_watcher.go +++ b/src/pkg/github/review_request_watcher.go @@ -299,18 +299,25 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re threadID := strings.TrimSpace(req.ThreadID) // A "comment" that names a thread is an in-thread reply, not a PR review. threadReply := okEvent && apiEvent == "COMMENT" && threadID != "" - // Quiet notification mode: a review whose whole body is the clean - // acknowledgement ("**Reviewed** — no findings from …") is recorded as - // a verdict and never submitted. Submitting it emails the author and - // every watcher to say nothing happened; the verdict still reaches the - // evidence bundle and the Activity Monitor. The request keeps its + // Quiet notification mode: a clean review — the one-line acknowledgement + // ("**Reviewed** — no findings from …"), or a narrated body that says it + // has no findings while its verdict report approves with none + // (review.CleanReview; the plain reviewer lanes write the latter, + // hivecommons/hive#16433) — is recorded as a verdict and never + // submitted. Submitting it emails the author and every watcher to say + // nothing happened; the verdict still reaches the evidence bundle and + // the Activity Monitor, and the body is folded into the PR's status + // comment below so the reasoning is not lost. The request keeps its // report, so the shape checks below treat it exactly as record_verdict. noFindingsSuppressed := false if okEvent && !recordOnly && !resolveThread && threadID == "" && !req.Revise && - c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" && review.NoFindingsAcknowledgement(req.Body) { - recordOnly = true - noFindingsSuppressed = true - req.Event = ReviewEventRecordVerdict + c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" { + reports, _ := review.ValidateReportsFor([]byte(strings.TrimSpace(req.Report)), c.perspectives) + if review.CleanReview(req.Body, reports) { + recordOnly = true + noFindingsSuppressed = true + req.Event = ReviewEventRecordVerdict + } } // Validate shape BEFORE authorizing or touching the API — a hopeless request // must never retry. @@ -506,6 +513,14 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re // Authorized and well-formed, but nothing to post: record and finish // without touching the GitHub API. if recordOnly { + if noFindingsSuppressed { + // The clean verdict lands in the status comment, edited in + // place, instead of a review submission of its own. + if _, ferr := c.UpsertPRStatusSection(ctx, req.Repo, req.Number, prstatus.KeyReviewFindingsPrefix+verdictSlug(req.Agent), reviewNoFindingsSection(req)); ferr != nil { + c.logger.Warn("review-request watcher: could not fold the clean verdict into the status comment", + slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", ferr.Error())) + } + } c.recordReviewEvidence(ctx, req, c.recordReviewVerdict(ctx, req, ""), nil, nowFn()) if err := c.fileOutOfScopeReviewBacklog(ctx, req, nowFn().UTC()); err != nil { c.logger.Warn("review-request watcher: could not file out-of-scope backlog", @@ -971,6 +986,20 @@ func (c *Client) maxReviewsPerHead() int { // acknowledgement the quiet mode recorded instead of submitting. const reviewNoFindingsSuppressedNote = "comment suppressed: no-findings acknowledgement recorded as a verdict (github.notifications.mode: quiet)" +// reviewNoFindingsSection renders a suppressed clean review for the status +// comment: the verdict on its own line, the reviewer's reasoning folded. +func reviewNoFindingsSection(req ReviewRequest) string { + var b strings.Builder + fmt.Fprintf(&b, "**Reviewed** by `%s` — no findings.", strings.TrimSpace(req.Agent)) + body := strings.TrimSpace(req.Body) + if body != "" && !review.NoFindingsAcknowledgement(body) { + b.WriteString("\n\n<details><summary>Reviewer notes</summary>\n\n") + b.WriteString(body) + b.WriteString("\n\n</details>") + } + return b.String() +} + // reviewFindingsSection renders a perspective's findings for the status // comment: who found them, then the body as written. func reviewFindingsSection(req ReviewRequest) string { diff --git a/src/pkg/github/review_verdict_relay.go b/src/pkg/github/review_verdict_relay.go index 8614e7f3a3..75996c6a04 100644 --- a/src/pkg/github/review_verdict_relay.go +++ b/src/pkg/github/review_verdict_relay.go @@ -385,6 +385,21 @@ func maintainerCallQuestion(body string) string { return "" } +// logVerdictDispatchRefusal reports a discarded verdict. A self-approval +// refusal is the guard working as designed, not a runtime fault, so it is +// logged at INFO to keep it out of the fleet's repeated-error reports. +func (c *Client) logVerdictDispatchRefusal(ctx context.Context, req ReviewRequest, report review.PerspectiveReport, reason string) { + level := slog.LevelWarn + if reason == "author_self_approval" { + level = slog.LevelInfo + } + c.logger.Log(ctx, level, "review-request watcher: verdict does not match a review dispatch, discarded", + slog.String("reviewed", fmt.Sprintf("%s#%d", req.Repo, req.Number)), + slog.String("perspective", string(report.Perspective)), + slog.String("agent", req.Agent), + slog.String("reason", reason)) +} + // writeOneVerdict commits a single perspective's verdict where review.Collect // will find it. One file per perspective, which is what the collector has // always read — a combined review changes how verdicts arrive, not how they @@ -408,11 +423,7 @@ func (c *Client) writeOneVerdict(ctx context.Context, req ReviewRequest, report // here exactly as it would be for a single-object verdict. auth := c.verdictDispatchAuthorizedAt(ctx, report, req, prSnapshot) if !auth.OK { - c.logger.Warn("review-request watcher: verdict does not match a review dispatch, discarded", - slog.String("reviewed", fmt.Sprintf("%s#%d", req.Repo, req.Number)), - slog.String("perspective", string(report.Perspective)), - slog.String("agent", req.Agent), - slog.String("reason", auth.Reason)) + c.logVerdictDispatchRefusal(ctx, req, report, auth.Reason) return report, false, false } // A dispatched verdict is stored under the head its dispatch record names, diff --git a/src/pkg/github/review_verdict_relay_test.go b/src/pkg/github/review_verdict_relay_test.go index 58576670d5..8f4e719aef 100644 --- a/src/pkg/github/review_verdict_relay_test.go +++ b/src/pkg/github/review_verdict_relay_test.go @@ -847,3 +847,24 @@ func TestAdvisoryVerdictRejectsSiblingReplicaOfAuthor(t *testing.T) { t.Fatalf("sibling-replica self-approval verdict was recorded: %v", matches) } } + +func TestLogVerdictDispatchRefusalLevel(t *testing.T) { + tests := []struct { + reason string + wantLevel string + }{ + {"author_self_approval", "level=INFO"}, + {"non_reviewer_without_dispatch", "level=WARN"}, + {"dispatch_state_unavailable", "level=WARN"}, + } + for _, tt := range tests { + t.Run(tt.reason, func(t *testing.T) { + var logBuf bytes.Buffer + c := &Client{logger: slog.New(slog.NewTextHandler(&logBuf, nil))} + c.logVerdictDispatchRefusal(context.Background(), ReviewRequest{Repo: "o/r", Number: 1, Agent: "reviewer"}, review.PerspectiveReport{}, tt.reason) + if !strings.Contains(logBuf.String(), tt.wantLevel) { + t.Fatalf("log = %q, want %s", logBuf.String(), tt.wantLevel) + } + }) + } +} diff --git a/src/pkg/github/sentinel_sweep.go b/src/pkg/github/sentinel_sweep.go index 2aaf540cab..e80cd80b1b 100644 --- a/src/pkg/github/sentinel_sweep.go +++ b/src/pkg/github/sentinel_sweep.go @@ -699,6 +699,39 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, err } + // The hive's sentinel comment for an EARLIER head, if this head has + // none yet. A new push rewrites it for the new head rather than + // stamping the PR a second time (hivecommons/hive#16433): the label is + // what blocks, the comment is the explanation, and one explanation per + // PR is enough. Only a comment the hive can verify as its own is + // reused — a hive that cannot name its accounts never rewrites a + // comment the PR author may have forged. findOwnMarkerComment keeps + // its exact-head read for the clearance logic below. + var prior *gh.IssueComment + if !posted && c.knowsOwnAccounts() { + if prior, _, err = c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker); err != nil { + return SentinelSweepEvent{}, false, err + } + } + writeSentinelComment := func(body, what string) error { + target := comment + if !posted { + target = prior + } + if target != nil { + if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, target.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return fmt.Errorf("updating sentinel %s: %w", what, err) + } + c.noteCommentEdited() + return nil + } + _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated + c.noteWritebackOutcome(displayRepo, resp, err) + if err != nil { + return fmt.Errorf("posting sentinel %s: %w", what, err) + } + return nil + } if decision.Block && !hasAlertLabel && sentinelClearedByMaintainer(comment, posted) { // The alert for this exact head is on the PR but the label is not: // only a maintainer removes it, and the comment promised "Hive will @@ -768,16 +801,14 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("removing %s label from trusted author PR: %w", label, err) } - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } if !posted { - _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated - c.noteWritebackOutcome(displayRepo, resp, err) - if err != nil { - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } } return event, true, nil @@ -790,15 +821,8 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("adding %s label: %w", label, err) } - body := markerBody - if posted { - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel alert: %w", err) - } - } else { - if _, _, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel comment: %w", err) - } + if err := writeSentinelComment(markerBody, "alert"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } diff --git a/src/pkg/github/sentinel_sweep_test.go b/src/pkg/github/sentinel_sweep_test.go index eabdf88659..5fa37f94c7 100644 --- a/src/pkg/github/sentinel_sweep_test.go +++ b/src/pkg/github/sentinel_sweep_test.go @@ -1,6 +1,7 @@ package github -// Tests for the sentinel sweep: label + one comment per head on a finding, +// Tests for the sentinel sweep: label + one comment per PR on a finding +// (rewritten for each new head when the hive can verify its own comment), // nothing on a clean PR, no re-application once a maintainer clears the // label for an unchanged head (including across a restart, where the // clearance is read back from the alert comment), fail-closed on an @@ -551,8 +552,8 @@ func TestSweepSentinelClearanceOnNewerHeadIsHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hC") { - t.Fatalf("push after clearance must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after clearance must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -617,8 +618,8 @@ func TestSweepSentinelDashboardApprovalReleasesHead(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 4 || !strings.Contains(f.comments[9][3], SentinelMarker+" hC") { - t.Fatalf("push after the approval must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after the approval must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } } @@ -654,8 +655,8 @@ func TestSweepSentinelDashboardApprovalNotHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][2], SentinelMarker+" hB") { - t.Fatalf("new head must re-alert: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || f.comments[9][1] != tc.body { + t.Fatalf("new head must re-alert by rewriting the hive's comment, leaving the other alone: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -800,8 +801,8 @@ func TestSweepSentinelClearanceOnNewerHeadRejected(t *testing.T) { if got := f.labels[9]; len(got) != 1 || got[0] != "sentinel-alert" { t.Fatalf("label must be applied: %v", got) } - if len(f.comments[9]) != 2 || f.comments[9][0] != alertA || !strings.Contains(f.comments[9][1], SentinelMarker+" hB") { - t.Fatalf("a fresh alert for hB must be posted and the hA alert left alone: %v", f.comments[9]) + if len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || strings.Contains(f.comments[9][0], SentinelMarker+" hA") { + t.Fatalf("the hA alert must be rewritten for hB, not duplicated: %v", f.comments[9]) } }) } @@ -858,7 +859,8 @@ func sentinelClearedFixture(t *testing.T, remover string, filesB []map[string]an // reviewed: the clearance carries over, no label and no new alert, and the // hive's marker comment is rewritten as the cleared alert for hB so the next // pass (a fresh client, as after a restart) stays quiet too. A later push that -// changes the flagged file re-alerts. +// changes the flagged file re-alerts, rewriting the hive's one comment for +// the new head (#16433) rather than stamping the PR again. func TestSweepSentinelClearanceCarriesOverUnchangedFlaggedChanges(t *testing.T) { filesB := []map[string]any{{"filename": "OWNERS", "status": "modified", "patch": sentinelOwnersPatch}} f, client := sentinelClearedFixture(t, "danathar", filesB) @@ -887,15 +889,15 @@ func TestSweepSentinelClearanceCarriesOverUnchangedFlaggedChanges(t *testing.T) f.checkSuites["hC"] = []string{"2026-10-25T04:00:00Z"} f.mu.Unlock() res, err := client().SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 2 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hC") { - t.Fatalf("a changed flagged file must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 2 || len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("a changed flagged file must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } } // The carry-over needs the same flagged content and a human's removal. A // changed patch, an added flagged file, a flagged file GitHub returns with // no patch, and a removal by a bot each leave the existing behaviour: hB is -// alerted on and labelled. +// alerted on and labelled, the hive's hA alert rewritten for hB (#16433). func TestSweepSentinelClearanceCarryOverRejected(t *testing.T) { owners := map[string]any{"filename": "OWNERS", "status": "modified", "patch": sentinelOwnersPatch} cases := []struct { @@ -918,8 +920,8 @@ func TestSweepSentinelClearanceCarryOverRejected(t *testing.T) { if got := f.labels[9]; len(got) != 2 { t.Fatalf("label must be applied again: %v", got) } - if len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hB") { - t.Fatalf("a fresh alert for hB must be posted: %v", f.comments[9]) + if len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || strings.Contains(f.comments[9][0], SentinelMarker+" hA") { + t.Fatalf("the hA alert must be rewritten for hB, not duplicated: %v", f.comments[9]) } }) } diff --git a/src/pkg/github/webhook_cache.go b/src/pkg/github/webhook_cache.go index dd9f29d45e..0c8d18ae94 100644 --- a/src/pkg/github/webhook_cache.go +++ b/src/pkg/github/webhook_cache.go @@ -31,6 +31,17 @@ type WebhookHealth struct { // deliveries and refreshes caused. TargetedRefreshes1h int `json:"targeted_refreshes_1h"` TrackerInvalidations1h int `json:"tracker_invalidations_1h"` + // CI deliveries (check_run, check_suite, status, workflow_run, + // workflow_job) for managed repositories (hivecommons/hive#16521): + // when the last one arrived, how many in the window, how many check + // observations they applied to a head's set without a GitHub call, and + // how many coalesced check-run re-reads they caused. A nil + // LastCIEventAt with webhooks otherwise healthy means the App or the + // relay does not deliver check events. + LastCIEventAt *time.Time `json:"last_ci_event_at"` + CIEvents1h int `json:"ci_events_1h"` + CIEventsApplied1h int `json:"ci_events_applied_1h"` + CIRefetches1h int `json:"ci_refetches_1h"` // WebhookModeStatus is the reconcile cadence the health drives: // `mode` webhook|polling and `since` (hivecommons/hive#13381). WebhookModeStatus @@ -79,6 +90,10 @@ type WebhookEventResult struct { // reported a failed check (failure / timed_out / error) on a head SHA, // with the open PRs that head resolved to. CIFailure *WebhookCIFailure `json:"ci_failure,omitempty"` + // CIEvidence reports what a check_run / check_suite / status / + // workflow_run / workflow_job delivery did to the head's check set + // (hivecommons/hive#16521). + CIEvidence *WebhookCIEvidence `json:"ci_evidence,omitempty"` } // WebhookItemHint is the state a webhook payload reports for the item it @@ -112,6 +127,10 @@ type webhookTracker struct { invalidations []time.Time refreshes []time.Time trackerDrops []time.Time + ciEvents []time.Time + ciApplied []time.Time + ciRefetches []time.Time + lastCIEvent time.Time wasHealthy bool // lastActivity is the newest GitHub `updated_at` a poll listed and // lastFailure the newest delivery that failed verification; both feed @@ -213,6 +232,18 @@ func RecordWebhookTrackerInvalidations(n int) { t.recordStamped(&t.trackerDrops, n) } +func (t *webhookTracker) recordCIEvent() { + t.mu.Lock() + defer t.mu.Unlock() + now := t.now() + t.lastCIEvent = now + t.ciEvents = append(pruneWebhookTimes(t.ciEvents, now), now) +} + +func (t *webhookTracker) recordCIApplied(n int) { t.recordStamped(&t.ciApplied, n) } + +func (t *webhookTracker) recordCIRefetches(n int) { t.recordStamped(&t.ciRefetches, n) } + func (t *webhookTracker) recordStamped(dst *[]time.Time, n int) { if n <= 0 { return @@ -364,14 +395,22 @@ func (t *webhookTracker) snapshot() WebhookHealth { t.invalidations = pruneWebhookTimes(t.invalidations, now) t.refreshes = pruneWebhookTimes(t.refreshes, now) t.trackerDrops = pruneWebhookTimes(t.trackerDrops, now) + t.ciEvents = pruneWebhookTimes(t.ciEvents, now) + t.ciApplied = pruneWebhookTimes(t.ciApplied, now) + t.ciRefetches = pruneWebhookTimes(t.ciRefetches, now) healthy, latest := t.healthyLocked(now) out := WebhookHealth{Healthy: healthy, Events1h: len(t.events), Invalidations1h: len(t.invalidations), TargetedRefreshes1h: len(t.refreshes), TrackerInvalidations1h: len(t.trackerDrops), + CIEvents1h: len(t.ciEvents), CIEventsApplied1h: len(t.ciApplied), CIRefetches1h: len(t.ciRefetches), WebhookModeStatus: t.mode.status(t.window, now)} if !latest.IsZero() { at := latest.UTC() out.LastEventAt = &at } + if !t.lastCIEvent.IsZero() { + at := t.lastCIEvent.UTC() + out.LastCIEventAt = &at + } return out } @@ -425,6 +464,39 @@ type webhookPRRef struct { Number int `json:"number"` } +// webhookCheckRunPayload is the `check_run` object of a check_run delivery. +type webhookCheckRunPayload struct { + ID int64 `json:"id"` + NodeID string `json:"node_id"` + HeadSHA string `json:"head_sha"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + DetailsURL string `json:"details_url"` + HTMLURL string `json:"html_url"` + StartedAt *time.Time `json:"started_at"` + CompletedAt *time.Time `json:"completed_at"` + PullRequests []webhookPRRef `json:"pull_requests"` + App *struct { + ID int64 `json:"id"` + Name string `json:"name"` + } `json:"app"` +} + +// webhookWorkflowJobPayload is the `workflow_job` object: one GitHub Actions +// job, which is its check run as the Actions App reports it. +type webhookWorkflowJobPayload struct { + ID int64 `json:"id"` + NodeID string `json:"node_id"` + HeadSHA string `json:"head_sha"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + HTMLURL string `json:"html_url"` + StartedAt *time.Time `json:"started_at"` + CompletedAt *time.Time `json:"completed_at"` +} + type webhookEventPayload struct { Repository struct { FullName string `json:"full_name"` @@ -472,23 +544,23 @@ type webhookEventPayload struct { Name string `json:"name"` } `json:"app"` } `json:"check_suite"` - CheckRun *struct { - HeadSHA string `json:"head_sha"` - Name string `json:"name"` - Conclusion string `json:"conclusion"` - DetailsURL string `json:"details_url"` - HTMLURL string `json:"html_url"` - PullRequests []webhookPRRef `json:"pull_requests"` - } `json:"check_run"` + CheckRun *webhookCheckRunPayload `json:"check_run"` WorkflowRun *struct { HeadSHA string `json:"head_sha"` PullRequests []webhookPRRef `json:"pull_requests"` } `json:"workflow_run"` - SHA string `json:"sha"` - State string `json:"state"` - Context string `json:"context"` - TargetURL string `json:"target_url"` - Branches []struct { + // WorkflowJob is one GitHub Actions job: its check run, as the Actions + // App reports it, without the check_run envelope. + WorkflowJob *webhookWorkflowJobPayload `json:"workflow_job"` + ID int64 `json:"id"` + NodeID string `json:"node_id"` + SHA string `json:"sha"` + State string `json:"state"` + Context string `json:"context"` + TargetURL string `json:"target_url"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + Branches []struct { Name string `json:"name"` } `json:"branches"` Ref string `json:"ref"` @@ -579,15 +651,20 @@ func (c *Client) HandleWebhookEvent(event string, payload []byte) (WebhookEventR sharedCIReportingCache.invalidate(p.Repository.FullName, res.HeadSHA) } numbers := webhookInvalidationTargets(event, p, aliases) + if IsWebhookCIEvent(event) && res.HeadSHA != "" { + numbers = sharedCIEvidence().resolvePRs(p.Repository.FullName, res.HeadSHA, numbers) + } // Capture the failed-check identity and the PRs it resolved to BEFORE // invalidation drops their cache entries: the receiver reacts to a red // check on the event rather than on the next sweep. res.CIFailure = c.webhookCIFailureResult(event, p, aliases, numbers) + CIFailureSignals().forgetResolvedWebhook(event, p) for _, n := range numbers { c.invalidateWebhookPR(aliases, n) } sharedWebhookTracker().recordInvalidations(len(numbers)) res.Invalidated = numbers + res.CIEvidence = c.applyWebhookCIEvidence(event, p, configured, numbers) return res, nil } @@ -732,6 +809,10 @@ func webhookHeadSHA(event string, p webhookEventPayload) string { if p.WorkflowRun != nil { return strings.TrimSpace(p.WorkflowRun.HeadSHA) } + case "workflow_job": + if p.WorkflowJob != nil { + return strings.TrimSpace(p.WorkflowJob.HeadSHA) + } } return "" } @@ -789,6 +870,10 @@ func webhookInvalidationTargets(event string, p webhookEventPayload, aliases []s addRefs(p.WorkflowRun.PullRequests) bySHA(p.WorkflowRun.HeadSHA) } + case "workflow_job": + if p.WorkflowJob != nil { + bySHA(p.WorkflowJob.HeadSHA) + } case "push": if ref, ok := strings.CutPrefix(p.Ref, "refs/heads/"); ok && ref != "" { addMatching(func(_, headRef, baseRef string) bool { return headRef == ref || baseRef == ref }) diff --git a/src/pkg/github/webhook_ci_evidence.go b/src/pkg/github/webhook_ci_evidence.go new file mode 100644 index 0000000000..576d51c812 --- /dev/null +++ b/src/pkg/github/webhook_ci_evidence.go @@ -0,0 +1,741 @@ +package github + +import ( + "context" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// Webhook-driven CI evidence (hivecommons/hive#16521). +// +// The Activity Monitor's CI chevron counts check runs on a PR's current head +// (PullRequest.CIActivity). Until now that evidence had one producer, the +// per-cycle check-run listing in EnrichCIStatus, so a row read "CI ?/?" +// from the moment a head was pushed until the next full cycle, and a +// sidelined PR never had any. A `check_run`, `workflow_job` or `status` +// delivery already names the head, the check and its result, so the payload +// is applied straight into a per-(repo, head) check set here. The tracker +// merges that set over whatever the last listing produced, and a head no +// listing has covered yet is re-read once, coalesced, so the required-check +// set behind the counts becomes known. The listing stays as the backstop +// for spokes without webhooks. + +// githubActionsAppID is the App id GitHub Actions reports on its check runs; +// a `workflow_job` payload carries no app object, but its check run is +// always this producer's. +const githubActionsAppID int64 = 15368 + +// ciEvidenceMaxHeads bounds the per-head store; the oldest-touched heads are +// evicted first. ciEvidenceTTL drops heads no delivery or listing has +// touched for that long (a merged PR's head, for one). +const ( + ciEvidenceMaxHeads = 4096 + ciEvidenceTTL = 48 * time.Hour +) + +// webhookCIEventTypes are the deliveries that carry CI evidence for a head. +var webhookCIEventTypes = map[string]bool{ + "check_run": true, + "check_suite": true, + "status": true, + "workflow_run": true, + "workflow_job": true, +} + +// IsWebhookCIEvent reports whether event is one of the check/status/workflow +// deliveries that drive CI evidence. +func IsWebhookCIEvent(event string) bool { return webhookCIEventTypes[event] } + +// WebhookCIEvidence reports what a CI delivery did to the per-head check set. +type WebhookCIEvidence struct { + HeadSHA string `json:"head_sha"` + // Applied is the number of check observations taken from the payload + // itself (check_run, workflow_job, status). A check_suite or + // workflow_run payload carries none. + Applied int `json:"applied"` + // Refetch is set when the head had no check-run listing yet (no + // required-check set to count against) and one coalesced re-read of + // the head's check runs was scheduled. + Refetch bool `json:"refetch,omitempty"` + // PRs are the open PR numbers the head resolved to. + PRs []int `json:"prs,omitempty"` +} + +type ciHeadKey struct { + repo string // canonical owner/name, lower-case + head string // lower-case SHA +} + +type ciHeadEvidence struct { + // prs are the open PR numbers deliveries resolved this head to. A + // check delivery invalidates the PR detail cache, so a later `status` + // or `workflow_job` payload (which names no PR) could not resolve the + // head by SHA without this memory. + prs map[int]bool + // listed is the last complete observation of the head (check-run + // listing plus required set and statuses), nil until one ran. + listed *PRCIActivity + // events holds the checks taken from deliveries, newest per identity. + events []PRActivityCheck + eventsAt time.Time + touched time.Time +} + +type ciEvidenceStore struct { + mu sync.Mutex + now func() time.Time + heads map[ciHeadKey]*ciHeadEvidence +} + +func newCIEvidenceStore() *ciEvidenceStore { + return &ciEvidenceStore{now: time.Now, heads: map[ciHeadKey]*ciHeadEvidence{}} +} + +var ciEvidencePtr = func() *atomic.Pointer[ciEvidenceStore] { + p := &atomic.Pointer[ciEvidenceStore]{} + p.Store(newCIEvidenceStore()) + return p +}() + +func sharedCIEvidence() *ciEvidenceStore { return ciEvidencePtr.Load() } + +// ResetCIEvidenceForTest swaps in an empty per-head CI evidence store with +// the given clock and returns a restore func. +func ResetCIEvidenceForTest(now func() time.Time) func() { + old := sharedCIEvidence() + s := newCIEvidenceStore() + if now != nil { + s.now = now + } + ciEvidencePtr.Store(s) + return func() { ciEvidencePtr.Store(old) } +} + +func ciEvidenceKey(repo, head string) ciHeadKey { + return ciHeadKey{repo: canonicalPRDetailRepo(repo), head: strings.ToLower(strings.TrimSpace(head))} +} + +// entryLocked returns the head's record, creating it when create is set. A +// bare repo name (no owner) matches the one stored full name ending in it. +func (s *ciEvidenceStore) entryLocked(key ciHeadKey, create bool) *ciHeadEvidence { + if e, ok := s.heads[key]; ok { + return e + } + if !strings.Contains(key.repo, "/") { + for k, e := range s.heads { + if k.head == key.head && strings.HasSuffix(k.repo, "/"+key.repo) { + return e + } + } + } + if !create { + return nil + } + e := &ciHeadEvidence{} + s.heads[key] = e + return e +} + +func (s *ciEvidenceStore) pruneLocked(now time.Time) { + for k, e := range s.heads { + if now.Sub(e.touched) >= ciEvidenceTTL { + delete(s.heads, k) + } + } + for len(s.heads) > ciEvidenceMaxHeads { + var oldestKey ciHeadKey + var oldest time.Time + first := true + for k, e := range s.heads { + if first || e.touched.Before(oldest) { + oldestKey, oldest, first = k, e.touched, false + } + } + delete(s.heads, oldestKey) + } +} + +// recordListed stores a complete observation of the head. Event checks +// older than the listing are dropped: the listing already reflects them. +func (s *ciEvidenceStore) recordListed(repo, head string, a *PRCIActivity) { + if a == nil || strings.TrimSpace(head) == "" || !strings.EqualFold(a.Head, head) { + return + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + e.listed = cloneCIActivity(a) + e.touched = now + if a.ObservedAt != nil && !e.eventsAt.After(*a.ObservedAt) { + e.events, e.eventsAt = nil, time.Time{} + } + s.pruneLocked(now) +} + +// hasListed reports whether a check-run listing has covered the head. +func (s *ciEvidenceStore) hasListed(repo, head string) bool { + s.mu.Lock() + defer s.mu.Unlock() + e := s.entryLocked(ciEvidenceKey(repo, head), false) + return e != nil && e.listed != nil +} + +// applyEvent upserts the checks a delivery reported for the head and +// returns how many it kept. +func (s *ciEvidenceStore) applyEvent(repo, head string, checks []PRActivityCheck) int { + if strings.TrimSpace(head) == "" || len(checks) == 0 { + return 0 + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + applied := 0 + for _, check := range checks { + if check.Name == "" { + continue + } + check.Head = head + e.events = upsertActivityCheck(e.events, check) + applied++ + } + if applied > 0 { + e.eventsAt = now + } + e.touched = now + s.pruneLocked(now) + return applied +} + +// resolvePRs remembers the PRs a CI delivery resolved the head to and +// returns them joined with the ones earlier deliveries remembered, sorted. +func (s *ciEvidenceStore) resolvePRs(repo, head string, numbers []int) []int { + if strings.TrimSpace(head) == "" { + return numbers + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + if e.prs == nil { + e.prs = map[int]bool{} + } + for _, n := range numbers { + if n > 0 { + e.prs[n] = true + } + } + e.touched = now + out := make([]int, 0, len(e.prs)) + for n := range e.prs { + out = append(out, n) + } + sort.Ints(out) + s.pruneLocked(now) + return out +} + +// touch keeps the head alive without evidence (check_suite, workflow_run). +func (s *ciEvidenceStore) touch(repo, head string) { + if strings.TrimSpace(head) == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + e.touched = now + s.pruneLocked(now) +} + +// merged returns the head's evidence: the newest listing (the store's or the +// caller's base, whichever observed later) with the delivered checks laid +// over it. Nil when neither exists. +func (s *ciEvidenceStore) merged(repo, head string, base *PRCIActivity) *PRCIActivity { + if strings.TrimSpace(head) == "" { + return base + } + if base != nil && !strings.EqualFold(base.Head, head) { + base = nil + } + s.mu.Lock() + e := s.entryLocked(ciEvidenceKey(repo, head), false) + var listed *PRCIActivity + var events []PRActivityCheck + var eventsAt time.Time + if e != nil { + listed = e.listed + events = append([]PRActivityCheck(nil), e.events...) + eventsAt = e.eventsAt + } + s.mu.Unlock() + if base != nil && (listed == nil || observedAfter(base.ObservedAt, listed.ObservedAt)) { + listed = base + } + if len(events) == 0 { + return listed + } + var out *PRCIActivity + if listed != nil { + out = cloneCIActivity(listed) + if out.ObservedAt != nil && !eventsAt.After(*out.ObservedAt) { + return out + } + } else { + out = &PRCIActivity{Head: head} + } + applied := 0 + for _, check := range events { + out.Checks = upsertActivityCheck(out.Checks, check) + applied++ + } + if applied > 0 { + at := eventsAt.UTC() + out.ObservedAt = &at + switch { + case out.Source == "": + out.Source = "github-webhook" + case !strings.Contains(out.Source, "github-webhook"): + out.Source += "+github-webhook" + } + sort.SliceStable(out.Checks, func(i, j int) bool { return out.Checks[i].Name < out.Checks[j].Name }) + } + return out +} + +func observedAfter(a, b *time.Time) bool { + if a == nil { + return false + } + if b == nil { + return true + } + return a.After(*b) +} + +// upsertActivityCheck places check into list the way GitHub's own "latest" +// listing would: the same run (node id) is updated in place, a newer run of +// the same check (kind, name, producing App) replaces the older one, an +// older observation than the one held is dropped, and anything else is +// appended. +func upsertActivityCheck(list []PRActivityCheck, check PRActivityCheck) []PRActivityCheck { + for i := range list { + if check.NodeID != "" && list[i].NodeID == check.NodeID { + if checkBefore(check, list[i]) { + return list + } + list[i] = check + return list + } + } + for i := range list { + if !sameCheckIdentity(list[i], check) { + continue + } + if checkBefore(check, list[i]) { + return list + } + list[i] = check + return list + } + return append(list, check) +} + +// checkBefore reports whether a is a strictly older observation than b; +// an observation without a time is never older. +func checkBefore(a, b PRActivityCheck) bool { + return a.Since != nil && b.Since != nil && a.Since.Before(*b.Since) +} + +// sameCheckIdentity matches two runs of one check by kind, name and +// producing App (an unknown App matches any). +func sameCheckIdentity(a, b PRActivityCheck) bool { + if a.Kind != b.Kind || a.Name != b.Name { + return false + } + if a.AppID == nil || b.AppID == nil { + return true + } + return *a.AppID == *b.AppID +} + +func cloneCIActivity(a *PRCIActivity) *PRCIActivity { + if a == nil { + return nil + } + out := *a + out.Required = append([]string(nil), a.Required...) + out.RequiredChecks = append([]PRRequiredCheck(nil), a.RequiredChecks...) + out.Checks = append([]PRActivityCheck(nil), a.Checks...) + if a.WorkflowApproval != nil { + wa := *a.WorkflowApproval + wa.RunIDs = append([]int64(nil), a.WorkflowApproval.RunIDs...) + out.WorkflowApproval = &wa + } + return &out +} + +// HeadCIActivity is the tracker's read: the CI evidence for repo's head, +// combining the last listing (base, from the status snapshot, or the +// store's own) with every check delivered since. It returns base unchanged +// when no delivery has named the head. +func HeadCIActivity(repo, head string, base *PRCIActivity) *PRCIActivity { + return sharedCIEvidence().merged(repo, head, base) +} + +// webhookCIChecks extracts the check observations a CI delivery carries. +func webhookCIChecks(event string, p webhookEventPayload) []PRActivityCheck { + switch event { + case "check_run": + cr := p.CheckRun + if cr == nil || strings.TrimSpace(cr.Name) == "" { + return nil + } + check := PRActivityCheck{ + Name: strings.TrimSpace(cr.Name), State: cr.Status, Conclusion: cr.Conclusion, + URL: firstNonEmpty(cr.DetailsURL, cr.HTMLURL), ID: cr.ID, NodeID: cr.NodeID, Head: strings.TrimSpace(cr.HeadSHA), + } + if cr.App != nil && cr.App.ID > 0 { + id := cr.App.ID + check.AppID = &id + } + check.Since = checkSince(cr.Status, cr.StartedAt, cr.CompletedAt) + return []PRActivityCheck{check} + case "workflow_job": + job := p.WorkflowJob + if job == nil || strings.TrimSpace(job.Name) == "" { + return nil + } + id := githubActionsAppID + check := PRActivityCheck{ + Name: strings.TrimSpace(job.Name), State: job.Status, Conclusion: job.Conclusion, + URL: job.HTMLURL, ID: job.ID, NodeID: job.NodeID, AppID: &id, Head: strings.TrimSpace(job.HeadSHA), + } + check.Since = checkSince(job.Status, job.StartedAt, job.CompletedAt) + return []PRActivityCheck{check} + case "status": + if strings.TrimSpace(p.Context) == "" { + return nil + } + check := PRActivityCheck{ + Name: strings.TrimSpace(p.Context), State: "completed", URL: p.TargetURL, + ID: p.ID, NodeID: p.NodeID, Head: strings.TrimSpace(p.SHA), Kind: "commit_status", + } + switch p.State { + case "success": + check.Conclusion = "success" + case "failure", "error": + check.Conclusion = "failure" + case "pending": + check.State = "pending" + default: + check.State = "unknown" + } + if at := firstTime(p.UpdatedAt, p.CreatedAt); at != nil { + check.Since = at + } + return []PRActivityCheck{check} + } + return nil +} + +func checkSince(status string, started, completed *time.Time) *time.Time { + if status == "completed" && completed != nil && !completed.IsZero() { + t := completed.UTC() + return &t + } + if started != nil && !started.IsZero() { + t := started.UTC() + return &t + } + return nil +} + +func firstTime(ts ...*time.Time) *time.Time { + for _, t := range ts { + if t != nil && !t.IsZero() { + u := t.UTC() + return &u + } + } + return nil +} + +// applyWebhookCIEvidence is HandleWebhookEvent's CI step: it applies the +// payload's checks to the head's set and, when no listing has covered the +// head, schedules one coalesced re-read of its check runs. numbers are the +// open PRs the delivery resolved to; the first one's base branch names the +// required-check policy the re-read resolves. +func (c *Client) applyWebhookCIEvidence(event string, p webhookEventPayload, configured string, numbers []int) *WebhookCIEvidence { + if !IsWebhookCIEvent(event) { + return nil + } + head := webhookHeadSHA(event, p) + if head == "" && p.WorkflowJob != nil { + head = strings.TrimSpace(p.WorkflowJob.HeadSHA) + } + if head == "" { + return nil + } + repo := p.Repository.FullName + sharedWebhookTracker().recordCIEvent() + // Any CI delivery for the head — a workflow_run leaving action_required + // once someone clicked Approve, a check run starting — means the cached + // approval probe may be stale; re-list on the next cycle. + forgetWorkflowApproval(repo, head) + out := &WebhookCIEvidence{HeadSHA: head, PRs: append([]int(nil), numbers...)} + store := sharedCIEvidence() + checks := webhookCIChecks(event, p) + if len(checks) > 0 { + out.Applied = store.applyEvent(repo, head, checks) + sharedWebhookTracker().recordCIApplied(out.Applied) + } else { + store.touch(repo, head) + } + if len(numbers) > 0 && !store.hasListed(repo, head) { + target := ciRefetchTarget{repo: configured, fullName: repo, head: head, number: numbers[0]} + for _, alias := range webhookRepoAliases(configured, repo) { + if pr, _, ok := sharedPRDetailCache.peek(alias, numbers[0]); ok { + target.baseRef = pr.GetBase().GetRef() + break + } + } + out.Refetch = c.ciRefetcher().enqueue(target) + } + if hook := ciEvidenceHook(); hook != nil && (out.Applied > 0) { + hook(repo, head) + } + return out +} + +// CIEvidenceHook is told when a head's CI evidence changed (a delivery was +// applied or a re-read landed) so the dashboard can re-derive the row. +type CIEvidenceHook func(repo, head string) + +var ( + ciEvidenceHookMu sync.RWMutex + ciEvidenceHookFn CIEvidenceHook +) + +// SetCIEvidenceHook installs (or, with nil, removes) the process-wide hook. +func SetCIEvidenceHook(fn CIEvidenceHook) { + ciEvidenceHookMu.Lock() + ciEvidenceHookFn = fn + ciEvidenceHookMu.Unlock() +} + +func ciEvidenceHook() CIEvidenceHook { + ciEvidenceHookMu.RLock() + defer ciEvidenceHookMu.RUnlock() + return ciEvidenceHookFn +} + +// ciRefetchTarget is one head whose check runs are to be listed once. +type ciRefetchTarget struct { + repo string // as configured (the detail cache's key) + fullName string // owner/name from the payload + head string + number int + baseRef string +} + +// ciRefetchTimer is the one-shot debounce timer; tests hand-fire it. +type ciRefetchTimer interface{ Stop() bool } + +// ciRefetcher coalesces head re-reads: a check fan-out of twenty deliveries +// on a fresh head costs one listing, not twenty. +type ciRefetcher struct { + mu sync.Mutex + pending map[ciHeadKey]ciRefetchTarget + timer ciRefetchTimer + debounce time.Duration + newTimer func(d time.Duration, f func()) ciRefetchTimer + fetch func(ctx context.Context, t ciRefetchTarget) error + ctx func() context.Context + // flushes counts debounce windows that fired (tests). + flushes int +} + +const defaultCIRefetchDebounce = 2 * time.Second + +// webhookCIRefetchRESTCaller tags the check-run listings made on behalf of +// CI deliveries so /api/gh-rate-limits lists them on their own. +const webhookCIRefetchRESTCaller = "hive:webhook_ci_refetch" + +func (c *Client) ciRefetcher() *ciRefetcher { + c.ciRefetchOnce.Do(func() { + if c.ciRefetch == nil { + c.ciRefetch = &ciRefetcher{} + } + r := c.ciRefetch + if r.pending == nil { + r.pending = map[ciHeadKey]ciRefetchTarget{} + } + if r.debounce <= 0 { + r.debounce = defaultCIRefetchDebounce + } + if r.newTimer == nil { + r.newTimer = func(d time.Duration, f func()) ciRefetchTimer { return time.AfterFunc(d, f) } + } + if r.fetch == nil { + r.fetch = c.refetchHeadCI + } + if r.ctx == nil { + r.ctx = context.Background + } + }) + return c.ciRefetch +} + +// enqueue queues one head; a head already waiting keeps its slot (the PR +// number and base ref of the first delivery). It reports whether the head +// is now pending. +func (r *ciRefetcher) enqueue(t ciRefetchTarget) bool { + if r == nil || t.head == "" || t.number <= 0 { + return false + } + r.mu.Lock() + defer r.mu.Unlock() + key := ciEvidenceKey(t.fullName, t.head) + if cur, ok := r.pending[key]; ok { + if cur.baseRef == "" && t.baseRef != "" { + cur.baseRef = t.baseRef + r.pending[key] = cur + } + return true + } + r.pending[key] = t + if r.timer == nil { + r.timer = r.newTimer(r.debounce, r.flush) + } + return true +} + +func (r *ciRefetcher) pendingCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.pending) +} + +// flush lists every pending head once. Heads enqueued while the listings +// run start a new window. +func (r *ciRefetcher) flush() { + r.mu.Lock() + targets := make([]ciRefetchTarget, 0, len(r.pending)) + for _, t := range r.pending { + targets = append(targets, t) + } + r.pending = map[ciHeadKey]ciRefetchTarget{} + r.timer = nil + r.flushes++ + fetch, ctxFn := r.fetch, r.ctx + r.mu.Unlock() + if fetch == nil { + return + } + ctx := context.Background() + if ctxFn != nil { + if c := ctxFn(); c != nil { + ctx = c + } + } + sort.Slice(targets, func(i, j int) bool { + if targets[i].fullName != targets[j].fullName { + return targets[i].fullName < targets[j].fullName + } + return targets[i].number < targets[j].number + }) + for _, t := range targets { + if ctx.Err() != nil { + return + } + _ = fetch(ctx, t) + } +} + +// refetchHeadCI lists the head's check runs once, resolves the base branch's +// required-check policy (one cached GraphQL query per repo@branch) and the +// commit statuses it needs, records the result as the head's listing and +// tells the hook. It refuses to spend when the REST budget is critical or +// GitHub is pacing the hive; the next eval cycle is then the backstop. +func (c *Client) refetchHeadCI(ctx context.Context, t ciRefetchTarget) error { + if c == nil { + return ErrNoGitHubClient + } + if mode, _ := c.APIBudgetMode(); mode == APIBudgetCritical { + return ErrAPIBudgetCritical + } + if RateLimitCautionEngaged() { + return ErrRateLimitCaution + } + owner, name := c.splitRepo(firstNonEmpty(t.fullName, t.repo)) + ctx = WithRESTCaller(ctx, webhookCIRefetchRESTCaller) + var all []*gh.CheckRun + options := &gh.ListCheckRunsOptions{ListOptions: gh.ListOptions{PerPage: 100}} + for { + runs, resp, err := c.client.Checks.ListCheckRunsForRef(ctx, owner, name, t.head, options) + if err != nil || runs == nil || runs.CheckRuns == nil { + c.logger.Warn("webhook CI refetch: failed to list check runs", "repo", owner+"/"+name, "pr", t.number, "head", t.head, "error", err) + if err == nil { + err = ErrNoGitHubClient + } + return err + } + all = append(all, runs.CheckRuns...) + if resp == nil || resp.NextPage == 0 { + break + } + options.Page = resp.NextPage + } + at := sharedWebhookTracker().now().UTC() + activity := prCIActivity(t.head, "github-check-runs", activityCheckRunsByNameAndApp(checkRunsOnHead(all, t.head)), &at) + if t.baseRef != "" { + pr := &PullRequest{Repo: owner + "/" + name, Number: t.number, HeadSHA: t.head, BaseRef: t.baseRef, CIActivity: activity} + newProtectionCollector(c).attachRequiredChecks(ctx, pr) + } + sharedCIEvidence().recordListed(owner+"/"+name, t.head, activity) + sharedWebhookTracker().recordCIRefetches(1) + if hook := ciEvidenceHook(); hook != nil { + hook(owner+"/"+name, t.head) + } + return nil +} + +// FlushWebhookCIRefetch runs any pending head re-reads now, synchronously, +// instead of waiting out the debounce. The governor calls it before a +// webhook-wake cycle; tests use it in place of a timer. +func (c *Client) FlushWebhookCIRefetch() { + if c == nil || c.ciRefetch == nil { + return + } + r := c.ciRefetcher() + r.mu.Lock() + if len(r.pending) == 0 { + r.mu.Unlock() + return + } + if r.timer != nil { + r.timer.Stop() + } + r.mu.Unlock() + r.flush() +} + +// RecordCIEvidenceForTest applies checks to repo's head as a delivery would, +// so tests outside this package can drive the tracker's merged read. +func RecordCIEvidenceForTest(repo, head string, checks []PRActivityCheck) int { + return sharedCIEvidence().applyEvent(repo, head, checks) +} + +// RecordCIListingForTest records a complete check-run listing for repo's +// head, as the enrich path or a webhook re-read would, so tests can exercise +// the payload-only delivery path that needs no re-read. +func RecordCIListingForTest(repo, head string, activity *PRCIActivity) { + sharedCIEvidence().recordListed(repo, head, activity) +} diff --git a/src/pkg/github/webhook_ci_evidence_test.go b/src/pkg/github/webhook_ci_evidence_test.go new file mode 100644 index 0000000000..acd2b946ee --- /dev/null +++ b/src/pkg/github/webhook_ci_evidence_test.go @@ -0,0 +1,298 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func ciTestCheckRunBody(number int, head, name, status, conclusion string, at time.Time) []byte { + completed := "null" + if status == "completed" { + completed = fmt.Sprintf("%q", at.Format(time.RFC3339)) + } + return []byte(fmt.Sprintf(`{"action":%q,"repository":{"full_name":"org/repo"},"check_run":{"id":%d,"node_id":"CR_%s_%d","head_sha":%q,"name":%q,"status":%q,"conclusion":%q,"details_url":"https://ci/%s","started_at":%q,"completed_at":%s,"pull_requests":[{"number":%d}],"app":{"id":15368,"name":"GitHub Actions"}}}`, + status, len(name)*100+number, name, len(name), head, name, status, conclusion, name, at.Add(-time.Minute).Format(time.RFC3339), completed, number)) +} + +type ciTestTimer struct{} + +func (t *ciTestTimer) Stop() bool { return true } + +// A check_run delivery is applied to the head's check set from the payload +// alone — no GitHub call — and the merged view the tracker reads counts it +// at once; the head's one coalesced re-read is queued because no listing +// has covered it yet. +func TestHandleWebhookEventCheckRunAppliesCIEvidenceFromPayload(t *testing.T) { + c, clock := setupWebhookCacheTest(t) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + var fired func() + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { fired = f; return &ciTestTimer{} }} + c.storePRDetail("repo", 7, testPRDetail(7, "sha-7", clock.now, "clean")) + + res, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "in_progress", "", clock.now)) + if err != nil { + t.Fatal(err) + } + if res.CIEvidence == nil || res.CIEvidence.Applied != 1 || !res.CIEvidence.Refetch || !reflect.DeepEqual(res.CIEvidence.PRs, []int{7}) || res.CIEvidence.HeadSHA != "sha-7" { + t.Fatalf("ci_evidence = %+v, want applied 1, refetch, PRs [7]", res.CIEvidence) + } + if fired == nil || c.ciRefetch.pendingCount() != 1 { + t.Fatalf("expected one pending head re-read, pending=%d timer armed=%v", c.ciRefetch.pendingCount(), fired != nil) + } + + clock.now = clock.now.Add(30 * time.Second) + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "completed", "success", clock.now)); err != nil { + t.Fatal(err) + } + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "lint", "completed", "failure", clock.now)); err != nil { + t.Fatal(err) + } + if c.ciRefetch.pendingCount() != 1 { + t.Fatalf("fan-out must coalesce to one pending head, got %d", c.ciRefetch.pendingCount()) + } + + got := HeadCIActivity("org/repo", "sha-7", nil) + if got == nil || got.Source != "github-webhook" || got.ObservedAt == nil || !got.ObservedAt.Equal(clock.now) { + t.Fatalf("merged activity = %+v, want webhook-sourced, observed at the last delivery", got) + } + want := map[string]string{"unit": "completed/success", "lint": "completed/failure"} + if len(got.Checks) != len(want) { + t.Fatalf("checks = %+v, want %v", got.Checks, want) + } + for _, check := range got.Checks { + if want[check.Name] != check.State+"/"+check.Conclusion { + t.Fatalf("check %s = %s/%s, want %s", check.Name, check.State, check.Conclusion, want[check.Name]) + } + if check.Head != "sha-7" || check.AppID == nil || *check.AppID != githubActionsAppID { + t.Fatalf("check %+v must carry the head and producing App", check) + } + } + // A bare configured name resolves to the same head. + if bare := HeadCIActivity("repo", "sha-7", nil); bare == nil || len(bare.Checks) != 2 { + t.Fatalf("bare repo lookup = %+v", bare) + } + // An out-of-order re-delivery of the older in_progress run must not + // roll the completed result back. + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "in_progress", "", clock.now.Add(-time.Hour))); err != nil { + t.Fatal(err) + } + for _, check := range HeadCIActivity("org/repo", "sha-7", nil).Checks { + if check.Name == "unit" && check.Conclusion != "success" { + t.Fatalf("stale re-delivery rolled unit back: %+v", check) + } + } + health := WebhookHealthSnapshot() + if health.CIEvents1h != 4 || health.CIEventsApplied1h != 4 || health.LastCIEventAt == nil || health.CIRefetches1h != 0 { + t.Fatalf("webhook health CI block = %+v", health) + } +} + +// Delivered checks lay over the cycle's listing: a newer delivery replaces +// the listed run of the same check, the required set the listing resolved +// is kept, and a listing taken after the deliveries supersedes them. +func TestHeadCIActivityMergesDeliveriesOverListing(t *testing.T) { + clock := &webhookTestClock{now: time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)} + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + t.Cleanup(resetWebhookTrackerForTest(clock.Now)) + listedAt := clock.now + appID := githubActionsAppID + listed := &PRCIActivity{Head: "sha-1", Source: "github-check-runs", ObservedAt: &listedAt, + RequiredKnown: true, Required: []string{"lint", "unit"}, RequiredSource: "protection", + RequiredChecks: []PRRequiredCheck{{Name: "lint", AppKnown: true, AppID: &appID}, {Name: "unit", AppKnown: true, AppID: &appID}}, + Checks: []PRActivityCheck{ + {Name: "lint", State: "completed", Conclusion: "success", NodeID: "CR_lint", AppID: &appID, Head: "sha-1"}, + {Name: "unit", State: "in_progress", NodeID: "CR_unit", AppID: &appID, Head: "sha-1"}, + }} + sharedCIEvidence().recordListed("org/repo", "sha-1", listed) + + // The tracker's base (the status snapshot's copy) is the same listing. + if got := HeadCIActivity("org/repo", "sha-1", listed); !reflect.DeepEqual(got, listed) { + t.Fatalf("no deliveries: merged = %+v, want the listing unchanged", got) + } + + clock.now = clock.now.Add(time.Minute) + done := clock.now + n := RecordCIEvidenceForTest("org/repo", "sha-1", []PRActivityCheck{{Name: "unit", State: "completed", Conclusion: "success", NodeID: "CR_unit", AppID: &appID, Since: &done}}) + if n != 1 { + t.Fatalf("applied = %d", n) + } + got := HeadCIActivity("org/repo", "sha-1", listed) + if got.Source != "github-check-runs+github-webhook" || !got.RequiredKnown || !reflect.DeepEqual(got.Required, []string{"lint", "unit"}) { + t.Fatalf("merged = %+v, want listing's required set with webhook source", got) + } + if len(got.Checks) != 2 { + t.Fatalf("checks = %+v, want unit replaced not appended", got.Checks) + } + for _, check := range got.Checks { + if check.Name == "unit" && (check.State != "completed" || check.Conclusion != "success") { + t.Fatalf("unit = %+v, want the delivered completion", check) + } + } + if len(listed.Checks) != 2 || listed.Checks[1].State != "in_progress" { + t.Fatalf("merge mutated the caller's base: %+v", listed.Checks) + } + if got.ObservedAt == nil || !got.ObservedAt.Equal(done) { + t.Fatalf("observed_at = %v, want the delivery time %v", got.ObservedAt, done) + } + + // A fresher listing (the next cycle) carries the delivered result + // itself; the stored deliveries are dropped and the listing wins. + clock.now = clock.now.Add(time.Minute) + relistedAt := clock.now + relisted := cloneCIActivity(listed) + relisted.ObservedAt = &relistedAt + relisted.Checks[1] = PRActivityCheck{Name: "unit", State: "completed", Conclusion: "failure", NodeID: "CR_unit", AppID: &appID, Head: "sha-1"} + sharedCIEvidence().recordListed("org/repo", "sha-1", relisted) + if got := HeadCIActivity("org/repo", "sha-1", nil); !strings.HasSuffix(got.Source, "github-check-runs") || got.Checks[1].Conclusion != "failure" { + t.Fatalf("after re-listing merged = %+v, want the listing alone", got) + } + // A stale base from the snapshot (older than the store's listing) does + // not win over it either. + if got := HeadCIActivity("org/repo", "sha-1", listed); got.Checks[1].Conclusion != "failure" { + t.Fatalf("older base won over the newer listing: %+v", got.Checks) + } + // Another head is untouched. + if got := HeadCIActivity("org/repo", "sha-2", nil); got != nil { + t.Fatalf("other head = %+v, want nil", got) + } +} + +// A `status` delivery becomes a commit_status observation (the legacy +// context side the required-check merge reads), and a `workflow_job` +// delivery is the Actions check run it describes. +func TestWebhookCIChecksStatusAndWorkflowJob(t *testing.T) { + c, clock := setupWebhookCacheTest(t) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { return &ciTestTimer{} }} + c.storePRDetail("repo", 3, testPRDetail(3, "sha-3", clock.now, "clean")) + + status := []byte(`{"id":91,"node_id":"SC_91","sha":"sha-3","state":"success","context":"dco","target_url":"https://dco/3","created_at":"2026-10-08T12:00:00Z","repository":{"full_name":"org/repo"}}`) + res, err := c.HandleWebhookEvent("status", status) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 1 { + t.Fatalf("status delivery: res=%+v err=%v", res.CIEvidence, err) + } + job := []byte(`{"action":"completed","repository":{"full_name":"org/repo"},"workflow_job":{"id":501,"node_id":"WJ_501","head_sha":"sha-3","name":"gate","status":"completed","conclusion":"success","html_url":"https://gh/job/501","started_at":"2026-10-08T11:58:00Z","completed_at":"2026-10-08T12:00:00Z"}}`) + res, err = c.HandleWebhookEvent("workflow_job", job) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 1 || !reflect.DeepEqual(res.Invalidated, []int{3}) { + t.Fatalf("workflow_job delivery: res=%+v invalidated=%v err=%v", res.CIEvidence, res.Invalidated, err) + } + got := HeadCIActivity("org/repo", "sha-3", nil) + if got == nil || len(got.Checks) != 2 { + t.Fatalf("merged = %+v", got) + } + byName := map[string]PRActivityCheck{} + for _, check := range got.Checks { + byName[check.Name] = check + } + if dco := byName["dco"]; dco.Kind != "commit_status" || dco.State != "completed" || dco.Conclusion != "success" || dco.NodeID != "SC_91" { + t.Fatalf("dco = %+v", dco) + } + if gate := byName["gate"]; gate.AppID == nil || *gate.AppID != githubActionsAppID || gate.Conclusion != "success" || gate.URL != "https://gh/job/501" { + t.Fatalf("gate = %+v", gate) + } + // check_suite carries no per-check result: nothing applied, head kept + // pending for its re-read, and a non-CI event reports no evidence. + suite := []byte(`{"action":"completed","repository":{"full_name":"org/repo"},"check_suite":{"head_sha":"sha-3","conclusion":"success","pull_requests":[{"number":3}],"app":{"name":"GitHub Actions"}}}`) + res, err = c.HandleWebhookEvent("check_suite", suite) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 0 || !res.CIEvidence.Refetch { + t.Fatalf("check_suite delivery: res=%+v err=%v", res.CIEvidence, err) + } + pr := []byte(`{"action":"synchronize","number":3,"pull_request":{"number":3,"state":"open"},"repository":{"full_name":"org/repo"}}`) + if res, err := c.HandleWebhookEvent("pull_request", pr); err != nil || res.CIEvidence != nil { + t.Fatalf("pull_request delivery must carry no CI evidence: %+v err=%v", res.CIEvidence, err) + } +} + +// The coalesced re-read lists the head's check runs once for any number +// of deliveries, records the result as the head's listing (so later +// deliveries lay over it) and tells the hook; its REST caller tag is its +// own. Required checks are resolved only when the PR's base is known. +func TestWebhookCIRefetchListsHeadOnceAndRecordsListing(t *testing.T) { + clock := &webhookTestClock{now: time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)} + t.Cleanup(resetPRDetailCacheForTest(clock.Now, 0)) + t.Cleanup(resetWebhookTrackerForTest(clock.Now)) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + listings := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/repos/org/repo/commits/sha-9/check-runs" { + t.Errorf("unexpected GitHub call %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + return + } + listings++ + _ = json.NewEncoder(w).Encode(gh.ListCheckRunsResults{Total: gh.Ptr(2), CheckRuns: []*gh.CheckRun{ + {ID: gh.Ptr(int64(1)), NodeID: gh.Ptr("CR_1"), Name: gh.Ptr("unit"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success"), HeadSHA: gh.Ptr("sha-9"), App: &gh.App{ID: gh.Ptr(githubActionsAppID)}}, + {ID: gh.Ptr(int64(2)), NodeID: gh.Ptr("CR_2"), Name: gh.Ptr("lint"), Status: gh.Ptr("in_progress"), HeadSHA: gh.Ptr("sha-9"), App: &gh.App{ID: gh.Ptr(githubActionsAppID)}}, + }}) + })) + t.Cleanup(srv.Close) + c := newTestClient(t, srv, "org", []string{"repo"}) + var fired func() + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { fired = f; return &ciTestTimer{} }} + c.storePRDetail("repo", 9, testPRDetail(9, "sha-9", clock.now, "clean")) + var hooked []string + SetCIEvidenceHook(func(repo, head string) { hooked = append(hooked, repo+"@"+head) }) + t.Cleanup(func() { SetCIEvidenceHook(nil) }) + + suite := []byte(`{"action":"requested","repository":{"full_name":"org/repo"},"check_suite":{"head_sha":"sha-9","pull_requests":[{"number":9}],"app":{"name":"GitHub Actions"}}}`) + for i := 0; i < 3; i++ { + if _, err := c.HandleWebhookEvent("check_suite", suite); err != nil { + t.Fatal(err) + } + } + if c.ciRefetch.pendingCount() != 1 || fired == nil { + t.Fatalf("pending = %d, want 1 coalesced head", c.ciRefetch.pendingCount()) + } + fired() + if listings != 1 { + t.Fatalf("check-run listings = %d, want 1", listings) + } + if !sharedCIEvidence().hasListed("org/repo", "sha-9") || c.ciRefetch.pendingCount() != 0 { + t.Fatal("re-read did not record the head's listing") + } + if !reflect.DeepEqual(hooked, []string{"org/repo@sha-9"}) { + t.Fatalf("hook calls = %v", hooked) + } + got := HeadCIActivity("org/repo", "sha-9", nil) + if got == nil || got.Source != "github-check-runs" || len(got.Checks) != 2 || got.RequiredKnown { + t.Fatalf("listing = %+v, want two listed checks, required unknown without a base ref", got) + } + if WebhookHealthSnapshot().CIRefetches1h != 1 { + t.Fatalf("health = %+v, want one CI refetch", WebhookHealthSnapshot()) + } + // Now that a listing exists, a delivery lays over it without queuing + // another re-read. + clock.now = clock.now.Add(time.Minute) + res, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(9, "sha-9", "lint", "completed", "success", clock.now)) + if err != nil || res.CIEvidence.Refetch || c.ciRefetch.pendingCount() != 0 { + t.Fatalf("listed head must not re-read: %+v pending=%d err=%v", res.CIEvidence, c.ciRefetch.pendingCount(), err) + } + for _, check := range HeadCIActivity("org/repo", "sha-9", nil).Checks { + if check.Name == "lint" && check.Conclusion != "success" { + t.Fatalf("lint = %+v, want delivered completion over the listing", check) + } + } + if !strings.Contains(hooked[len(hooked)-1], "sha-9") || len(hooked) != 2 { + t.Fatalf("hook calls = %v, want the applied delivery to notify too", hooked) + } + // A context already cancelled makes the flush a no-op rather than a call. + c.ciRefetch.ctx = func() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + return ctx + } + c.ciRefetch.enqueue(ciRefetchTarget{repo: "repo", fullName: "org/repo", head: "sha-9", number: 9}) + c.FlushWebhookCIRefetch() + if listings != 1 { + t.Fatalf("cancelled context still listed: %d", listings) + } +} diff --git a/src/pkg/github/workflow_approval.go b/src/pkg/github/workflow_approval.go new file mode 100644 index 0000000000..dc23eacf1c --- /dev/null +++ b/src/pkg/github/workflow_approval.go @@ -0,0 +1,130 @@ +package github + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PRWorkflowApproval records workflow runs on a PR head that GitHub holds +// behind its "approve and run workflows" gate (status action_required). Such +// runs create no check runs, so from the check-run listing alone the required +// checks simply look unreported; this is the evidence that they are in fact +// waiting on a person clicking Approve (hivecommons/hive#16599). +type PRWorkflowApproval struct { + Pending int `json:"pending"` + RunIDs []int64 `json:"run_ids,omitempty"` + Actor string `json:"actor,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` +} + +// WorkflowApprovalStatus is the workflow-run status GitHub reports while a +// run waits for a maintainer to approve it. +const WorkflowApprovalStatus = "action_required" + +// workflowApprovalCacheTTL bounds the extra workflow-run listing to one call +// per head per window; the cycle calls EnrichCIStatus far more often than a +// human approves workflows. +const workflowApprovalCacheTTL = 90 * time.Second + +type workflowApprovalEntry struct { + at time.Time + val *PRWorkflowApproval +} + +var workflowApprovalCache sync.Map // repo@sha → workflowApprovalEntry + +// workflowApprovalEvictAfter is how long a head's probe stays cached once +// it is no longer refreshed: heads that got pushed over or merged stop +// being probed, and their entries go with the next sweep of the map. +const workflowApprovalEvictAfter = 30 * time.Minute + +var workflowApprovalLastEvict atomic.Int64 // unix seconds + +// evictStaleWorkflowApprovals drops entries older than +// workflowApprovalEvictAfter, at most once per eviction window, so the +// package-global map stays bounded by the heads probed in the last half hour. +func evictStaleWorkflowApprovals(now time.Time) { + last := workflowApprovalLastEvict.Load() + if now.Unix()-last < int64(workflowApprovalEvictAfter/time.Second) { + return + } + if !workflowApprovalLastEvict.CompareAndSwap(last, now.Unix()) { + return + } + workflowApprovalCache.Range(func(key, value any) bool { + if e, ok := value.(workflowApprovalEntry); !ok || now.Sub(e.at) > workflowApprovalEvictAfter { + workflowApprovalCache.Delete(key) + } + return true + }) +} + +// workflowRunsAwaitingApproval lists the head's workflow runs and keeps the +// ones gated on approval. It returns nil when none are, or when the listing +// failed: absence of evidence is not evidence. +func (c *Client) workflowRunsAwaitingApproval(ctx context.Context, repo, sha string) *PRWorkflowApproval { + if c == nil || c.client == nil || strings.TrimSpace(sha) == "" { + return nil + } + key := repo + "@" + sha + evictStaleWorkflowApprovals(time.Now()) + if cached, ok := workflowApprovalCache.Load(key); ok { + if e, ok := cached.(workflowApprovalEntry); ok && time.Since(e.at) < workflowApprovalCacheTTL { + return e.val + } + } + owner, name := c.splitRepo(repo) + runs, _, err := c.client.Actions.ListRepositoryWorkflowRuns(WithRESTCaller(ctx, "hive:workflow_approval"), owner, name, &gh.ListWorkflowRunsOptions{ + HeadSHA: sha, + ListOptions: gh.ListOptions{PerPage: 100}, + }) + if err != nil || runs == nil { + c.logger.Debug("failed to list workflow runs for head", "repo", repo, "sha", sha, "error", err) + return nil + } + val := workflowApprovalFromRuns(runs.WorkflowRuns, time.Now().UTC()) + workflowApprovalCache.Store(key, workflowApprovalEntry{at: time.Now(), val: val}) + return val +} + +// workflowApprovalFromRuns is the pure half: the approval-gated subset of a +// head's workflow runs, or nil when the head has none. +func workflowApprovalFromRuns(runs []*gh.WorkflowRun, now time.Time) *PRWorkflowApproval { + var out *PRWorkflowApproval + for _, run := range runs { + if run == nil { + continue + } + if run.GetStatus() != WorkflowApprovalStatus && run.GetConclusion() != WorkflowApprovalStatus { + continue + } + if out == nil { + at := now.UTC() + out = &PRWorkflowApproval{ObservedAt: &at} + } + out.Pending++ + if id := run.GetID(); id != 0 { + out.RunIDs = append(out.RunIDs, id) + } + if out.Actor == "" { + if actor := run.GetActor().GetLogin(); actor != "" { + out.Actor = actor + } else if actor := run.GetTriggeringActor().GetLogin(); actor != "" { + out.Actor = actor + } + } + } + return out +} + +// forgetWorkflowApproval drops the cached probe for a head so the next +// cycle re-lists: called when a CI webhook for the head arrives (someone +// approved, a run started) and after the hive approves runs itself. +func forgetWorkflowApproval(repo, sha string) { + workflowApprovalCache.Delete(repo + "@" + sha) +} diff --git a/src/pkg/github/workflow_approval_test.go b/src/pkg/github/workflow_approval_test.go new file mode 100644 index 0000000000..a9cacfc97a --- /dev/null +++ b/src/pkg/github/workflow_approval_test.go @@ -0,0 +1,69 @@ +package github + +import ( + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func TestWorkflowApprovalFromRuns(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + runs := []*gh.WorkflowRun{ + nil, + {ID: gh.Ptr(int64(1)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success")}, + {ID: gh.Ptr(int64(2)), Status: gh.Ptr(WorkflowApprovalStatus), Actor: &gh.User{Login: gh.Ptr("dependabot[bot]")}}, + {ID: gh.Ptr(int64(3)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr(WorkflowApprovalStatus)}, + {ID: gh.Ptr(int64(4)), Status: gh.Ptr("in_progress")}, + } + got := workflowApprovalFromRuns(runs, now) + if got == nil { + t.Fatal("expected approval evidence") + } + if got.Pending != 2 || len(got.RunIDs) != 2 || got.RunIDs[0] != 2 || got.RunIDs[1] != 3 { + t.Fatalf("pending=%d ids=%v", got.Pending, got.RunIDs) + } + if got.Actor != "dependabot[bot]" { + t.Fatalf("actor=%q", got.Actor) + } + if got.ObservedAt == nil || !got.ObservedAt.Equal(now) { + t.Fatalf("observed_at=%v", got.ObservedAt) + } + if workflowApprovalFromRuns(runs[:2], now) != nil { + t.Fatal("no gated runs must yield nil, not an empty record") + } +} + +func TestCloneCIActivityCopiesWorkflowApproval(t *testing.T) { + src := &PRCIActivity{Head: "abc", WorkflowApproval: &PRWorkflowApproval{Pending: 1, RunIDs: []int64{7}}} + out := cloneCIActivity(src) + out.WorkflowApproval.RunIDs[0] = 9 + out.WorkflowApproval.Pending = 5 + if src.WorkflowApproval.RunIDs[0] != 7 || src.WorkflowApproval.Pending != 1 { + t.Fatal("clone shares workflow approval with its source") + } +} + +func TestWorkflowApprovalCacheEvictsAndForgets(t *testing.T) { + workflowApprovalCache.Store("org/repo@old", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + workflowApprovalCache.Store("org/repo@fresh", workflowApprovalEntry{at: time.Now()}) + workflowApprovalLastEvict.Store(0) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old"); ok { + t.Fatal("stale entry survived eviction") + } + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); !ok { + t.Fatal("fresh entry evicted") + } + // Within the window the sweep is a no-op even for stale entries. + workflowApprovalCache.Store("org/repo@old2", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old2"); !ok { + t.Fatal("eviction ran again inside its window") + } + forgetWorkflowApproval("org/repo", "fresh") + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); ok { + t.Fatal("forget left the entry") + } + workflowApprovalCache.Delete("org/repo@old2") +} diff --git a/src/pkg/governor/fixer_queue.go b/src/pkg/governor/fixer_queue.go new file mode 100644 index 0000000000..5c2688a2d0 --- /dev/null +++ b/src/pkg/governor/fixer_queue.go @@ -0,0 +1,95 @@ +package governor + +import ( + "sort" + "strings" + "time" +) + +// FixerQueueStatus describes a PR awaiting delivery of its fix kick. Ahead is +// a pointer so the first queued PR emits zero while an unqueued PR omits it. +type FixerQueueStatus struct { + FixerQueuePosition int `json:"fixer_queue_position,omitempty"` + FixerQueueAhead *int `json:"fixer_queue_ahead,omitempty"` +} + +type deferredFixKick struct { + ref string + firstDeferredAt time.Time +} + +// RecordFixKickDeferred preserves the first deferral across retries, new heads +// and fixer reassignment. This is visibility bookkeeping, not a dispatch gate. +func (g *Governor) RecordFixKickDeferred(ref string, at time.Time) { + ref = strings.ToLower(strings.TrimSpace(ref)) + if g == nil || ref == "" { + return + } + g.mu.Lock() + defer g.mu.Unlock() + for _, kick := range g.deferredFixKicks { + if kick.ref == ref { + return + } + } + g.deferredFixKicks = append(g.deferredFixKicks, deferredFixKick{ref: ref, firstDeferredAt: at}) + // Stable sorting keeps dispatch order when several deferrals share a clock + // tick. Later retries never reset the timestamp or move an entry back. + sort.SliceStable(g.deferredFixKicks, func(i, j int) bool { + return g.deferredFixKicks[i].firstDeferredAt.Before(g.deferredFixKicks[j].firstDeferredAt) + }) +} + +// RecordFixKickDelivered removes a PR only after its fix kick actually lands. +func (g *Governor) RecordFixKickDelivered(ref string) { + ref = strings.ToLower(strings.TrimSpace(ref)) + if g == nil { + return + } + g.mu.Lock() + defer g.mu.Unlock() + for i, kick := range g.deferredFixKicks { + if kick.ref == ref { + g.deferredFixKicks = append(g.deferredFixKicks[:i], g.deferredFixKicks[i+1:]...) + return + } + } +} + +// ReconcileFixerQueue drops PRs absent from keep: the enumeration's open-PR +// set (PRs closed or merged while their fixer was busy) or the current plan's +// fix-kick refs (PRs that no longer need a fix). +func (g *Governor) ReconcileFixerQueue(keep map[string]bool) { + if g == nil { + return + } + g.mu.Lock() + defer g.mu.Unlock() + kept := g.deferredFixKicks[:0] + for _, kick := range g.deferredFixKicks { + if keep[kick.ref] { + kept = append(kept, kick) + } + } + g.deferredFixKicks = kept +} + +// FixerQueue returns an independent snapshot keyed by owner/repo#number. +// Entries are one-based and reflect first-deferral age across all fixer lanes. +// The queue is in memory: after restart, dispatch rebuilds it from busy kicks. +func (g *Governor) FixerQueue() map[string]FixerQueueStatus { + if g == nil { + return nil + } + g.mu.RLock() + defer g.mu.RUnlock() + if len(g.deferredFixKicks) == 0 { + return nil + } + out := make(map[string]FixerQueueStatus, len(g.deferredFixKicks)) + for i, kick := range g.deferredFixKicks { + ahead := i + out[kick.ref] = FixerQueueStatus{FixerQueuePosition: i + 1, FixerQueueAhead: &ahead} + } + return out +} diff --git a/src/pkg/governor/fixer_queue_test.go b/src/pkg/governor/fixer_queue_test.go new file mode 100644 index 0000000000..d865ce8fa8 --- /dev/null +++ b/src/pkg/governor/fixer_queue_test.go @@ -0,0 +1,72 @@ +package governor + +import ( + "encoding/json" + "testing" + "time" +) + +func TestFixerQueueFirstDeferralDeliveryAndClosure(t *testing.T) { + g := &Governor{} + at := time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC) + g.RecordFixKickDeferred("org/repo#2", at.Add(time.Minute)) + g.RecordFixKickDeferred("ORG/REPO#1", at) + g.RecordFixKickDeferred("org/other#1", at.Add(time.Minute)) + // A retry must preserve its original position, including equal-time ties. + g.RecordFixKickDeferred("org/repo#1", at.Add(time.Hour)) + assertFixerQueue(t, g.FixerQueue(), "org/repo#1", "org/repo#2", "org/other#1") + + // Returned maps and ahead pointers cannot mutate governor state. + snapshot := g.FixerQueue() + *snapshot["org/repo#2"].FixerQueueAhead = 99 + delete(snapshot, "org/repo#1") + assertFixerQueue(t, g.FixerQueue(), "org/repo#1", "org/repo#2", "org/other#1") + + g.RecordFixKickDelivered("ORG/REPO#1") + assertFixerQueue(t, g.FixerQueue(), "org/repo#2", "org/other#1") + g.ReconcileFixerQueue(map[string]bool{"org/other#1": true}) + assertFixerQueue(t, g.FixerQueue(), "org/other#1") + g.RecordFixKickDelivered("org/other#1") + if got := g.FixerQueue(); len(got) != 0 { + t.Fatalf("delivered PRs still queued: %+v", got) + } + // A newly deferred kick after delivery starts a fresh wait. + g.RecordFixKickDeferred("org/repo#2", at.Add(2*time.Hour)) + g.RecordFixKickDeferred("org/other#1", at.Add(3*time.Hour)) + assertFixerQueue(t, g.FixerQueue(), "org/repo#2", "org/other#1") + g.ReconcileFixerQueue(nil) + assertFixerQueue(t, g.FixerQueue()) +} + +func assertFixerQueue(t *testing.T, got map[string]FixerQueueStatus, refs ...string) { + t.Helper() + if len(got) != len(refs) { + t.Fatalf("queue = %+v, want %v", got, refs) + } + for i, ref := range refs { + entry := got[ref] + if entry.FixerQueuePosition != i+1 || entry.FixerQueueAhead == nil || *entry.FixerQueueAhead != i { + t.Fatalf("%s = %+v, want position %d / ahead %d", ref, entry, i+1, i) + } + } +} + +func TestFixerQueueJSONOptionalFields(t *testing.T) { + for _, tc := range []struct { + status FixerQueueStatus + want string + }{ + {FixerQueueStatus{}, `{}`}, + {FixerQueueStatus{FixerQueuePosition: 1, FixerQueueAhead: new(int)}, `{"fixer_queue_position":1,"fixer_queue_ahead":0}`}, + } { + got, err := json.Marshal(tc.status) + if err != nil || string(got) != tc.want { + t.Fatalf("json = %s (%v), want %s", got, err, tc.want) + } + } + var g *Governor + g.RecordFixKickDeferred("org/repo#1", time.Now()) + g.RecordFixKickDelivered("org/repo#1") + g.ReconcileFixerQueue(nil) + assertFixerQueue(t, g.FixerQueue()) +} diff --git a/src/pkg/governor/governor.go b/src/pkg/governor/governor.go index cc5f0cf9b7..8b82f6aa28 100644 --- a/src/pkg/governor/governor.go +++ b/src/pkg/governor/governor.go @@ -265,6 +265,7 @@ type Governor struct { modeHistory []ModeChange evalHistory []EvalSnapshot kickHistory []KickRecord + deferredFixKicks []deferredFixKick agentReports map[string]AgentReportRecord kickOutcomes map[string]KickOutcomeRecord budget BudgetInfo diff --git a/src/pkg/hub/spoke/cluster_metrics.go b/src/pkg/hub/spoke/cluster_metrics.go index fe5f1c98dc..aef70da225 100644 --- a/src/pkg/hub/spoke/cluster_metrics.go +++ b/src/pkg/hub/spoke/cluster_metrics.go @@ -31,10 +31,15 @@ const ( // before running kubectl again. Prevents running kubectl on every heartbeat. const metricsCollectionCacheTTL = 60 * time.Second -// metricsCollectionTimeout bounds how long we wait for each kubectl command -// during spoke-side metrics collection. +// metricsCollectionTimeout bounds individual Kubernetes API requests, including +// callers outside cluster-health collection. const metricsCollectionTimeout = 10 * time.Second +// clusterHealthCollectionTimeout is shared by all cluster-health API requests. +// Leave most of the heartbeat collect budget for its other collectors; granting +// every node proxy request a fresh timeout can otherwise stall many beats. +const clusterHealthCollectionTimeout = 3 * time.Second + // nodeHealthWarningInterval prevents a permanently missing/forbidden node API // from writing the same warning on every heartbeat. const nodeHealthWarningInterval = time.Hour @@ -75,9 +80,15 @@ func CollectClusterHealth(logger *slog.Logger) *HeartbeatClusterHealthReport { } func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthReport { + ctx, cancel := context.WithTimeout(context.Background(), clusterHealthCollectionTimeout) + defer cancel() + return collectClusterHealthWithContext(ctx, logger) +} + +func collectClusterHealthWithContext(ctx context.Context, logger *slog.Logger) *HeartbeatClusterHealthReport { // Query nodes first. The core Node API has the capacity/allocatable data // needed for useful totals even when metrics-server is absent or forbidden. - getOut, err := k8sAPIGet("/api/v1/nodes") + getOut, err := k8sAPIGetWithContext(ctx, "/api/v1/nodes") if err != nil { reason := nodeHealthErrorReason("nodes API failed", err) logNodeHealthWarning(logger, reason) @@ -179,7 +190,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // the hub so the UI can tell operators exactly what to fix. metricsByNode := make(map[string]map[string]string) nodeHealthError := "" - topOut, err := k8sAPIGet("/apis/metrics.k8s.io/v1beta1/nodes") + topOut, err := k8sAPIGetWithContext(ctx, "/apis/metrics.k8s.io/v1beta1/nodes") if err != nil { nodeHealthError = nodeHealthErrorReason("metrics API failed", err) logNodeHealthWarning(logger, nodeHealthError) @@ -248,7 +259,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // The node object's ephemeral-storage capacity cannot tell us how full the // disk is. Best-effort per node: a failure leaves usage/percent nil while // retaining capacity above. - if rawStats, statsErr := k8sAPIGet(nodeStatsSummaryPath(name)); statsErr != nil { + if rawStats, statsErr := k8sAPIGetWithContext(ctx, nodeStatsSummaryPath(name)); statsErr != nil { if logger != nil { logger.Debug("spoke metrics: node disk stats unavailable", "node", name, "error", statsErr) } @@ -269,7 +280,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // already assigned to a node are missed), so the capacity estimate below // can be marginally optimistic. var cpuRequestedPerNode, memRequestedPerNode map[string]int64 - podOut, err := k8sAPIGet("/api/v1/pods?fieldSelector=status.phase%3DRunning") + podOut, err := k8sAPIGetWithContext(ctx, "/api/v1/pods?fieldSelector=status.phase%3DRunning") if err != nil { if nodeHealthError == "" { nodeHealthError = nodeHealthErrorReason("pods API failed", err) @@ -515,6 +526,15 @@ func k8sTLSConfig() (*tls.Config, error) { } func k8sAPIGet(path string) ([]byte, error) { + return k8sAPIGetWithContext(context.Background(), path) +} + +func k8sAPIGetWithContext(ctx context.Context, path string) ([]byte, error) { + // Once the collection budget is exhausted, skip remaining node requests + // without repeatedly reading credentials or creating transports. + if err := ctx.Err(); err != nil { + return nil, err + } token, err := os.ReadFile(k8sTokenPath) if err != nil { return nil, fmt.Errorf("reading service account token: %w", err) @@ -530,7 +550,7 @@ func k8sAPIGet(path string) ([]byte, error) { Transport: &http.Transport{TLSClientConfig: tlsConfig}, } - ctx, cancel := context.WithTimeout(context.Background(), metricsCollectionTimeout) + ctx, cancel := context.WithTimeout(ctx, metricsCollectionTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, k8sAPIServer+path, nil) diff --git a/src/pkg/hub/spoke/cluster_metrics_budget_test.go b/src/pkg/hub/spoke/cluster_metrics_budget_test.go new file mode 100644 index 0000000000..3b1a5ce657 --- /dev/null +++ b/src/pkg/hub/spoke/cluster_metrics_budget_test.go @@ -0,0 +1,91 @@ +package spoke + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const budgetTestNodes = `{"items":[{"metadata":{"name":"node-a"},"status":{"allocatable":{"cpu":"4","memory":"8Gi"},"conditions":[{"type":"Ready","status":"True"}]}}]}` + +func TestClusterHealthCollectionBudget(t *testing.T) { + // A stalled API must leave time for the rest of heartbeat collection, even + // on a cold cache. Previously this consumed the entire heartbeat budget. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + defer srv.Close() + withFakeK8sAPI(t, srv) + + start := time.Now() + report := collectClusterHealthUncached(nil) + if elapsed := time.Since(start); elapsed >= heartbeatTimeout { + t.Fatalf("cluster health took %s, exhausted heartbeat budget %s", elapsed, heartbeatTimeout) + } + if report == nil || !strings.Contains(report.NodeHealthError, "context deadline exceeded") { + t.Fatalf("expected partial report with deadline error, got %+v", report) + } +} + +func TestClusterHealthSharesContextAcrossRequests(t *testing.T) { + for _, stallPath := range []string{ + "/api/v1/nodes", + "/apis/metrics.k8s.io/v1beta1/nodes", + nodeStatsSummaryPath("node-a"), + "/api/v1/pods", + } { + t.Run(stallPath, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == stallPath { + // Expire the shared collection context while this request is + // in flight. Later requests must use the same spent budget. + cancel() + <-r.Context().Done() + return + } + if ctx.Err() != nil { + t.Errorf("API request after collection cancellation: %s", r.URL.Path) + } + if r.URL.Path == "/api/v1/nodes" { + _, _ = w.Write([]byte(budgetTestNodes)) + } else { + _, _ = w.Write([]byte(`{"items":[]}`)) + } + })) + defer srv.Close() + withFakeK8sAPI(t, srv) + + report := collectClusterHealthWithContext(ctx, nil) + if report == nil || !strings.Contains(report.NodeHealthError, "context canceled") { + t.Fatalf("expected partial report with cancellation error, got %+v", report) + } + if stallPath != "/api/v1/nodes" { + if report.Summary.TotalNodes != 1 || report.Summary.TotalCPUCores != 4 || report.Summary.TotalMemGB != 8 { + t.Fatalf("lost node capacity after cancellation: %+v", report.Summary) + } + if report.Summary.HiveCapacityRemaining != nil { + t.Fatal("capacity estimate should be unavailable without pod requests") + } + if report.Nodes[0].DiskPercent != nil { + t.Fatal("missing disk usage must stay unavailable") + } + } + }) + } +} + +func TestK8sAPIGetSpentCollectionBudget(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + withMissingK8sToken(t) + _, err := k8sAPIGetWithContext(ctx, "/api/v1/nodes") + if !errors.Is(err, context.Canceled) { + t.Fatalf("spent budget should stop before credential access, got %v", err) + } +} diff --git a/src/pkg/hub/spoke/heartbeat.go b/src/pkg/hub/spoke/heartbeat.go index 714f76a60f..246d23b527 100644 --- a/src/pkg/hub/spoke/heartbeat.go +++ b/src/pkg/hub/spoke/heartbeat.go @@ -1441,6 +1441,13 @@ func StartHeartbeat(ctx context.Context, hubURL string, collect StatusCollector, } } + // A timeout cannot cancel a collector blocked on a mutex or NFS. Keep + // subsequent beats from starting more copies of that same blocked work. + collect = nonOverlappingHeartbeatCollector(collect) + if freshCollect != nil { + freshCollect = FreshStatusCollector(nonOverlappingHeartbeatCollector(StatusCollector(freshCollect))) + } + logger.Info("hub heartbeat enabled", "url", hubURL, "interval", interval) waitForReady(ctx, logger) @@ -1969,7 +1976,8 @@ func collectWithTimeout(ctx context.Context, collect StatusCollector, timeout ti // outcome. Here we only note the timeout itself, then name the // sections that consumed the budget. logger.Warn("hub heartbeat collect timed out; loop keeps ticking so liveness stays green", - "timeout", timeout.String()) + "timeout", timeout.String(), + "slowest", timings.summary(collectTimingTopN)) logCollectTimeoutBreakdown(logger, timings, timeout) } return nil diff --git a/src/pkg/hub/spoke/heartbeat_collect_guard.go b/src/pkg/hub/spoke/heartbeat_collect_guard.go new file mode 100644 index 0000000000..99e308fe35 --- /dev/null +++ b/src/pkg/hub/spoke/heartbeat_collect_guard.go @@ -0,0 +1,18 @@ +package spoke + +import "sync" + +// nonOverlappingHeartbeatCollector bounds a loop to one active invocation of +// this collector, including invocations that outlive collectWithTimeout. Busy +// beats return nil immediately and use sendHeartbeat's stale/minimal fallback. +// The lock belongs to the loop, not to process-global test or payload state. +func nonOverlappingHeartbeatCollector(collect StatusCollector) StatusCollector { + var active sync.Mutex + return func() *HeartbeatPayload { + if !active.TryLock() { + return nil + } + defer active.Unlock() // also release when the timeout helper recovers a panic + return collect() + } +} diff --git a/src/pkg/hub/spoke/heartbeat_collect_guard_test.go b/src/pkg/hub/spoke/heartbeat_collect_guard_test.go new file mode 100644 index 0000000000..477e133d72 --- /dev/null +++ b/src/pkg/hub/spoke/heartbeat_collect_guard_test.go @@ -0,0 +1,98 @@ +package spoke + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestNonOverlappingHeartbeatCollector_TimeoutRetryAndRecovery(t *testing.T) { + ResetHeartbeatStateForTest() + t.Cleanup(ResetHeartbeatStateForTest) + var calls atomic.Int32 + release := make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + collect := nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls.Add(1) + <-release + return &HeartbeatPayload{HiveID: "recovered"} + }) + + if got := collectWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("blocked collect returned %+v", got) + } + // Repeated beats must be able to fall back without queuing more work on + // the stuck dependency. Without the guard each call starts another copy. + for i := 0; i < 5; i++ { + if got := collectWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("busy collect returned %+v", got) + } + } + if got := calls.Load(); got != 1 { + t.Fatalf("started %d collectors while blocked, want 1", got) + } + + unblock() + // A late full payload still becomes last-good. Seeing the cache also + // proves the guard's lock was released before attempting a fresh collect. + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for loadLastGoodPayload() == nil { + select { + case <-deadline.C: + t.Fatal("late completion did not populate the fallback cache") + case <-tick.C: + } + } + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got == nil || got.HiveID != "recovered" { + t.Fatalf("collect did not recover after blocker cleared: %+v", got) + } + if got := calls.Load(); got != 2 { + t.Fatalf("collector calls after recovery = %d, want 2", got) + } +} + +func TestNonOverlappingHeartbeatCollector_PanicReleasesGuard(t *testing.T) { + calls := 0 + collect := nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls++ + if calls == 1 { + panic("collector failed") + } + return &HeartbeatPayload{HiveID: "recovered"} + }) + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got != nil { + t.Fatalf("panicking collect returned %+v", got) + } + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got == nil { + t.Fatal("panic left collector permanently busy") + } +} + +func TestNonOverlappingHeartbeatCollector_FreshStatsStayBounded(t *testing.T) { + var calls atomic.Int32 + release := make(chan struct{}) + finished := make(chan struct{}) + var finishOnce sync.Once + collect := FreshStatusCollector(nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls.Add(1) + <-release + defer finishOnce.Do(func() { close(finished) }) + return nil + })) + t.Cleanup(func() { close(release); <-finished }) + for i := 0; i < 5; i++ { + if got := collectFreshStatsWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("blocked fresh-stats collect returned %+v", got) + } + } + if got := calls.Load(); got != 1 { + t.Fatalf("started %d fresh-stats collectors while blocked, want 1", got) + } +} diff --git a/src/pkg/hub/spoke/heartbeat_collect_timing_test.go b/src/pkg/hub/spoke/heartbeat_collect_timing_test.go index 232af1f62d..58559d925e 100644 --- a/src/pkg/hub/spoke/heartbeat_collect_timing_test.go +++ b/src/pkg/hub/spoke/heartbeat_collect_timing_test.go @@ -126,6 +126,12 @@ func TestCollectWithTimeout_LogsSlowestSectionsOnTimeout(t *testing.T) { mu.Lock() out := buf.String() mu.Unlock() + // Self-report captures attributes from the original timeout record, not + // the separate breakdown record. Keep the culprit on that first warning. + first, _, _ := strings.Cut(out, "\n") + if !strings.Contains(first, "collect timed out;") || !strings.Contains(first, "evidence=") || !strings.Contains(first, "(in-flight)") { + t.Fatalf("timeout warning lacks the in-flight section: %s", first) + } if !strings.Contains(out, "slowest collectors") || !strings.Contains(out, "evidence=") || !strings.Contains(out, "(in-flight)") { t.Fatalf("timeout log lacks the per-section breakdown naming the in-flight collector:\n%s", out) } diff --git a/src/pkg/hub/webhook.go b/src/pkg/hub/webhook.go index 4612a42e42..b6dbe65dbd 100644 --- a/src/pkg/hub/webhook.go +++ b/src/pkg/hub/webhook.go @@ -95,7 +95,7 @@ func (s *HubServer) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) switch event { case "installation", "installation_repositories": s.handleInstallationEvent(body) - case "pull_request", "pull_request_review", "pull_request_review_comment", "check_suite", "check_run", "status", "issue_comment", "issues", "push": + case "pull_request", "pull_request_review", "pull_request_review_comment", "check_suite", "check_run", "workflow_run", "workflow_job", "status", "issue_comment", "issues", "push": s.relayWebhookToSpoke(event, r.Header, body) default: s.logger.Debug("ignoring webhook event", "event", event) diff --git a/src/pkg/intent/pin_only.go b/src/pkg/intent/pin_only.go index a9cb8c1d0c..bf4bf2cca6 100644 --- a/src/pkg/intent/pin_only.go +++ b/src/pkg/intent/pin_only.go @@ -4,6 +4,7 @@ import ( "fmt" "path" "regexp" + "slices" "strconv" "strings" ) @@ -22,6 +23,15 @@ var ( unsafePinRE = regexp.MustCompile(`(?i)(permissions|secrets[.]|\benv\b|\brun:|\bwith:|id-token|cosign|attest|provenance|credential|signing|codeowners)`) ) +// ActionPin is one accepted action-sha replacement: the upstream action +// repository ("owner/repo", without any sub-path), the new 40-hex commit, and +// the trailing version comment ("v4", "v4.1.2"; empty when absent). +type ActionPin struct { + Repo string + SHA string + Version string +} + // ClassifyPinOnly checks the entire supplied diff, not only guarded files: a // mixed PR must not acquire a pin-only exception. Every file must be an existing // modified file in both the actual human-merge matches and the exception paths. @@ -29,11 +39,21 @@ var ( // addition/deletion counts. Deliberately supports only narrow line grammars. // // Callers MUST separately prove a complete file list bound to the current head, -// authenticated trusted authorship, and review of each referenced upstream -// change. A true result proves syntax only, NEVER those facts or merge safety. +// authenticated trusted authorship, and that each new action SHA belongs to +// its upstream repository (ClassifyPinOnlyActions returns them). A true result +// proves syntax only, NEVER those facts or merge safety. func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (bool, string) { + ok, why, _ := ClassifyPinOnlyActions(files, matches, spec) + return ok, why +} + +// ClassifyPinOnlyActions is ClassifyPinOnly that also returns, on acceptance, +// the distinct action-sha pins it accepted. GitHub resolves a `uses:` SHA +// across the whole fork network of owner/repo, so the syntax alone does not +// tie the new SHA to the upstream action; the caller resolves each pin. +func ClassifyPinOnlyActions(files []ChangedFile, matches []string, spec PinOnlySpec) (bool, string, []ActionPin) { if len(files) == 0 || len(matches) == 0 || len(spec.Paths) == 0 || len(spec.Kinds) == 0 { - return false, "missing pin-only evidence or policy" + return false, "missing pin-only evidence or policy", nil } kinds := make(map[string]bool) for _, kind := range spec.Kinds { @@ -41,7 +61,7 @@ func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (b case "action-sha", "image-digest", "version-pin": kinds[kind] = true default: - return false, "unknown pin kind: " + kind + return false, "unknown pin kind: " + kind, nil } } guarded := make(map[string]bool) @@ -49,31 +69,39 @@ func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (b guarded[match] = true } seen := make(map[string]bool) + var pins []ActionPin for _, file := range files { name := file.Filename if name == "" || path.Clean(name) != name || strings.HasPrefix(name, "../") || strings.HasPrefix(name, "/") || seen[name] { - return false, "invalid or duplicate path: " + name + return false, "invalid or duplicate path: " + name, nil } seen[name] = true if !guarded[name] || !PathMatchesAny(name, spec.Paths) { - return false, name + ": outside approved human-merge paths" + return false, name + ": outside approved human-merge paths", nil } if strings.Contains(strings.ToLower(name), "owners") || file.Status != "modified" || file.Patch == "" { - return false, name + ": not an existing modified pin file with a patch" + return false, name + ": not an existing modified pin file with a patch", nil + } + filePins, err := classifyPinPatch(file, kinds) + if err != nil { + return false, name + ": " + err.Error(), nil } - if err := classifyPinPatch(file, kinds); err != nil { - return false, name + ": " + err.Error() + for _, pin := range filePins { + if !slices.Contains(pins, pin) { + pins = append(pins, pin) + } } } for match := range guarded { if !seen[match] { - return false, match + ": missing matched file" + return false, match + ": missing matched file", nil } } - return true, "all changes are approved pin replacements (syntax only)" + return true, "all changes are approved pin replacements (syntax only)", pins } -func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { +func classifyPinPatch(file ChangedFile, kinds map[string]bool) ([]ActionPin, error) { + var pins []ActionPin var removed, added []string oldLeft, newLeft, additions, deletions, hunks := 0, 0, 0, 0, 0 flush := func() error { @@ -81,9 +109,13 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { return fmt.Errorf("unpaired addition/removal") } for i := range removed { - if !pinReplacement(removed[i], added[i], kinds) { + pin, ok := matchPinReplacement(removed[i], added[i], kinds) + if !ok { return fmt.Errorf("non-pin or unsafe replacement") } + if pin != nil { + pins = append(pins, *pin) + } } removed, added = nil, nil return nil @@ -92,30 +124,30 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { for i, line := range lines { if m := pinHunkRE.FindStringSubmatch(line); m != nil { if err := flush(); err != nil { - return err + return nil, err } if oldLeft != 0 || newLeft != 0 { - return fmt.Errorf("incomplete hunk before line %d", i+1) + return nil, fmt.Errorf("incomplete hunk before line %d", i+1) } oldLeft, newLeft = 1, 1 var err error if m[1] != "" { oldLeft, err = strconv.Atoi(m[1]) if err != nil { - return fmt.Errorf("invalid old hunk count") + return nil, fmt.Errorf("invalid old hunk count") } } if m[2] != "" { newLeft, err = strconv.Atoi(m[2]) if err != nil { - return fmt.Errorf("invalid new hunk count") + return nil, fmt.Errorf("invalid new hunk count") } } hunks++ continue } if hunks == 0 { - return fmt.Errorf("invalid patch line %d", i+1) + return nil, fmt.Errorf("invalid patch line %d", i+1) } if line == "" { // GitHub renders blank context lines as "" rather than " ". @@ -124,13 +156,13 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { switch line[0] { case ' ': if err := flush(); err != nil { - return err + return nil, err } oldLeft-- newLeft-- case '-': if len(added) != 0 { - return fmt.Errorf("interleaved replacement") + return nil, fmt.Errorf("interleaved replacement") } removed = append(removed, line[1:]) deletions++ @@ -141,24 +173,31 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { newLeft-- default: // Even newline/format metadata is outside this bounded grammar. - return fmt.Errorf("unsupported patch line %d", i+1) + return nil, fmt.Errorf("unsupported patch line %d", i+1) } if oldLeft < 0 || newLeft < 0 { - return fmt.Errorf("hunk count exceeded") + return nil, fmt.Errorf("hunk count exceeded") } } if err := flush(); err != nil { - return err + return nil, err } if hunks == 0 || oldLeft != 0 || newLeft != 0 || additions == 0 || additions != file.Additions || deletions != file.Deletions { - return fmt.Errorf("incomplete patch or mismatched changed-line counts") + return nil, fmt.Errorf("incomplete patch or mismatched changed-line counts") } - return nil + return pins, nil } func pinReplacement(old, next string, kinds map[string]bool) bool { + _, ok := matchPinReplacement(old, next, kinds) + return ok +} + +// matchPinReplacement reports whether old -> next is an accepted pin +// replacement and, for an action-sha replacement, the new pin. +func matchPinReplacement(old, next string, kinds map[string]bool) (*ActionPin, bool) { if old == next || unsafePinRE.MatchString(old) || unsafePinRE.MatchString(next) { - return false + return nil, false } for _, kind := range []string{"action-sha", "image-digest", "version-pin"} { if !kinds[kind] { @@ -181,7 +220,7 @@ func pinReplacement(old, next string, kinds map[string]bool) bool { if strings.Contains(a[3], "#") != strings.Contains(b[3], "#") { continue } - return true + return actionPinFrom(b), true } if kind == "version-pin" { // Do not permit quote changes to alter YAML interpretation. @@ -200,8 +239,21 @@ func pinReplacement(old, next string, kinds map[string]bool) bool { } } if a[3] == b[3] { - return true + return nil, true } } - return false + return nil, false +} + +// actionPinFrom builds the pin from an actionPinRE match of the new line. +func actionPinFrom(m []string) *ActionPin { + ref := strings.TrimSpace(m[1]) + ref = strings.TrimPrefix(ref, "- ") + ref = strings.TrimSuffix(strings.TrimPrefix(ref, "uses: "), "@") + parts := strings.SplitN(ref, "/", 3) + return &ActionPin{ + Repo: parts[0] + "/" + parts[1], + SHA: strings.ToLower(m[2]), + Version: strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(m[3]), "#")), + } } diff --git a/src/pkg/intent/pin_only_test.go b/src/pkg/intent/pin_only_test.go index 68a883bfdc..8a740a4b64 100644 --- a/src/pkg/intent/pin_only_test.go +++ b/src/pkg/intent/pin_only_test.go @@ -1,6 +1,7 @@ package intent import ( + "slices" "strings" "testing" ) @@ -117,3 +118,38 @@ func TestPinReplacementNarrowGrammar(t *testing.T) { } } } + +func TestClassifyPinOnlyActionsReturnsAcceptedPins(t *testing.T) { + sha := func(c string) string { return strings.Repeat(c, 40) } + spec := PinOnlySpec{Paths: []string{".github/workflows/*.yml", "Containerfile"}, Kinds: []string{"action-sha", "image-digest"}} + workflow := ChangedFile{Filename: ".github/workflows/build.yml", Status: "modified", Additions: 3, Deletions: 3, Patch: "@@ -1,5 +1,5 @@\n" + + "- - uses: actions/checkout@" + sha("a") + " # v4\n" + + "+ - uses: actions/checkout@" + strings.ToUpper(sha("b")) + " # v4.2.1\n" + + " context\n" + + "- uses: github/codeql-action/init@" + sha("c") + "\n" + + "+ uses: github/codeql-action/init@" + sha("d") + "\n" + + " more context\n" + + "- - uses: actions/checkout@" + sha("a") + " # v4\n" + + "+ - uses: actions/checkout@" + sha("b") + " # v4.2.1"} + image := ChangedFile{Filename: "Containerfile", Status: "modified", Additions: 1, Deletions: 1, + Patch: "@@ -1 +1 @@\n-FROM ghcr.io/org/image@sha256:" + strings.Repeat("a", 64) + "\n+FROM ghcr.io/org/image@sha256:" + strings.Repeat("b", 64)} + ok, why, pins := ClassifyPinOnlyActions([]ChangedFile{workflow, image}, []string{workflow.Filename, image.Filename}, spec) + if !ok { + t.Fatalf("refused: %s", why) + } + want := []ActionPin{ + {Repo: "actions/checkout", SHA: sha("b"), Version: "v4.2.1"}, + {Repo: "github/codeql-action", SHA: sha("d")}, + } + if !slices.Equal(pins, want) { + t.Fatalf("pins = %+v, want %+v", pins, want) + } + if ok, _, pins := ClassifyPinOnlyActions([]ChangedFile{image}, []string{image.Filename}, spec); !ok || len(pins) != 0 { + t.Fatalf("image-only diff: ok=%v pins=%+v, want accepted with no action pins", ok, pins) + } + workflow.Patch += "\n+ - run: evil" + workflow.Additions++ + if ok, _, pins := ClassifyPinOnlyActions([]ChangedFile{workflow}, []string{workflow.Filename}, spec); ok || pins != nil { + t.Fatalf("refused diff: ok=%v pins=%+v, want no pins", ok, pins) + } +} diff --git a/src/pkg/issueclaim/issueclaim.go b/src/pkg/issueclaim/issueclaim.go index 0b481814ec..8f563ae148 100644 --- a/src/pkg/issueclaim/issueclaim.go +++ b/src/pkg/issueclaim/issueclaim.go @@ -128,6 +128,9 @@ func (c Claim) Live(now time.Time) bool { type Release struct { Identity string At time.Time + // Kind is the released holder's kind when the marker carries kind= + // (human, agent, contributor, external); "" on older markers. + Kind string } // ParseReleaseMarker reads a `<!-- hive:release who=<identity> ... -->` @@ -151,6 +154,8 @@ func ParseReleaseMarker(body string) (Release, bool) { switch key { case "who": rel.Identity = val + case "kind": + rel.Kind = val case "at": at, err := time.Parse(time.RFC3339, val) if err != nil { diff --git a/src/pkg/review/decision_question_class.go b/src/pkg/review/decision_question_class.go new file mode 100644 index 0000000000..3abfd5c968 --- /dev/null +++ b/src/pkg/review/decision_question_class.go @@ -0,0 +1,168 @@ +package review + +import ( + "path" + "regexp" + "strconv" + "strings" + + "github.com/hivecommons/hive/pkg/intent" +) + +// DecisionQuestionClass sorts one reviewer "decision needed" ask on a +// hive-authored PR into what it needs: a person's sign-off, or the hive's own +// delegated decision. hivecommons/docs#618 parked a green, finding-free, +// hive-authored PR at stage/085 because one perspective ended with a +// scope question ("should this merge ahead of that workflow edit?") that the +// risk-class denylist (DecisionRiskClasses) read as a sensitive-path ask — +// the owner's words: "this is auto-merge material, not needs-human". +type DecisionQuestionClass string + +const ( + // DecisionQuestionPolicySignOff: the ask stays a person's. The PR edits + // workflows from a fork, touches secrets / permissions / OWNERS / + // security-labelled paths, changes the auto-merge or human-merge + // policy, or the reviewer names an owner-only guard outright. + DecisionQuestionPolicySignOff DecisionQuestionClass = "policy-sign-off" + // DecisionQuestionScope: a scope or follow-up question ("should we + // also…", "merge ahead of…", "apply X from the PR body", "confirm Y is + // acceptable") on a hive-authored PR with CI green and no unresolved + // finding on its head. The hive answers it through the delegate path. + DecisionQuestionScope DecisionQuestionClass = "scope-question" + // DecisionQuestionIneligible: not a candidate for auto-decision at all + // (no question, not hive-authored, CI not green, findings open). The + // ordinary 085 park stands. + DecisionQuestionIneligible DecisionQuestionClass = "ineligible" +) + +// DecisionQuestionInput is what the classifier sees. It is a value, not a +// GitHub read: callers gather the head's files and status first. +type DecisionQuestionInput struct { + // Question is the reviewer's decision question, verbatim. + Question string + // HiveAuthored: the hive opened the PR, or adopted it in place. + HiveAuthored bool + // FromFork: the head lives in a fork of the base repository. + FromFork bool + // CIGreen: every gating check on the head passed. + CIGreen bool + // UnresolvedFindings: the head's review verdict carries a finding or a + // changes-requested perspective that no fix has cleared. + UnresolvedFindings bool + // Files are the head's changed files with their patches (patch may be + // empty when the caller did not fetch it). + Files []DecisionQuestionFile +} + +// DecisionQuestionFile is one changed file of the PR under question. +type DecisionQuestionFile struct { + Path string + Patch string +} + +// decisionPolicyPaths are the paths whose edit turns a reviewer question +// into a sign-off: trust and governance files, security policy, workflow +// and ruleset config, the hive's own policy files, and secrets-adjacent +// files. Deliberately narrower than sentinel.DefaultSensitivePaths, whose +// go.mod / Makefile / package.json entries guard supply chain, not policy. +var decisionPolicyPaths = []string{ + "OWNERS", "**/OWNERS", "OWNERS_ALIASES", "**/OWNERS_ALIASES", + "CODEOWNERS", "**/CODEOWNERS", "MAINTAINERS", "**/MAINTAINERS", + "GOVERNANCE.md", "SECURITY.md", "**/SECURITY.md", + ".github/rulesets/**", ".github/settings.yml", ".github/CODEOWNERS", + "policies/**", "**/policies/**", + "hive.yaml", "**/hive.yaml", "hive.yaml.dashboard", "**/hive.yaml.dashboard", + "**/.env*", "**/*.pem", "**/*.key", "**/id_rsa*", "**/secrets*", +} + +// decisionWorkflowPaths are the CI-automation paths a fork may not edit +// without a person's sign-off (the App cannot push them either). +var decisionWorkflowPaths = []string{".github/workflows/**", "**/.github/workflows/**", ".github/actions/**"} + +// decisionPolicyConfigKeys are hive config keys whose change in a patch is +// a merge-policy change, whatever file carries them. +var decisionPolicyConfigKeys = []string{"auto_merge", "human_merge_paths", "self_authored_decision_policy", "auto_decide_questions"} + +// decisionOwnerOnlyGuards are the asks a reviewer phrases as an explicit +// owner-only guard. Each is a whole-word match on the lower-cased question. +var decisionOwnerOnlyGuards = []*regexp.Regexp{ + regexp.MustCompile(`\bsentinel\b`), + regexp.MustCompile(`\bgithub permissions?\b`), + regexp.MustCompile(`\bapp permissions?\b`), + regexp.MustCompile(`\borg(?:anization)? (?:permissions?|admin|owner|membership)\b`), + regexp.MustCompile(`\bunauthori[sz]ed\b`), + regexp.MustCompile(`\bsecrets?\b`), + regexp.MustCompile(`\btokens?\b`), + regexp.MustCompile(`\bcredentials?\b`), + regexp.MustCompile(`\bbranch protection\b`), + regexp.MustCompile(`\bcodeowners\b`), + regexp.MustCompile(`\bowners file\b`), + regexp.MustCompile(`\bowner-only\b`), +} + +// ClassifyDecisionQuestion is the pure classifier behind the reviewer +// question auto-decide (governor.review.auto_decide_questions). The reason +// names the first rule that settled the class, for the INFO line and the +// audit record. Policy sign-off wins over scope: a question on a PR that +// edits OWNERS is the owner's however it is phrased. +func ClassifyDecisionQuestion(in DecisionQuestionInput) (DecisionQuestionClass, string) { + q := strings.ToLower(strings.TrimSpace(in.Question)) + if q == "" { + return DecisionQuestionIneligible, "no reviewer question" + } + for _, f := range in.Files { + p := strings.TrimSpace(f.Path) + if p == "" { + continue + } + if in.FromFork && intent.PathMatchesAny(p, decisionWorkflowPaths) { + return DecisionQuestionPolicySignOff, "fork PR edits workflow path " + p + } + if intent.PathMatchesAny(p, decisionPolicyPaths) { + return DecisionQuestionPolicySignOff, "PR touches policy path " + p + } + if key := decisionPatchPolicyKey(p, f.Patch); key != "" { + return DecisionQuestionPolicySignOff, "PR changes " + key + " in " + p + } + } + for _, guard := range decisionOwnerOnlyGuards { + if m := guard.FindString(q); m != "" { + return DecisionQuestionPolicySignOff, "ask names owner-only guard " + strconv.Quote(m) + } + } + switch { + case !in.HiveAuthored: + return DecisionQuestionIneligible, "PR is not hive-authored" + case !in.CIGreen: + return DecisionQuestionIneligible, "CI is not green on head" + case in.UnresolvedFindings: + return DecisionQuestionIneligible, "head has unresolved review findings" + } + return DecisionQuestionScope, "scope/follow-up question on a green hive-authored PR with no findings" +} + +// decisionPatchPolicyKey reports the merge-policy config key a patch adds +// or removes in a hive config file; "" when none. Only YAML-shaped files are +// read, so a Go test naming `auto_merge` in a string is not a policy edit. +func decisionPatchPolicyKey(p, patch string) string { + if patch == "" { + return "" + } + switch strings.ToLower(path.Ext(p)) { + case ".yaml", ".yml", ".dashboard": + default: + return "" + } + for _, line := range strings.Split(patch, "\n") { + if len(line) < 2 || (line[0] != '+' && line[0] != '-') || strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---") { + continue + } + body := strings.TrimSpace(line[1:]) + for _, key := range decisionPolicyConfigKeys { + if strings.HasPrefix(body, key+":") { + return key + } + } + } + return "" +} diff --git a/src/pkg/review/decision_question_class_test.go b/src/pkg/review/decision_question_class_test.go new file mode 100644 index 0000000000..aa88efd1da --- /dev/null +++ b/src/pkg/review/decision_question_class_test.go @@ -0,0 +1,134 @@ +package review + +import ( + "strings" + "testing" +) + +// The two asks that parked green, finding-free, hive-authored PRs for a +// person (hivecommons/docs#618 and hivecommons/hive#16456), verbatim. +const ( + docs618Ask = "@clubanderson should decide whether to apply the hive-docs-refresh.yml opt-in from the PR body (adding the \"hive-docs-refresh\" workflow_dispatch input) and whether this PR should merge ahead of that workflow edit." + hive16456Ask = "Decision needed: @clubanderson should confirm the merge-request relay may lift the hold…" +) + +func TestClassifyDecisionQuestion(t *testing.T) { + green := func(q string, files ...DecisionQuestionFile) DecisionQuestionInput { + return DecisionQuestionInput{Question: q, HiveAuthored: true, CIGreen: true, Files: files} + } + cases := []struct { + name string + in DecisionQuestionInput + want DecisionQuestionClass + reason string + }{ + { + name: "docs#618 scope question is the hive's", + in: green(docs618Ask, DecisionQuestionFile{Path: "docs/sync/README.md"}, DecisionQuestionFile{Path: "scripts/sync.sh"}), + want: DecisionQuestionScope, reason: "scope/follow-up", + }, + { + name: "hive#16456 confirm-the-relay question is the hive's", + in: green(hive16456Ask, DecisionQuestionFile{Path: "src/pkg/github/review_verdict_relay.go"}), + want: DecisionQuestionScope, reason: "scope/follow-up", + }, + { + name: "should-we-also follow-up", + in: green("Should we also update the operator reference to mention the new flag, or is a follow-up fine?"), + want: DecisionQuestionScope, + }, + { + name: "confirm acceptable wording", + in: green("@clubanderson should confirm the renamed caption is acceptable before this merges."), + want: DecisionQuestionScope, + }, + { + name: "fork PR editing a workflow is a sign-off", + in: DecisionQuestionInput{Question: "Should the new job run on pull_request_target?", HiveAuthored: true, CIGreen: true, FromFork: true, + Files: []DecisionQuestionFile{{Path: ".github/workflows/ci.yml"}}}, + want: DecisionQuestionPolicySignOff, reason: "fork PR edits workflow path", + }, + { + name: "same-repo hive PR editing a workflow is still the hive's", + in: green("Should this merge ahead of the docs refresh?", DecisionQuestionFile{Path: ".github/workflows/docs.yml"}), + want: DecisionQuestionScope, + }, + { + name: "OWNERS edit is a sign-off however it is phrased", + in: green("Should we also add the new reviewer to the docs alias?", DecisionQuestionFile{Path: "docs/OWNERS"}), + want: DecisionQuestionPolicySignOff, reason: "policy path docs/OWNERS", + }, + { + name: "SECURITY.md edit is a sign-off", + in: green("Confirm the new disclosure address is right.", DecisionQuestionFile{Path: "SECURITY.md"}), + want: DecisionQuestionPolicySignOff, reason: "policy path", + }, + { + name: "auto_merge config change in a patch is a sign-off", + in: green("Confirm the lane should merge its own PRs.", DecisionQuestionFile{Path: "deploy/overlays/prod/governor.yaml", + Patch: "@@ -1,3 +1,4 @@\n repos:\n hive:\n+ auto_merge: true\n"}), + want: DecisionQuestionPolicySignOff, reason: "changes auto_merge", + }, + { + name: "auto_merge named in a Go test is not a policy edit", + in: green("Should the test also cover the off case?", DecisionQuestionFile{Path: "src/pkg/config/config_test.go", + Patch: "+\tcfg.AutoMerge.Enabled = true // auto_merge: on\n"}), + want: DecisionQuestionScope, + }, + { + name: "explicit sentinel guard is a sign-off", + in: green("The sentinel flagged the install script; @clubanderson should acknowledge it before merge."), + want: DecisionQuestionPolicySignOff, reason: `owner-only guard "sentinel"`, + }, + { + name: "GitHub permissions guard is a sign-off", + in: green("Whether the App's GitHub permissions allow pushing this is the owner's call."), + want: DecisionQuestionPolicySignOff, reason: "github permissions", + }, + { + name: "secret token guard is a sign-off", + in: green("Confirm the new token scope is intended."), + want: DecisionQuestionPolicySignOff, reason: "token", + }, + { + name: "contributor PR is not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", CIGreen: true}, + want: DecisionQuestionIneligible, reason: "not hive-authored", + }, + { + name: "red CI is not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", HiveAuthored: true}, + want: DecisionQuestionIneligible, reason: "CI is not green", + }, + { + name: "open findings are not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", HiveAuthored: true, CIGreen: true, UnresolvedFindings: true}, + want: DecisionQuestionIneligible, reason: "unresolved review findings", + }, + { + name: "no question", + in: DecisionQuestionInput{HiveAuthored: true, CIGreen: true}, + want: DecisionQuestionIneligible, reason: "no reviewer question", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, reason := ClassifyDecisionQuestion(tc.in) + if got != tc.want { + t.Fatalf("class = %q (%s), want %q", got, reason, tc.want) + } + if tc.reason != "" && !strings.Contains(strings.ToLower(reason), strings.ToLower(tc.reason)) { + t.Fatalf("reason = %q, want it to mention %q", reason, tc.reason) + } + }) + } +} + +// The two real asks still land in a DecisionRiskClass by wording alone +// (that is why they parked); the classifier is what lets the hive answer +// them regardless. +func TestClassifyDecisionQuestionRealAsksMatchRiskClassByWording(t *testing.T) { + if _, risk := DecisionQuestionRiskClass(docs618Ask); !risk { + t.Fatalf("docs#618 ask no longer matches a risk class; the classifier is not what routes it") + } +} diff --git a/src/pkg/review/dispatch.go b/src/pkg/review/dispatch.go index 190286a69e..8e5f87218f 100644 --- a/src/pkg/review/dispatch.go +++ b/src/pkg/review/dispatch.go @@ -176,8 +176,12 @@ type DispatchOptions struct { CombinedPerspectives bool ReviewerAgents []string FixerAgent string - ProjectOrg string - AIAuthor string + FixerFallbackAgents []string + // FixerAvailable optionally filters repair candidates by runtime liveness. + // Nil preserves the existing capability-only selection. + FixerAvailable func(string) bool + ProjectOrg string + AIAuthor string // PostComments carries config.ReviewConfig.PostComments into the prompt // builder, so reviewers are told to publish their verdict on the PR. PostComments bool @@ -1618,7 +1622,14 @@ func (p *DispatchPlan) dispatchFix(pr PullRequest, agg Aggregate, opts DispatchO agent := selectFixerAgent(pr, opts) if agent == "" { p.recordFixExclusion(pr, FixDispatchExcludedNoEnabledFixer, attempts) - p.addHuman(pr, "no enabled kick-capable fixer agent is available", now) + // Temporary runtime backpressure must remain retryable rather than + // becoming a maintainer decision. Preserve the configuration hold only + // when no candidate is capable even without the liveness filter. + capabilityOnly := opts + capabilityOnly.FixerAvailable = nil + if selectFixerAgent(pr, capabilityOnly) == "" { + p.addHuman(pr, "no enabled kick-capable fixer agent is available", now) + } return } attempts++ @@ -1690,8 +1701,9 @@ func hasLabelFold(labels []string, want string) bool { func selectFixerAgent(pr PullRequest, opts DispatchOptions) string { candidates := []string{strings.TrimSpace(opts.FixerAgent), strings.TrimSpace(pr.Lane), DefaultFixerAgent} + candidates = append(candidates, opts.FixerFallbackAgents...) for _, candidate := range candidates { - if candidate == "" { + if candidate == "" || (opts.FixerAvailable != nil && !opts.FixerAvailable(candidate)) { continue } for _, a := range opts.Agents { diff --git a/src/pkg/review/no_findings.go b/src/pkg/review/no_findings.go index 5476a98162..5f952f1442 100644 --- a/src/pkg/review/no_findings.go +++ b/src/pkg/review/no_findings.go @@ -21,3 +21,40 @@ func NoFindingsAcknowledgement(body string) bool { body = strings.TrimSpace(body) return body != "" && noFindingsRe.MatchString(body) } + +// noFindingsPhraseRe matches the free-text way a reviewer says it found +// nothing ("No findings.", "no findings from this perspective", "I have no +// findings") anywhere in a body. +var noFindingsPhraseRe = regexp.MustCompile(`(?i)\bno\s+(?:further\s+|other\s+|additional\s+)?findings\b`) + +// CleanReview reports whether a review body submitted with reports is a +// clean review in substance, not only in form: either the one-line +// acknowledgement, or a body that says it has no findings while every +// report it rides with approves (or is not applicable) with an empty +// findings list and asks for no decision. The plain reviewer lanes narrate +// their reading ("Read the tree at abc1234 … Looks correct to me. No +// findings.") and so escaped NoFindingsAcknowledgement, costing a review +// email per clean lane per head (hivecommons/hive#16433). A body carrying a +// hidden hive marker (a decision question, a redundant-of pointer) is never +// clean: something downstream reads it. +func CleanReview(body string, reports []PerspectiveReport) bool { + body = strings.TrimSpace(body) + if body == "" { + return false + } + if noFindingsRe.MatchString(body) { + return true + } + if len(reports) == 0 || strings.Contains(body, "<!--") || !noFindingsPhraseRe.MatchString(body) { + return false + } + for _, r := range reports { + if r.DecisionRequested || len(r.Findings) > 0 { + return false + } + if !r.NotApplicable && r.Verdict != VerdictApprove { + return false + } + } + return true +} diff --git a/src/pkg/review/no_findings_test.go b/src/pkg/review/no_findings_test.go index 630bac0462..6eb949e39c 100644 --- a/src/pkg/review/no_findings_test.go +++ b/src/pkg/review/no_findings_test.go @@ -1,6 +1,10 @@ package review -import "testing" +import ( + "testing" + + "github.com/hivecommons/hive/pkg/outputschema" +) func TestNoFindingsAcknowledgement(t *testing.T) { yes := []string{ @@ -27,3 +31,31 @@ func TestNoFindingsAcknowledgement(t *testing.T) { } } } + +func TestCleanReview(t *testing.T) { + approve := []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictApprove}} + narrated := "Read the tree at `c7c8dfb`: the retry loop bounds its attempts and the error is wrapped. Looks correct to me.\n\nNo findings." + cases := []struct { + name string + body string + reports []PerspectiveReport + want bool + }{ + {"one-line ack without reports", "**Reviewed** — no findings from this perspective.", nil, true}, + {"narrated clean reviewer-lane body", narrated, approve, true}, + {"no further findings", "Re-read after the fixup; no further findings from me.", approve, true}, + {"not-applicable perspective", "Nothing to review for style here — no findings.", []PerspectiveReport{{Perspective: PerspectiveStyle, Verdict: VerdictApprove, NotApplicable: true}}, true}, + {"narration without the phrase", "Read the tree at `c7c8dfb`. Looks correct to me.", approve, false}, + {"says no findings but report has one", narrated, []PerspectiveReport{{AgentReport: outputschema.AgentReport{Findings: []outputschema.Finding{{Title: "nil deref"}}}, Perspective: PerspectiveCorrectness, Verdict: VerdictApprove}}, false}, + {"says no findings but requests changes", narrated, []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictChangesRequested}}, false}, + {"decision requested", "No findings, but a maintainer should decide the API shape.", []PerspectiveReport{{Perspective: PerspectiveCorrectness, Verdict: VerdictApprove, DecisionRequested: true}}, false}, + {"hidden marker", "<!-- hive-decision-question: keep the flag? -->\nNo findings otherwise.", approve, false}, + {"narrated body without reports", narrated, nil, false}, + {"empty", "", approve, false}, + } + for _, tc := range cases { + if got := CleanReview(tc.body, tc.reports); got != tc.want { + t.Errorf("%s: CleanReview = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/src/pkg/scheduler/kick_reauthor_test.go b/src/pkg/scheduler/kick_reauthor_test.go new file mode 100644 index 0000000000..dddf0f69ed --- /dev/null +++ b/src/pkg/scheduler/kick_reauthor_test.go @@ -0,0 +1,27 @@ +package scheduler + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// An issue the hive re-authored (its earlier PR closed as superseded after +// the fixer gave up) tells the kick to open a fresh PR declaring the +// supersession; an ordinary issue gets no such line. +func TestFormatIssueList_ReauthoredIssueHint(t *testing.T) { + s := newSchedulerWithIoscan(false) + issues := []github.Issue{ + {Repo: "test-org/console", Number: 7, Title: "fix the widget", AgeMinutes: 1, Labels: []string{"bug", stagelabels.LabelReauthored}}, + {Repo: "test-org/console", Number: 8, Title: "tidy the gadget", AgeMinutes: 1, Labels: []string{"bug"}}, + } + out, _ := s.formatIssueListWithPolicy(issues) + if strings.Count(out, "↳ re-authoring:") != 1 || !strings.Contains(out, "Supersedes #<old PR>") { + t.Fatalf("re-author hint missing or repeated:\n%s", out) + } + if idx := strings.Index(out, "↳ re-authoring:"); idx < strings.Index(out, "#7") || idx > strings.Index(out, "#8") { + t.Fatalf("hint not under issue #7:\n%s", out) + } +} diff --git a/src/pkg/scheduler/kickmessage.go b/src/pkg/scheduler/kickmessage.go index cdf609de65..5c00852840 100644 --- a/src/pkg/scheduler/kickmessage.go +++ b/src/pkg/scheduler/kickmessage.go @@ -11,6 +11,7 @@ import ( "github.com/hivecommons/hive/pkg/decisionpolicy" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/promptsrc" + "github.com/hivecommons/hive/pkg/stagelabels" "github.com/hivecommons/hive/pkg/upstreamwatch" ) @@ -167,6 +168,11 @@ func (s *Scheduler) formatIssueListWithPolicyForAgent(issues []github.Issue, ref if s.isUpstreamPortIssue(issue) { b.WriteString(fmt.Sprintf(" ↳ if you merge the upstream branch into this fork instead, title the PR `chore: sync upstream <range>` and label it `%s` so hive lands it as a merge commit, not a squash\n", github.UpstreamSyncLabel)) } + if hasIssueLabel(issue.Labels, stagelabels.LabelReauthored) { + // The hive closed its own earlier PR for this issue after its + // fixer gave up; the fresh PR is this kick's to open. + b.WriteString(" ↳ re-authoring: the hive's earlier PR for this issue was closed as superseded after its fixer gave up; open a FRESH PR from the current base (do not reuse the old branch) and write `Supersedes #<old PR>` in the body\n") + } if issue.ClaimContext != nil && issue.ClaimContext.Decision == github.ClaimDecisionReopenedAfterMerge { prRef := fmt.Sprintf("%s#%d", issue.ClaimContext.PRRepo, issue.ClaimContext.PRNumber) b.WriteString(fmt.Sprintf(" ↳ reopened after %s merged", prRef)) diff --git a/src/pkg/stageengine/derive_issue.go b/src/pkg/stageengine/derive_issue.go index 9d01bd63ca..dd83ef878a 100644 --- a/src/pkg/stageengine/derive_issue.go +++ b/src/pkg/stageengine/derive_issue.go @@ -26,6 +26,10 @@ const ( // reasonIssueOpenPRPartial is 040 under a PR that references the issue // without closing it (ClaimFact.Partial); ReasonIsPartialCover reads it. reasonIssueOpenPRPartial = "open PR addresses part of it (references it without a closing keyword)" + // reasonIssueDecidedHumanWork prefixes the reason of an issue whose + // direction a person already gave and whose remainder is held for a + // person (hivecommons/hive#16579). + reasonIssueDecidedHumanWork = "decided; remaining work held for a person: " ) // ReasonIsPartialCover reports whether a 040 reason describes a PR that @@ -35,6 +39,28 @@ func ReasonIsPartialCover(reason string) bool { return strings.HasPrefix(strings.TrimSpace(reason), "open PR addresses part of it") } +const reasonOpenChildrenPrefix = "waiting on " + +// ReasonOpenChildren reads the "; waiting on N open child issue(s)" suffix +// deriveIssue appends to a decomposed parent's reason and returns N, or 0 +// when the reason carries no such suffix. Presentation layers use it to say +// the parent is tracking its children rather than waiting on the scanner. +func ReasonOpenChildren(reason string) int { + for _, part := range strings.Split(reason, ";") { + part = strings.TrimSpace(part) + if !strings.HasPrefix(part, reasonOpenChildrenPrefix) || !strings.HasSuffix(part, " open child issue(s)") { + continue + } + digits := strings.TrimSuffix(strings.TrimPrefix(part, reasonOpenChildrenPrefix), " open child issue(s)") + n, err := strconv.Atoi(digits) + if err != nil || n <= 0 { + return 0 + } + return n + } + return 0 +} + // deriveIssue maps issue Facts to a Decision. Pure: same Facts → same // Decision. An issue never goes past 040-covered-by-pr: 050+ are PR stages // (stagelabels.Table, PR: true) and mirroring them onto the issue is what @@ -72,13 +98,14 @@ func deriveIssue(f Facts) Decision { } } -// issueParkClear reconciles `needs-human` against `approved-direction`, -// which cannot both stand (hivecommons/hive#15099). The un-park that -// applies the ack removes `needs-human` in the same write, so a -// `needs-human` found next to the ack was applied after it — the later -// signal (DecisionLiftsNeedsHuman's own rule), whether an agent parked the -// issue on a blocker or a person asked again. The ack is the stale one: -// the issue stays 045 and the writer clears `approved-direction`. +// issueParkClear reconciles `needs-human` against `approved-direction` on +// an issue parked at 045 (hivecommons/hive#15099). That happens for a +// structured blocker — no decision grants the App a permission — and for a +// park let through because a newer, different `/hive decision` is pending +// (Park.DecisionSuperseded): either way the ack is the stale one and the +// writer clears it. A plain `needs-human` next to a standing ack derives +// out of the pipeline instead and keeps it (hivecommons/hive#16579), so +// nothing is cleared for it. func issueParkClear(f Facts, stage stagelabels.Stage) []string { is := f.Issue label := strings.TrimSpace(is.ApprovedDirectionLabel) @@ -139,6 +166,23 @@ func issueStage(f Facts) (stage stagelabels.Stage, covered bool, reason string) } return stagelabels.IssueNeedsDecision, false, "blocked: " + short } + // A decision is already recorded (`approved-direction`): a + // `needs-human` next to it is the agent standing down on work only + // a person can do (a cluster rollout, a backup, an out-of-repo + // step) — what the re-park refusal tells agents to do — not a new + // question. Re-deriving 045 stripped the ack and re-opened the + // decision inbox on every scanner pass, and the un-park sweep + // re-applied the same old decision: a bounce loop + // (hivecommons/hive#16579, seen on hivecommons/dibs#567). The + // issue is held out of the pipeline like a hold and keeps the ack; + // a person who wants to decide again removes `approved-direction` + // — or posts a new `/hive decision`: the label relay lets an + // agent's park through on that newer, different decision + // (Park.DecisionSuperseded), the ack is stale again, and the issue + // re-parks at 045 with it cleared until the un-park sweep answers. + if strings.TrimSpace(is.ApprovedDirectionLabel) != "" && !f.Park.DecisionSuperseded { + return stagelabels.None, false, reasonIssueDecidedHumanWork + is.NeedsHumanLabel + } return stagelabels.IssueNeedsDecision, false, "held for a person: " + is.NeedsHumanLabel } // The prior-art gate's park is its own stage, 017, not 045: nothing is diff --git a/src/pkg/stageengine/derive_issue_test.go b/src/pkg/stageengine/derive_issue_test.go index ca41d03da3..cbe1245dc2 100644 --- a/src/pkg/stageengine/derive_issue_test.go +++ b/src/pkg/stageengine/derive_issue_test.go @@ -134,9 +134,10 @@ func TestDeriveIssueFlags(t *testing.T) { } // hivecommons/hive#15099: `needs-human` with a structured blocker stays -// 045 and names the blocker. `approved-direction` next to `needs-human` -// is the stale label either way (the un-park that applies the ack removes -// the park label, so a surviving park label came later) and is cleared. +// 045 and names the blocker, and `approved-direction` next to it is the +// stale label and is cleared. A plain `needs-human` next to the ack is the +// agent standing down on human-only work after a decision and stays out of +// 045 with the ack kept (hivecommons/hive#16579). func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { blocked := func(f *Facts) { f.Issue.Bucket = BucketFiltered @@ -160,8 +161,20 @@ func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { f.Park.NeedsHuman = true f.Issue.ApprovedDirectionLabel = "approved-direction" })) + if d.Stage != stagelabels.None || d.Reason != "decided; remaining work held for a person: needs-human" || len(d.Clear) != 0 { + t.Fatalf("a plain needs-human after a decision keeps the ack out of 045 (#16579): %+v", d) + } + // A newer, different `/hive decision` is pending (the label relay let + // an agent's park through on it): the ack is stale again, the issue + // re-parks at 045 and the writer clears it. + d = DeriveIssue(derivedIssueFacts(func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Park.DecisionSuperseded = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + })) if d.Stage != stagelabels.IssueNeedsDecision || d.Reason != "held for a person: needs-human" || len(d.Clear) != 1 || d.Clear[0] != "approved-direction" { - t.Fatalf("a later needs-human outranks the ack: %+v", d) + t.Fatalf("a park on a newer decision outranks the stale ack: %+v", d) } d = DeriveIssue(derivedIssueFacts(func(f *Facts) { blocked(f); f.Issue.BlockerShort = "" })) if d.Reason != "blocked: capability:workflows-permission" { @@ -177,3 +190,51 @@ func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { t.Fatalf("held: %+v", d) } } + +// hivecommons/hive#16579 (seen on hivecommons/dibs#567): parked → +// `/hive decision` → `approved-direction` + 010 → a later scanner pass +// finds the remaining checklist human-only and adds `needs-human`. That +// evaluation must neither re-derive 045 nor strip the ack — doing so put +// the decision back in the inbox and the un-park sweep re-applied the same +// decision, bouncing the issue every pass. +func TestDeriveIssueDecisionSticksOverHumanOnlyRemainder(t *testing.T) { + steps := []struct { + name string + mutate func(f *Facts) + wantStage stagelabels.Stage + }{ + {"agent parks", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + }, stagelabels.IssueNeedsDecision}, + {"maintainer decides", func(f *Facts) { + f.Park.ApprovedDirection = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + }, stagelabels.Actionable}, + {"remainder is human-only", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + }, stagelabels.None}, + {"next pass re-evaluates", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + f.Issue.Stalled = true + }, stagelabels.None}, + } + for _, tc := range steps { + d := DeriveIssue(derivedIssueFacts(tc.mutate)) + if d.Stage != tc.wantStage { + t.Fatalf("%s: stage = %v, want %v (%+v)", tc.name, d.Stage, tc.wantStage, d) + } + for _, c := range d.Clear { + if c == "approved-direction" { + t.Fatalf("%s: stripped approved-direction: %+v", tc.name, d) + } + } + if d.Terminal { + t.Fatalf("%s: an open decided issue is not terminal: %+v", tc.name, d) + } + } +} diff --git a/src/pkg/stageengine/derive_pr.go b/src/pkg/stageengine/derive_pr.go index c45956d78e..a4278a6b7d 100644 --- a/src/pkg/stageengine/derive_pr.go +++ b/src/pkg/stageengine/derive_pr.go @@ -316,7 +316,10 @@ func passDecision(verdict stageVerdict, role stagelabels.Role, obs stageObservat verdict.Rank = stageRankOwned obs.Reason = stagelabels.LaneReasonRebaseFailedTwice } - if !verdict.Terminal && pass.FixerExhausted > 0 && verdict.Stage == FixingStage(obs) { + if !verdict.Terminal && pass.Reauthoring > 0 && verdict.Stage == FixingStage(obs) { + obs.Reason = stagelabels.ReauthoringReason(pass.Reauthoring) + } + if !verdict.Terminal && pass.FixerExhausted > 0 && pass.Reauthoring == 0 && verdict.Stage == FixingStage(obs) { verdict.Stage = stagelabels.NeedsDecision verdict.Rank = stageRankOwned obs.Reason = stagelabels.FixerExhaustedReason(pass.FixerExhausted) diff --git a/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go b/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go index 7f6f4ea383..f9a0981e4c 100644 --- a/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go +++ b/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go @@ -66,3 +66,15 @@ func TestPreserveStageOnStaleDecisionAnswer(t *testing.T) { t.Fatal("a PR not previously at 085 has nothing to preserve") } } + +// The hive re-authors its own exhausted PR instead of asking a person: +// the PR stays on its fixing stage, the reason names the issue a fresh +// PR is being opened for, and the exhausted count does not park it. +func TestDerivePRReauthoringStaysOnFixing(t *testing.T) { + f := hiveFixingFacts(contributorLaneReasonChangesRequested) + f.PR.Pass = &PRPassFacts{AuthorIsApp: true, FixerExhausted: 6, FixerExcluded: true, Reauthoring: 16265} + d := DerivePR(f) + if d.Stage != stagelabels.Fixing || d.Reason != stagelabels.ReauthoringReason(16265) { + t.Fatalf("re-authoring: stage = %s reason = %q, want 070 re-authoring:16265", d.Stage, d.Reason) + } +} diff --git a/src/pkg/stageengine/facts.go b/src/pkg/stageengine/facts.go index 304991125a..8aac290aea 100644 --- a/src/pkg/stageengine/facts.go +++ b/src/pkg/stageengine/facts.go @@ -83,6 +83,13 @@ type ParkFacts struct { HumanOnlyReason string // lane rule unrelated to trust (workflow edits, tests removed, …) ApprovedDirection bool // /hive approve|decision recorded; un-park keeps needs-human (#12715) DecisionQuestion string + // DecisionSuperseded says a newer `/hive decision` with different text + // is on the timeline after the recorded one: direction is changing, so + // the `approved-direction` the issue still wears is stale and a + // `needs-human` park re-derives 045 with the ack cleared instead of + // standing down on it (FactSink.ReparkedOnNewDecision; + // hivecommons/hive#16579). + DecisionSuperseded bool } // AdoptionFacts is the stage-074 ownership state of a contributor PR. @@ -162,9 +169,13 @@ type IssueFacts struct { BlockerShort string // ApprovedDirectionLabel is the `approved-direction` label the issue // wears (a recorded /hive approve|decision), "" when absent. Next to - // `needs-human` it is the stale one — the un-park that applied it - // removed the park label, so a surviving `needs-human` came later — - // and the writer clears it (hivecommons/hive#15099). + // `needs-human` and a structured Blocker it is the stale one and the + // writer clears it (hivecommons/hive#15099); next to a plain + // `needs-human` the decision stands and the remainder is held for a + // person out of the pipeline, not re-parked at 045 + // (hivecommons/hive#16579) — unless Park.DecisionSuperseded says a + // newer, different decision is pending, when the ack is stale again + // and the park re-derives 045 with it cleared. ApprovedDirectionLabel string // UmbrellaLabel is the never-claim label the issue carries // (governor.claims.never_claim_labels, default `epic`). @@ -296,6 +307,13 @@ type PRPassFacts struct { // stagelabels.FixerExhaustedReason(n) so a person decides instead of // the row claiming "Fixing" with nobody on it (hivecommons/hive#15744). FixerExhausted int + // Reauthoring is the issue the hive is re-authoring this PR for after + // its fixer gave up: the PR is closed as superseded and a fresh hive + // PR opens for that issue from the current base, so the PR stays on + // its fixing stage with stagelabels.ReauthoringReason(issue) rather + // than parking at 085 (a hive agent's PR needs no re-author pill). + // Zero when no re-author is under way. + Reauthoring int // RecoveryUnauthorized is an observed exact-head CI recovery permission // refusal. It parks the item without treating infrastructure as source work. RecoveryUnauthorized string diff --git a/src/pkg/stageengine/facts_sink.go b/src/pkg/stageengine/facts_sink.go index 3afda9102a..96edcccd89 100644 --- a/src/pkg/stageengine/facts_sink.go +++ b/src/pkg/stageengine/facts_sink.go @@ -25,8 +25,15 @@ type FactSink interface { AddressedBy(ctx context.Context, issue Ref, pr Ref) error Uncovered(ctx context.Context, issue Ref, pr Ref) error Parked(ctx context.Context, ref Ref, label string) error // agent escalation (045/085/needs-human) - Unparked(ctx context.Context, ref Ref, by string) error // /hive approve|decision - Closed(ctx context.Context, ref Ref) error // the issue closed; its stage lifts + // ReparkedOnNewDecision is Parked for an issue that already wears + // `approved-direction` when a newer, different `/hive decision` is + // pending on its timeline (the label relay's recorded-decision refusal + // let the park through): direction is changing, so the ack is stale + // and the park derives 045 with it cleared rather than standing down + // on the old decision (hivecommons/hive#16579). + ReparkedOnNewDecision(ctx context.Context, ref Ref, label string) error + Unparked(ctx context.Context, ref Ref, by string) error // /hive approve|decision + Closed(ctx context.Context, ref Ref) error // the issue closed; its stage lifts // PRDecided is a trusted merger's `/hive decision` answered on a PR // parked at 085: the decision is recorded for Head, so the park lifts // now — in the same breath as the reply — instead of waiting for the @@ -192,19 +199,31 @@ func (s *factSink) Uncovered(ctx context.Context, issue Ref, pr Ref) error { // Parked implements FactSink: an agent (or a person) parked the item on a // human with label → 045 on an issue, 085 on a PR. func (s *factSink) Parked(ctx context.Context, ref Ref, label string) error { + return s.submit(ctx, parkedFacts(ref, label, false)) +} + +// ReparkedOnNewDecision implements FactSink: Parked with +// ParkFacts.DecisionSuperseded set, so a `needs-human` next to a stale +// `approved-direction` re-derives 045 and clears the ack. +func (s *factSink) ReparkedOnNewDecision(ctx context.Context, ref Ref, label string) error { + return s.submit(ctx, parkedFacts(ref, label, true)) +} + +func parkedFacts(ref Ref, label string, superseded bool) Facts { label = strings.TrimSpace(label) f := Facts{Ref: ref, Labels: []string{label}} f.Park = ParkFacts{ - Holds: stagelabels.Holds(f.Labels), - NeedsHuman: strings.EqualFold(label, NeedsHumanLabel), - DecisionLabel: label, + Holds: stagelabels.Holds(f.Labels), + NeedsHuman: strings.EqualFold(label, NeedsHumanLabel), + DecisionLabel: label, + DecisionSuperseded: superseded, } if ref.Kind == stagelabels.PRItem { f.PR = &PRFacts{} } else { f.Issue = &IssueFacts{Bucket: BucketFiltered, FilteredReason: label} } - return s.submit(ctx, f) + return f } // Unparked implements FactSink: /hive approve or /hive decision recorded by diff --git a/src/pkg/stageengine/facts_sink_test.go b/src/pkg/stageengine/facts_sink_test.go index daa6d53683..a3e7542035 100644 --- a/src/pkg/stageengine/facts_sink_test.go +++ b/src/pkg/stageengine/facts_sink_test.go @@ -73,7 +73,12 @@ func TestFactSinkBuildsMinimalFacts(t *testing.T) { } }}, {"parked issue", func() error { return sink.Parked(ctx, issue, " needs-human ") }, func(t *testing.T, f Facts) { - if !f.Park.NeedsHuman || f.Park.DecisionLabel != "needs-human" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "needs-human" || len(f.Labels) != 1 { + if !f.Park.NeedsHuman || f.Park.DecisionSuperseded || f.Park.DecisionLabel != "needs-human" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "needs-human" || len(f.Labels) != 1 { + t.Fatalf("%+v %+v", f.Park, f.Issue) + } + }}, + {"reparked on new decision", func() error { return sink.ReparkedOnNewDecision(ctx, issue, "stage/045-needs-decision") }, func(t *testing.T, f Facts) { + if !f.Park.DecisionSuperseded || f.Park.DecisionLabel != "stage/045-needs-decision" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "stage/045-needs-decision" { t.Fatalf("%+v %+v", f.Park, f.Issue) } }}, diff --git a/src/pkg/stageengine/stageenginetest/fake.go b/src/pkg/stageengine/stageenginetest/fake.go index 819a17a0e3..05430866f5 100644 --- a/src/pkg/stageengine/stageenginetest/fake.go +++ b/src/pkg/stageengine/stageenginetest/fake.go @@ -170,7 +170,7 @@ type Recorder struct { // Recorded is one FactSink call. type Recorded struct { - Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | Unparked | Closed | PRDecided + Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | ReparkedOnNewDecision | Unparked | Closed | PRDecided Ref stageengine.Ref Claim *stageengine.ClaimFact PR *stageengine.Ref @@ -216,6 +216,9 @@ func (r *Recorder) Uncovered(_ context.Context, issue, pr stageengine.Ref) error func (r *Recorder) Parked(_ context.Context, ref stageengine.Ref, label string) error { return r.record(Recorded{Method: "Parked", Ref: ref, Label: label}) } +func (r *Recorder) ReparkedOnNewDecision(_ context.Context, ref stageengine.Ref, label string) error { + return r.record(Recorded{Method: "ReparkedOnNewDecision", Ref: ref, Label: label}) +} func (r *Recorder) Unparked(_ context.Context, ref stageengine.Ref, by string) error { return r.record(Recorded{Method: "Unparked", Ref: ref, Who: by}) } diff --git a/src/pkg/stagelabels/fixer_exhausted_test.go b/src/pkg/stagelabels/fixer_exhausted_test.go index 9e2aa20381..d4bb431ae7 100644 --- a/src/pkg/stagelabels/fixer_exhausted_test.go +++ b/src/pkg/stagelabels/fixer_exhausted_test.go @@ -26,19 +26,29 @@ func TestFixerExhaustedReasonRoundTrip(t *testing.T) { func TestFixerExhaustedRouteAndComment(t *testing.T) { head := "5b62304abcdef0123456789" - r := FixerExhaustedRoute(head, 6, " tests fail on arm64 ") + r := FixerExhaustedRoute(head, 6, " tests fail on arm64 ", 0) if r.Stage != NeedsDecision || !r.SelfAuthored || r.Head != head || r.ActionsHeading != "Your options:" { t.Fatalf("route = %+v", r) } if len(r.Reasons) != 2 || !strings.Contains(r.Reasons[0], "gave up after 6 attempts on `"+ShortSHA(head)+"`") || r.Reasons[1] != "last reviewer finding: tests fail on arm64" { t.Fatalf("reasons = %q", r.Reasons) } - if len(r.Actions) != 3 || !strings.HasPrefix(r.Actions[0], "**Re-author from scratch**") || !strings.HasPrefix(r.Actions[1], "**Hand it to a person**") || !strings.HasPrefix(r.Actions[2], "**Close as not planned**") { + if len(r.Actions) != 3 || !strings.HasPrefix(r.Actions[0], "**Give direction**") || !strings.HasPrefix(r.Actions[1], "**Hand it to a person**") || !strings.HasPrefix(r.Actions[2], "**Close as not planned**") { t.Fatalf("actions = %q", r.Actions) } + for _, a := range r.Actions { + if strings.Contains(strings.ToLower(a), "re-author") { + t.Fatalf("re-authoring offered as a human choice on a hive PR: %q", a) + } + } + // Second exhaustion on the hive's own re-author: the route says so. + again := FixerExhaustedRoute(head, 6, "", 16456) + if len(again.Reasons) != 2 || !strings.Contains(again.Reasons[1], "re-author of #16456") { + t.Fatalf("re-authored reasons = %q", again.Reasons) + } c := DecisionComment(r) - for _, want := range []string{DecisionCommentMarker, "Needs a decision, not a merge:\n- the hive's fixer gave up", "- last reviewer finding: tests fail on arm64", "**Your options:**", "`adoption/supersede`", "/hive decision"} { + for _, want := range []string{DecisionCommentMarker, "Needs a decision, not a merge:\n- the hive's fixer gave up", "- last reviewer finding: tests fail on arm64", "**Your options:**", "/hive decision"} { if !strings.Contains(c, want) { t.Fatalf("comment missing %q:\n%s", want, c) } @@ -48,7 +58,7 @@ func TestFixerExhaustedRouteAndComment(t *testing.T) { } // No summary: a single reason, rendered inline. - one := FixerExhaustedRoute(head, 3, "") + one := FixerExhaustedRoute(head, 3, "", 0) if len(one.Reasons) != 1 { t.Fatalf("reasons = %q", one.Reasons) } @@ -56,3 +66,17 @@ func TestFixerExhaustedRouteAndComment(t *testing.T) { t.Fatalf("single-reason comment:\n%s", c) } } + +func TestReauthoringReason(t *testing.T) { + if got := ReauthoringReason(16265); got != "re-authoring:16265" { + t.Fatalf("ReauthoringReason = %q", got) + } + if n, ok := ParseReauthoring("re-authoring:16265"); !ok || n != 16265 { + t.Fatalf("ParseReauthoring = %d %v", n, ok) + } + for _, bad := range []string{"", "re-authoring:", "re-authoring:0", "re-authoring:x", "fixer-exhausted:6"} { + if n, ok := ParseReauthoring(bad); ok || n != 0 { + t.Fatalf("ParseReauthoring(%q) = %d %v, want 0 false", bad, n, ok) + } + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 1209b6247f..675390fc8e 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -358,8 +358,39 @@ const ( // attempt count (hivecommons/hive#15744). Before this the PR sat at 070 // reading "Fixing" with nobody on it (#15308, 13h). LaneReasonFixerExhaustedPrefix = "fixer-exhausted:" + // LaneReasonReauthoringPrefix opens the 070 reason for a hive-authored + // PR whose fixer gave up and which the hive is re-authoring itself + // ("re-authoring:16265"): the suffix is the issue a fresh PR is being + // opened for; this PR is closed as superseded. The hive re-authors + // once per issue; a second exhaustion parks at 085 without the option. + LaneReasonReauthoringPrefix = "re-authoring:" + // LabelReauthored is the durable once-per-issue marker the automatic + // re-author leaves on the ISSUE: a later hive PR for the same issue + // whose fixer is exhausted again is parked for a person instead of + // being re-authored a second time. + LabelReauthored = "hive/re-authored" ) +// ReauthoringReason renders the 070 reason for a hive PR being re-authored +// for issue. +func ReauthoringReason(issue int) string { + return LaneReasonReauthoringPrefix + strconv.Itoa(issue) +} + +// ParseReauthoring reads the issue number out of a re-authoring reason; +// ok is false for any other reason. +func ParseReauthoring(reason string) (issue int, ok bool) { + reason = strings.TrimSpace(reason) + if !strings.HasPrefix(reason, LaneReasonReauthoringPrefix) { + return 0, false + } + n, err := strconv.Atoi(strings.TrimPrefix(reason, LaneReasonReauthoringPrefix)) + if err != nil || n <= 0 { + return 0, false + } + return n, true +} + // FixerExhaustedReason renders the 085 reason for a PR whose fixer gave up // after attempts tries. func FixerExhaustedReason(attempts int) string { @@ -668,6 +699,26 @@ const ( DecisionCommentMarker = "<!-- hive:stage-needs-decision -->" ) +// EntryCommentMarker is the marker the entry comment for stage carries, or +// "" for a stage with no entry comment. +func EntryCommentMarker(stage Stage) string { + switch stage { + case ReadyForHumanMerge: + return ReadyCommentMarker + case NeedsDecision: + return DecisionCommentMarker + } + return "" +} + +// EntryCommentUpdated is body — a fresh ReadyComment or DecisionComment — +// as it is written over the PR's existing entry comment: the same text with +// one line saying when it was last rewritten, so a reader who saw the +// earlier wording knows it changed (hivecommons/hive#16433). +func EntryCommentUpdated(body string, at time.Time) string { + return strings.TrimRight(body, "\n") + "\n\n<sub>Updated " + at.UTC().Format("2006-01-02 15:04 UTC") + ".</sub>" +} + // ReadyComment renders the 090 entry comment: // // Ready for a human merge: verdict approved @abc1234, 55/55 checks green, @@ -758,14 +809,20 @@ func DecisionComment(r Route) string { // FixerExhaustedRoute is the 085 route for a hive-authored PR whose fix // dispatcher refused another fix because the re-engagement cap is spent // (hivecommons/hive#15744). summary is the reviewer's one-line finding the -// fixer never cleared ("" when unknown). The comment lists the three -// answers the tracker offers: re-author from scratch (the lead action), -// hand it to a person, or close it as not planned. -func FixerExhaustedRoute(head string, attempts int, summary string) Route { +// fixer never cleared ("" when unknown). The hive re-authors its own PR +// automatically on the first exhaustion (ReauthoringReason), so this +// route is reached only when it cannot (no issue, or the issue was +// already re-authored once: reauthoredFrom names that earlier PR) and +// lists the answers left: give direction, hand it to a person, or close +// it as not planned. Re-authoring is never offered as a human choice. +func FixerExhaustedRoute(head string, attempts int, summary string, reauthoredFrom int) Route { reasons := []string{"the hive's fixer gave up after " + strconv.Itoa(attempts) + " attempts on `" + ShortSHA(head) + "`; no fix job is running"} if summary = strings.TrimSpace(summary); summary != "" { reasons = append(reasons, "last reviewer finding: "+summary) } + if reauthoredFrom > 0 { + reasons = append(reasons, "this PR is already the hive's re-author of #"+strconv.Itoa(reauthoredFrom)+"; the hive re-authors an issue once and does not try a third time on its own") + } return Route{ Stage: NeedsDecision, Reasons: reasons, @@ -773,8 +830,8 @@ func FixerExhaustedRoute(head string, attempts int, summary string) Route { SelfAuthored: true, ActionsHeading: "Your options:", Actions: []string{ - "**Re-author from scratch** — *Re-author* in the tracker (or add the `adoption/supersede` label): the hive opens a fresh PR for the same issue from the current base and closes this one as superseded.", - "**Hand it to a person** — reply `/hive decision <who or what to change>` or push to the branch yourself; the hive steps back while a human owns it.", + "**Give direction** — reply `/hive decision <what to change>` (or *Give direction* in the tracker); the hive's fixer gets one more run with your note.", + "**Hand it to a person** — push to the branch yourself or say who takes it; the hive steps back while a human owns it.", "**Close as not planned** — close the PR (or *Close as not planned* under Decide… in the tracker) when the change is no longer wanted.", }, } diff --git a/src/pkg/stagelabels/reauthor_store_test.go b/src/pkg/stagelabels/reauthor_store_test.go new file mode 100644 index 0000000000..fbbc4ac38c --- /dev/null +++ b/src/pkg/stagelabels/reauthor_store_test.go @@ -0,0 +1,74 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// The hive's one-per-issue re-author record (hivecommons/hive#16582): +// marked on the superseded PR's record, idempotent per head, found again +// by issue across the repo, absent for other repos, and persisted. +func TestStoreReauthored(t *testing.T) { + now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + clock := func() time.Time { return now } + st := NewStore(filepath.Join(t.TempDir(), "s.json"), clock) + key := Key("hivecommons/hive", 90) + + // Unknown key, bad issue: no-op; nothing re-authored for the issue. + st.MarkReauthored(key, 12, "aaa", 6, now) + st.MarkReauthorNoted(key) + if _, ok := st.Get(key); ok { + t.Fatal("Mark* must not create a record") + } + if st.ReauthoredFor("hivecommons/hive", 12) != 0 || (*Store)(nil).ReauthoredFor("hivecommons/hive", 12) != 0 { + t.Fatal("nothing re-authored yet") + } + + st.Observe(key, Fixing, ReauthoringReason(12)) + st.MarkReauthored(key, 0, "aaa", 6, now) + if r, _ := st.Get(key); r.Reauthored() { + t.Fatal("issue 0 must not mark") + } + st.MarkReauthored(key, 12, "aaa", 6, now) + r, _ := st.Get(key) + if !r.Reauthored() || r.ReauthorIssue != 12 || r.ReauthorHead != "aaa" || r.ReauthorAttempts != 6 || !r.ReauthoredAt.Equal(now) || r.ReauthorNoted { + t.Fatalf("record = %+v", r) + } + // Same issue+head again: unchanged (the first timestamp stands). + st.MarkReauthored(key, 12, "aaa", 7, now.Add(time.Hour)) + if r, _ = st.Get(key); r.ReauthorAttempts != 6 || !r.ReauthoredAt.Equal(now) { + t.Fatalf("second mark rewrote the record: %+v", r) + } + st.MarkReauthorNoted(key) + st.MarkReauthorNoted(key) + if r, _ = st.Get(key); !r.ReauthorNoted { + t.Fatalf("noted = %+v", r) + } + + // Lookup by issue: lowest PR in the repo wins; other repos/issues don't match. + st.Observe(Key("hivecommons/hive", 95), Fixing, "x") + st.MarkReauthored(Key("hivecommons/hive", 95), 12, "bbb", 6, now) + st.Observe(Key("acme/docs", 3), Fixing, "x") + st.MarkReauthored(Key("acme/docs", 3), 12, "ccc", 6, now) + if got := st.ReauthoredFor("HiveCommons/Hive", 12); got != 90 { + t.Fatalf("ReauthoredFor = %d, want 90", got) + } + if got := st.ReauthoredFor("hivecommons/hive", 13); got != 0 { + t.Fatalf("ReauthoredFor other issue = %d", got) + } + if got := st.ReauthoredFor("acme/docs", 12); got != 3 { + t.Fatalf("ReauthoredFor acme = %d", got) + } + + if err := st.Save(); err != nil { + t.Fatal(err) + } + again := NewStore(st.path, clock) + if err := again.Load(); err != nil { + t.Fatal(err) + } + if r, ok := again.Get(key); !ok || r.ReauthorIssue != 12 || !r.ReauthorNoted || again.ReauthoredFor("hivecommons/hive", 12) != 90 { + t.Fatalf("reloaded = %+v", r) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index a8a2641a4d..4b6ed68b08 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -11,6 +11,7 @@ import ( "reflect" "slices" "sort" + "strconv" "strings" "sync" "time" @@ -99,6 +100,20 @@ type Record struct { SupersededBy int `json:"superseded_by,omitempty"` SupersededAt time.Time `json:"superseded_at,omitempty"` SupersededOpen bool `json:"superseded_open,omitempty"` + // ReauthorIssue / ReauthorHead / ReauthorAttempts / ReauthoredAt record + // that the hive re-authored this PR itself after its fixer gave up on + // ReauthorHead (hivecommons/hive: "we should not need a re-author pill + // on a hive agent's PR"): the PR was closed as superseded and a fresh + // hive PR for ReauthorIssue is opened from the current base. One + // record per issue — the dashboard reads the fresh PR's lineage from + // it and the engine refuses a second automatic re-author. + ReauthorIssue int `json:"reauthor_issue,omitempty"` + ReauthorHead string `json:"reauthor_head,omitempty"` + ReauthorAttempts int `json:"reauthor_attempts,omitempty"` + ReauthoredAt time.Time `json:"reauthored_at,omitempty"` + // ReauthorNoted is true once the close note was posted on the + // re-authored PR; the close itself may be retried, the note never. + ReauthorNoted bool `json:"reauthor_noted,omitempty"` // SupersededClosedFirst is true while the original was closed at // adoption time, before its copy merged (close-first supersession, // hivecommons/hive#15135). The reconciler keeps polling the copy @@ -2133,6 +2148,66 @@ func (s *Store) MarkSuperseded(key string, by int, open bool, now time.Time) { s.dirty = true } +// MarkReauthored records that the hive re-authored key itself for issue +// after its fixer gave up on head after attempts tries. Idempotent per key. +func (s *Store) MarkReauthored(key string, issue int, head string, attempts int, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || issue <= 0 { + return + } + if r.ReauthorIssue == issue && r.ReauthorHead == head { + return + } + r.ReauthorIssue, r.ReauthorHead, r.ReauthorAttempts, r.ReauthoredAt = issue, head, attempts, now + s.items[key] = r + s.dirty = true +} + +// MarkReauthorNoted records that the re-author close note was posted. +func (s *Store) MarkReauthorNoted(key string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.ReauthorNoted { + return + } + r.ReauthorNoted = true + s.items[key] = r + s.dirty = true +} + +// Reauthored reports whether the hive re-authored this PR itself. +func (r Record) Reauthored() bool { + return r.ReauthorIssue > 0 +} + +// ReauthoredFor returns, over the store, the PR the hive already +// re-authored for repo's issue (the record's own number), or 0 when the +// issue has not been re-authored. One automatic re-author per issue. +func (s *Store) ReauthoredFor(repo string, issue int) int { + if s == nil || issue <= 0 { + return 0 + } + s.mu.Lock() + defer s.mu.Unlock() + best := 0 + for key, r := range s.items { + if r.ReauthorIssue != issue { + continue + } + rec, numText, found := strings.Cut(key, "#") + if !found || !strings.EqualFold(rec, repo) { + continue + } + if n, err := strconv.Atoi(numText); err == nil && n > 0 && (best == 0 || n < best) { + best = n + } + } + return best +} + // MarkSupersederMergedNoted records that the diverged-head note was posted // for head, so the next poll of the same head stays silent. func (s *Store) MarkSupersederMergedNoted(key, head string) { diff --git a/src/pkg/webassets/trackerrow/tracker-row-anchor.js b/src/pkg/webassets/trackerrow/tracker-row-anchor.js index 807d3c153e..f91cfd897b 100644 --- a/src/pkg/webassets/trackerrow/tracker-row-anchor.js +++ b/src/pkg/webassets/trackerrow/tracker-row-anchor.js @@ -44,6 +44,10 @@ // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; diff --git a/src/pkg/webassets/trackerrow/trackerrow.go b/src/pkg/webassets/trackerrow/trackerrow.go index 9a0a5af04d..ecaf1aff3a 100644 --- a/src/pkg/webassets/trackerrow/trackerrow.go +++ b/src/pkg/webassets/trackerrow/trackerrow.go @@ -12,8 +12,8 @@ // The files are plain function declarations with no side effects. A host page // supplies what they call: the STAGE_TRACKER_* stage constants // (tracker-words-core.js and agent-now.js on the spoke) and esc(). The anchor -// calls stageTrackerUnderRepair and stageTrackerMergeRefusalFromRaw only when -// they are defined. +// calls stageTrackerUnderRepair, stageTrackerMergeRefusalFromRaw and +// stageTrackerPersonActsOnPR only when they are defined. package trackerrow import "embed" diff --git a/src/proxy/package-lock.json b/src/proxy/package-lock.json index 6e84e835cd..86be927a62 100644 --- a/src/proxy/package-lock.json +++ b/src/proxy/package-lock.json @@ -29,18 +29,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -465,9 +465,9 @@ "license": "MIT" }, "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -708,9 +708,9 @@ } }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", diff --git a/src/scripts/comment-merged-refs.sh b/src/scripts/comment-merged-refs.sh index ddbbdb648f..c9f92f1c2a 100755 --- a/src/scripts/comment-merged-refs.sh +++ b/src/scripts/comment-merged-refs.sh @@ -122,6 +122,7 @@ json.dump(obj, sys.stdout)' posted=0 skipped=0 +card_errors=0 while IFS= read -r issue; do [ -n "$issue" ] || continue issue_json=$(api "repos/${REPO}/issues/${issue}") @@ -180,18 +181,26 @@ sys.exit(1)' # The runtime's hive:status card carries the same condition as an # `issue-partial:<pr>` section; a second notifying comment would duplicate it. # The comments fetched above are handed to the helper so it does not - # re-fetch the same pages. + # re-fetch the same pages. Exit 1 is "no such section"; anything else is a + # read/parse failure, which must not be mistaken for absence and post. card_helper="$(dirname "${BASH_SOURCE[0]}")/../../.github/scripts/hive-status-card.sh" if [ -x "$card_helper" ]; then comments_file=$(mktemp) printf '%s' "$comments_json" > "$comments_file" - if GH_BIN="$GH_BIN" HIVE_COMMENTS_FILE="$comments_file" "$card_helper" has "$REPO" "$issue" "issue-partial:${PR_NUMBER}" 2>/dev/null; then - rm -f "$comments_file" + card_rc=0 + GH_BIN="$GH_BIN" HIVE_COMMENTS_FILE="$comments_file" "$card_helper" has "$REPO" "$issue" "issue-partial:${PR_NUMBER}" || card_rc=$? + rm -f "$comments_file" + if [ "$card_rc" -eq 0 ]; then echo "Skipping #${issue}: hive:status card already carries the partial-merge note." skipped=$((skipped + 1)) continue fi - rm -f "$comments_file" + if [ "$card_rc" -ne 1 ]; then + echo "::error::Skipping #${issue}: could not read its hive:status card (hive-status-card.sh exit ${card_rc}); not posting a possible duplicate." >&2 + card_errors=$((card_errors + 1)) + skipped=$((skipped + 1)) + continue + fi fi comment_body=$(printf '%s\nPR #%s has merged (%s) and referenced this issue with a non-closing `%s` rather than a closing keyword.\n\nThis issue remains open because the merged PR did not use `Closes` / `Fixes` / `Resolves`. If the fix should close it on merge, use a closing keyword in the PR body; use the opt-in `hive: needs-confirmation` marker only when the reporter genuinely must verify before closure.' \ @@ -308,3 +317,8 @@ $closing_issues EOF_CLOSING printf 'Parent auto-close sweep complete for PR #%s: %s parent(s) closed, %s parent(s) skipped.\n' "$PR_NUMBER" "$parent_closed" "$parent_skipped" + +if [ "$card_errors" -gt 0 ]; then + echo "Refs sweep for PR #${PR_NUMBER}: ${card_errors} issue(s) skipped because their hive:status card could not be read." >&2 + exit 1 +fi diff --git a/src/scripts/dashboard-mobile-shots.mjs b/src/scripts/dashboard-mobile-shots.mjs index 08733f234c..635a342f1e 100644 --- a/src/scripts/dashboard-mobile-shots.mjs +++ b/src/scripts/dashboard-mobile-shots.mjs @@ -21,13 +21,17 @@ // clipped-by-strip: a topbar chip whose box pokes outside an overflow-clipping // ancestor strip (how the ≡ drawer toggle lost its left edge on phones, #15476). // -// This is a reporting tool, not a gate: it exits 0 even when findings exist and -// exits 1 only when the harness itself errors. Chrome missing prints SKIP and exits 0. +// General overflow findings remain reporting-only. Preparation/activity acceptance +// violations exit 1; the existing workflow remains non-required/reporting-only. +// Chrome missing is a local SKIP but a canonical CI failure. import { spawn } from 'node:child_process'; import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; +import { createHash } from 'node:crypto'; import { preparationRailLayoutFixture } from './fixtures/dashboard-preparation-rail.mjs'; +import { activityDensityFixture } from './fixtures/dashboard-activity-density.mjs'; +import { waitForDashboardPaint, resetDashboardFixtureOverlays } from './fixtures/dashboard-browser-readiness.mjs'; const CHROME_CANDIDATES = [ process.env.CHROME_BIN, @@ -45,6 +49,8 @@ const PROFILE_DIR = path.join(process.cwd(), '.chrome-dashboard-mobile-shots'); const IOS_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1'; const IPAD_UA = 'Mozilla/5.0 (iPad; CPU OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1'; const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36'; +const DESKTOP_UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36'; +const ACTIVITY_DESKTOP_WIDTHS = [2400, 1440, 1110, 1024]; const VIEWPORTS = [ { name: '390x844@3', width: 390, height: 844, dpr: 3, mobile: true, ua: IOS_UA }, @@ -56,6 +62,8 @@ const VIEWPORTS = [ { name: '932x430@3', width: 932, height: 430, dpr: 3, mobile: true, ua: IOS_UA }, { name: '667x375@2', width: 667, height: 375, dpr: 2, mobile: true, ua: IOS_UA }, { name: '740x360@3', width: 740, height: 360, dpr: 3, mobile: true, ua: ANDROID_UA }, + ...ACTIVITY_DESKTOP_WIDTHS.map(width => ({ name: width + 'x1200@1', width, height: 1200, + dpr: 1, mobile: false, ua: DESKTOP_UA, activityOnly: true })), ]; const THEMES = ['light', 'dark']; @@ -220,6 +228,7 @@ async function main() { const themes = opts.theme ? [opts.theme] : THEMES; const bin = chromePath(); if (!bin) { + if (process.env.CI) throw new Error('Canonical browser proof requires Chrome/Chromium; none found'); console.log('SKIP: Chrome/Chromium not found (set CHROME_BIN or install google-chrome/chromium)'); return; } @@ -254,6 +263,18 @@ async function main() { const report = []; const preparationRailReport = []; + const activityReport = []; + const activityFailures = []; + const fixtureRoot = path.join(process.cwd(), 'src/pkg/dashboard/webstatic/testdata'); + const density = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'tracker-activity-density.json'), 'utf8')); + const probes = ['tracker-header-geometry', 'tracker-decision-interaction'].map(name => ({ + name, source: fs.readFileSync(path.join(fixtureRoot, name + '.js'), 'utf8'), + })); + const event = process.env.GITHUB_EVENT_PATH ? JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) : {}; + const provenance = { head: event.pull_request?.head?.sha || process.env.GITHUB_SHA || 'unpublished-local', + checkoutSHA: process.env.GITHUB_SHA || 'unpublished-local', + generatedAssetSHA256: createHash('sha256').update(fs.readFileSync('src/pkg/dashboard/static/index.html')).digest('hex'), + mockEvidence: true, fixtureSource: density.source }; let socket; try { const tabs = await waitForTabs(); @@ -280,17 +301,126 @@ async function main() { if (result.result.exceptionDetails) throw new Error(result.result.exceptionDetails.exception?.description || 'evaluate failed'); return result.result.result.value; }; + const renderReady = () => evaluate('(' + waitForDashboardPaint.toString() + ')({ dedicatedPreview: true })'); + const screenshot = async (file, viewportOnly = false) => { + const readiness = await renderReady(); + const viewport = viewportOnly ? await evaluate(`({ + x: scrollX, y: scrollY, width: innerWidth, height: innerHeight, + clientWidth: document.documentElement.clientWidth, + clientHeight: document.documentElement.clientHeight + })`) : null; + const clip = viewport ? { x: viewport.x, y: viewport.y, width: viewport.width, height: viewport.height, scale: 1 } : undefined; + const shot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: !viewportOnly, ...(clip ? { clip } : {}) }); + if (shot.error) throw new Error(shot.error.message); + fs.writeFileSync(path.join(opts.out, file), Buffer.from(shot.result.data, 'base64')); + if (!viewport) return; + const pixels = await evaluate(`(async () => { + const image = new Image(); + image.src = ${JSON.stringify('data:image/png;base64,')} + ${JSON.stringify(shot.result.data)}; + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; + const context = canvas.getContext('2d', { willReadFrequently: true }); + context.drawImage(image, 0, 0); + const width = Math.min(canvas.width, Math.floor(${viewport.clientWidth} * canvas.width / ${viewport.width})); + const height = Math.min(canvas.height, Math.floor(${viewport.clientHeight} * canvas.height / ${viewport.height})); + const data = context.getImageData(0, 0, width, height).data; + let painted = false; + for (let pixel = 4; pixel < data.length; pixel += 4) { + if (data[pixel] !== data[0] || data[pixel + 1] !== data[1] || + data[pixel + 2] !== data[2] || data[pixel + 3] !== data[3]) { painted = true; break; } + } + return { painted, width: canvas.width, height: canvas.height, inspectedWidth: width, inspectedHeight: height }; + })()`); + return { file, readiness, viewport, clip, ...pixels, + failures: pixels.painted ? [] : ['Viewport capture contains only a uniform background; DOM assertions are not visual proof'] }; + }; + const nativeDecisionInput = async prefix => { + const failures = []; + const point = await evaluate(`(async () => { + stageTrackerCloseDecisionPop(false); + const trigger = [...document.querySelectorAll('.ham-chevron-decision .ham-decision-trigger')] + .find(button => Number(button.closest('[data-ham-stage]')?.dataset.hamStage) === 80); + if (!trigger) throw new Error('Missing native stage-80 decision trigger'); + trigger.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await new Promise(requestAnimationFrame); + const help = document.querySelector('.ham-chevron-info.config-info'); + help.focus({ preventScroll: true }); + const box = trigger.getBoundingClientRect(); + const portal = document.getElementById('config-tooltip-portal'); + const target = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + return { x: (box.left + box.right) / 2, y: (box.top + box.bottom) / 2, + documentFocused: document.hasFocus(), helpFocused: document.activeElement === help, + triggerReachable: target === trigger || trigger.contains(target), + target: target?.className || target?.tagName || null, + tooltipWasOpen: !!portal && !portal.hidden && getComputedStyle(portal).display !== 'none' }; + })()`); + if (!point.tooltipWasOpen) failures.push('Native pointer precondition: ordinary tooltip was not open'); + if (!point.triggerReachable) failures.push('Native pointer precondition: trigger is intercepted by ' + point.target); + const moved = await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y, pointerType: 'mouse' }); + if (moved.error) throw new Error(moved.error.message); + await sleep(STATE_SETTLE_MS); + const inspect = async mode => { + const result = await evaluate(`(() => { + const dialogs = [...document.querySelectorAll('.ham-decision-pop')]; + const portal = document.getElementById('config-tooltip-portal'); + const tolerance = 1; + const actions = [...(dialogs[0]?.querySelectorAll('.ham-decision-act') || [])].map(action => { + const box = action.getBoundingClientRect(); + const target = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + return { label: action.textContent.trim(), box: box.toJSON(), + target: target?.className || target?.tagName || null, + reachable: box.width > 0 && box.height > 0 && box.left >= -tolerance && + box.right <= innerWidth + tolerance && box.top >= -tolerance && + box.bottom <= innerHeight + tolerance && (target === action || action.contains(target)) }; + }); + return { dialogs: dialogs.length, + tooltipOpen: !!portal && !portal.hidden && getComputedStyle(portal).display !== 'none', + focusInside: !!dialogs[0]?.contains(document.activeElement), actions }; + })()`); + if (result.dialogs !== 1 || result.tooltipOpen) failures.push(mode + ': one unobscured decision dialog required'); + if (mode !== 'native pointer' && !result.focusInside) failures.push(mode + ': keyboard must enter the existing dialog'); + if (!result.actions.length || result.actions.some(action => !action.reachable)) { + failures.push(mode + ': every native decision action must be reachable and unobscured: ' + JSON.stringify(result.actions)); + } + return { mode, ...result }; + }; + const observations = [await inspect('native pointer')]; + const pointerCapture = await screenshot(prefix + '-decision-pointer.png', true); + failures.push(...pointerCapture.failures); + const keys = [{ key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 }, + { key: 'Enter', code: 'Enter', keyCode: 13 }, { key: ' ', code: 'Space', keyCode: 32 }]; + for (const { key, code, keyCode } of keys) { + await evaluate(`(() => { + const trigger = [...document.querySelectorAll('.ham-chevron-decision .ham-decision-trigger')] + .find(button => Number(button.closest('[data-ham-stage]')?.dataset.hamStage) === 80); + trigger.focus({ preventScroll: true }); + return true; + })()`); + for (const type of ['keyDown', 'keyUp']) { + const pressed = await send('Input.dispatchKeyEvent', { type, key, code, windowsVirtualKeyCode: keyCode }); + if (pressed.error) throw new Error(pressed.error.message); + } + observations.push(await inspect('native keyboard ' + JSON.stringify(key))); + } + const keyboardCapture = await screenshot(prefix + '-decision-keyboard.png', true); + failures.push(...keyboardCapture.failures); + await evaluate('stageTrackerCloseDecisionPop(false); true'); + return { pointerPrecondition: point, observations, captures: [pointerCapture, keyboardCapture], failures }; + }; await send('Page.enable'); await send('Runtime.enable'); + // Headless input must own focus for native focusin and keyboard delivery. + await send('Page.bringToFront'); + await send('Emulation.setFocusEmulationEnabled', { enabled: true }); // Each state callback is best-effort: a missing helper yields a skipped shot, not a harness error. const setThemeJS = (theme) => `document.body.classList.toggle('light-mode', ${theme === 'light'}); document.documentElement.style.colorScheme = '${theme}'; true`; - const resetJS = `(() => { + const resetJS = `(async () => { + window.__activityDensityCleanup?.(); document.getElementById('preparation-rail-layout-fixture')?.remove(); - document.querySelectorAll('.config-overlay, .modal-overlay').forEach((el) => { el.classList.add('hidden'); }); - document.documentElement.classList.remove('modal-open'); document.body.classList.remove('modal-open'); - return true; + return await (${resetDashboardFixtureOverlays.toString()})({ dedicatedPreview: true }); })()`; const collapseAllJS = `(() => { const ids = Array.from(document.querySelectorAll('[data-dashboard-section]')).map((el) => el.id).filter(Boolean); @@ -319,7 +449,7 @@ async function main() { screenOrientation: { type: landscape ? 'landscapePrimary' : 'portraitPrimary', angle: landscape ? 90 : 0 }, }); await send('Emulation.setUserAgentOverride', { userAgent: vp.ua }); - await send('Emulation.setTouchEmulationEnabled', { enabled: true }); + await send('Emulation.setTouchEmulationEnabled', { enabled: vp.mobile }); for (const theme of themes) { await send('Page.navigate', { url: `file://${process.cwd()}/src/pkg/dashboard/static/index.html` }); await sleep(PAGE_SETTLE_MS); @@ -335,6 +465,8 @@ async function main() { link.href = url; })))`); await evaluate(setThemeJS(theme)); + const pageReadiness = await renderReady(); + let fixtureCleanup; const sectionIDs = await evaluate(collapseAllJS); const states = [{ name: 'collapsed', run: async () => true }]; @@ -352,10 +484,51 @@ async function main() { if (result.failures.length) throw new Error('Preparation rail layout: ' + result.failures.join('; ')); return true; } }); + if (vp.activityOnly) states.length = 0; + states.push({ name: 'activity-density', run: async () => { + await evaluate(collapseAllJS); + if (!await evaluate(expandOneJS('activity-monitor-section'))) throw new Error('Cannot expand actual Activity Monitor'); + const fixture = await evaluate('(' + activityDensityFixture.toString() + ')(' + JSON.stringify(density) + ')'); + await sleep(STATE_SETTLE_MS); + const capture = await screenshot(`${vp.name}-${theme}-activity-density-viewport.png`, true); + const results = [{ probe: 'viewport-paint', ok: capture.painted, result: capture }]; + if (!capture.painted) activityFailures.push(vp.name + ' ' + theme + ' blank viewport capture'); + for (const probe of probes) { + const result = await evaluate(`(async () => { + try { return { ok: true, result: await (${probe.source})({ dedicatedPreview: true }) }; } + catch (error) { + let result; + try { result = JSON.parse(error.message); } catch (_) { result = { failures: [String(error.stack || error)] }; } + return { ok: false, result }; + } + })()`); + results.push({ probe: probe.name, ...result }); + if (!result.ok) activityFailures.push(vp.name + ' ' + theme + ' ' + probe.name); + } + let native; + try { native = await nativeDecisionInput(`${vp.name}-${theme}-activity`); } + catch (error) { native = { failures: [String(error.stack || error)] }; } + const nativeOK = native.failures.length === 0; + results.push({ probe: 'native-CDP-pointer-keyboard', ok: nativeOK, result: native }); + if (!nativeOK) activityFailures.push(vp.name + ' ' + theme + ' native input'); + const result = { viewport: vp.name, theme, provenance, pageReadiness, fixtureCleanup, fixture, results }; + activityReport.push(result); + fs.writeFileSync(path.join(opts.out, `${vp.name}-${theme}-activity-probes.json`), JSON.stringify(result, null, 2) + '\n'); + return true; + } }); for (const state of states) { - await evaluate(resetJS); - const ok = await state.run(); + fixtureCleanup = await evaluate(resetJS); + let ok; + try { ok = await state.run(); } + catch (error) { + if (state.name !== 'activity-density') throw error; + activityFailures.push(vp.name + ' ' + theme + ' fixture/harness'); + const result = { viewport: vp.name, theme, provenance, failures: [String(error.stack || error)] }; + activityReport.push(result); + fs.writeFileSync(path.join(opts.out, `${vp.name}-${theme}-activity-probes.json`), JSON.stringify(result, null, 2) + '\n'); + ok = true; // Capture the broken fixture too; fail after all viewports. + } if (!ok) { console.log(`skip ${vp.name} ${theme} ${state.name}: not available`); continue; @@ -363,21 +536,22 @@ async function main() { await sleep(STATE_SETTLE_MS); const findings = await evaluate(SCAN_EXPRESSION); for (const f of findings) report.push({ viewport: vp.name, theme, state: state.name, ...f }); - const shot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); - if (shot.error) throw new Error(shot.error.message); const file = `${vp.name}-${theme}-${state.name}.png`.replace(/[^A-Za-z0-9._@-]/g, '_'); - fs.writeFileSync(path.join(opts.out, file), Buffer.from(shot.result.data, 'base64')); + await screenshot(file); console.log(`shot ${file}: ${findings.length} finding(s)`); } + await evaluate(resetJS); } } } finally { if (socket) socket.close(); fs.writeFileSync(path.join(opts.out, 'overflow-report.json'), JSON.stringify(report, null, 2) + '\n'); fs.writeFileSync(path.join(opts.out, 'preparation-rail-layout.json'), JSON.stringify(preparationRailReport, null, 2) + '\n'); + fs.writeFileSync(path.join(opts.out, 'activity-layout.json'), JSON.stringify({ provenance, runs: activityReport }, null, 2) + '\n'); await cleanup(); } console.log(`wrote ${report.length} finding(s) to ${path.join(opts.out, 'overflow-report.json')}`); + if (activityFailures.length) throw new Error('Activity browser acceptance failed: ' + activityFailures.join('; ')); } main().catch((err) => { diff --git a/src/scripts/fixtures/dashboard-activity-density.mjs b/src/scripts/fixtures/dashboard-activity-density.mjs new file mode 100644 index 0000000000..f9a9076d7a --- /dev/null +++ b/src/scripts/fixtures/dashboard-activity-density.mjs @@ -0,0 +1,168 @@ +// Dedicated file:// acceptance page only. All evidence/permissions are mocks; +// real production renderers and delegated interaction handlers remain in use. +export function activityDensityFixture(input) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel) throw new Error('Actual Activity Monitor panel is missing'); + const nowMs = Date.now(), observed = new Date(nowMs).toISOString(); + const saved = { data: _stageTracker, rows: _stageTrackerRows, + role: window._hiveRole, user: window._hiveUser, + preparation: [_stageTrackerPreparationShown, _stageTrackerPreparationRendered, + _stageTrackerPreparationInline, _stageTrackerPreparationNow] }; + const items = structuredClone(input.rows); + const rebase = item => { + item.state = 'open'; + item.stage_since = observed; + for (const key of ['ci_activity', 'review_activity', 'code_activity']) { + if (item[key]) item[key].observed_at = observed; + } + if (item.decision_needed && !item.decision_needed.options) { + item.decision_needed.options = [{ action: 'decide:approve', enabled: true, + label: 'Review mock decision', consequence: 'Mock fixture only' }]; + } + for (const child of item.linked_prs || []) rebase(child); + }; + items.forEach(rebase); + const mockPR = (number, stage, extra = {}) => ({ + repo: 'fixture/activity', kind: 'pr', number, stage, state: 'open', + title: 'Mock acceptance projection — not a live PR', + head: 'mock-current-head-' + number, stage_since: observed, + url: 'https://example.invalid/activity/' + number, ...extra, + }); + const track = (item, state, caption) => ({ + head: item.head, state, caption, observed_at: observed, source: 'acceptance-fixture', + }); + const unknown = mockPR(9001, 50, { caption: 'Current-head evidence unavailable' }); + const conflict = mockPR(9002, 80, { + merge_gate: { state: 'claim-conflict:9003', duplicate_issue: 9000 }, + decision_needed: { question: 'Which mock implementation should be kept?', + blocker: 'Both claim mock issue #9000; neither is admitted.', + options: [{ action: 'decide:approve', enabled: true, label: 'Keep this implementation', consequence: 'Mock fixture only' }] }, + }); + const longHandle = 'thatguywob'.repeat(12); + const waiting = mockPR(9004, 71, { display_column: 30, + caption: 'Waiting for @' + longHandle + ' · not observed coding', + author: longHandle, author_kind: 'human', + code_activity: { state: 'waiting_owner', head: 'mock-current-head-9004', + caption: 'Waiting for @' + longHandle + ' · not observed coding', source: 'native-author-wait' }, + push: { state: 'waiting', login: longHandle, since: observed, next: 're-review' }, + }); + const running = mockPR(9005, 50); + running.ci_activity = track(running, 'running', 'CI running'); + running.ci_activity.active = true; + running.review_activity = track(running, 'approved', 'Review approved'); + const held = mockPR(9006, 70, { caption: 'Waiting for fixer · no observed code work', + hold: { by: 'hanthor', pill: 'Held by @hanthor', reason: 'Mock human hold' }, + modifiers: ['hold'] }); + const coding = mockPR(9007, 70, { display_column: 30 }); + coding.code_activity = { ...track(coding, 'fixing', 'Remediating · fixer'), active: true, + since: observed, source: 'fix-dispatch+successful-edit+verified-git-worktree' }; + coding.ci_activity = { ...track(coding, 'running', 'CI running'), active: true }; + coding.review_activity = { ...track(coding, 'reviewing', 'Review working · reviewer'), active: true }; + const triage = { repo: 'fixture/activity', kind: 'issue', number: 9008, stage: 15, + state: 'open', title: 'Mock issue-only triage controls and long wrapping metadata', + url: 'https://example.invalid/activity/9008', operator_action_count: 7 }; + // One short caption ("Open · hold") → a one-line-tall chevron row; the + // long-handle row above wraps to two. Both heights are probed. + const parked = { repo: 'fixture/activity', kind: 'issue', number: 9009, stage: 0, + state: 'open', title: 'Mock held issue with a one-line chevron caption', + url: 'https://example.invalid/activity/9009', modifiers: ['hold'], + hold: { by: 'hanthor', pill: 'Held by @hanthor', reason: 'Mock human hold' } }; + items.push(unknown, conflict, waiting, running, held, coding, triage, parked); + const prUnder = (repo, issueNumber, pr, title) => ({ + repo, kind: 'issue', number: issueNumber, stage: 40, state: 'open', + title, url: 'https://example.invalid/activity/' + issueNumber, linked_prs: [pr], + }); + const prepFront = (number, base, ciState, reviewState) => { + const item = mockPR(number, 74, { repo: 'hivecommons/hive', base_ref: base, + caption: 'Head changed; preparation unverified; CI/re-review queued', + push: { state: 'pushed', login: 'fixture-owner', since: observed, next: 're-review' } }); + item.ci_activity = track(item, ciState, ciState === 'unknown' ? 'Required checks not observed' : 'CI waiting · test not observed'); + item.review_activity = track(item, reviewState, 'Review ' + reviewState + ' · ' + (reviewState === 'assigned' ? 'adjudicator' : 'unassigned')); + return item; + }; + const front16450 = prepFront(16450, 'v6', 'unknown', 'assigned'); + const front16451 = prepFront(16451, 'v5', 'waiting', 'queued'); + const issue16420 = items.find(item => item.kind === 'issue' && item.number === 16420); + issue16420.stage = 40; + issue16420.linked_prs = [front16450, { number: 16436, stage: 74, state: 'closed', + title: 'Mock closed adopted original', superseded_by: 16450, base_ref: 'v6' }]; + items.push(prUnder('hivecommons/hive', 16363, front16451, 'Mock preparation front on a one-to-one issue')); + const pluk = mockPR(436, 50, { repo: 'hivecommons/pluk' }); + pluk.ci_activity = track(pluk, 'passing', 'CI passed'); + pluk.review_activity = track(pluk, 'assigned', 'Review assigned · ci-maintainer'); + items.push(prUnder(pluk.repo, 435, pluk, 'Mock CI-passed / review-assigned linked row')); + const pr16437Index = items.findIndex(item => item.kind === 'pr' && item.number === 16437); + const pr16437 = items.splice(pr16437Index, 1)[0]; + pr16437.stage = 60; + pr16437.manual_merge = false; + pr16437.ci_activity = track(pr16437, 'unknown', 'Required checks not observed'); + pr16437.review_activity = track(pr16437, 'approved', 'Review approved'); + items.push(prUnder(pr16437.repo, 16421, pr16437, 'Mock approved-review / unknown-CI linked row')); + const superseded = items.find(item => item.number === 16438).linked_prs.find(pr => pr.number === 16446); + superseded.stage = 70; + superseded.display_column = 50; + superseded.superseded = true; + superseded.human_attention = { kind: 'pr', number: superseded.number, head: superseded.head, + reason: 'Superseded by #16449 — a maintainer decides whether to close this mock implementation' }; + superseded.code_activity = { ...track(superseded, 'waiting_fixer', 'Waiting for fixer · no observed code work') }; + superseded.decision_needed = { question: 'Close this mock implementation as superseded by #16449?', + options: [{ action: 'decide:close-superseded', enabled: true, label: 'Close mock superseded PR' }] }; + superseded.review_activity = track(superseded, 'changes_requested', 'Review findings · human decision'); + const base_preparation = [front16450, front16451].map(front => ({ + repo: front.repo, base_ref: front.base_ref, state: 'observed', + owner: { number: front.number, role: 'owner', state: 'current', + head_sha: 'mock-previous-head-' + front.number, current_head: front.head, + since: observed, detail: 'Head changed; current preparation unverified' }, waiting: [], + })); + const host = document.createElement('div'); + host.id = 'activity-density-layout-fixture'; + const note = document.createElement('p'); + note.textContent = 'Acceptance fixture: screenshot-shaped identities with MOCK stages/evidence/permissions; not authenticated live projection.'; + host.appendChild(note); + window.__activityDensityCleanup = () => { + stageTrackerCloseDecisionPop(false); + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); + host.remove(); + _stageTracker = saved.data; + _stageTrackerRows = saved.rows; + window._hiveRole = saved.role; + window._hiveUser = saved.user; + [_stageTrackerPreparationShown, _stageTrackerPreparationRendered, + _stageTrackerPreparationInline, _stageTrackerPreparationNow] = saved.preparation; + delete window.__activityDensityCleanup; + }; + _stageTracker = { items, base_preparation }; + _stageTrackerRows = items; + window._hiveRole = 'owner'; + window._hiveUser = 'fixture-owner'; + // Display labels are fixture inputs; physical order/boundaries stay canonical. + const labels = { 0: 'Open', 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', + 50: 'CI / Review', 80: 'Merge queue' }; + const stages = STAGE_TRACKER_PATH.map(number => ({ number, short: labels[number] || String(number) })).concat([ + { number: 15, short: 'Triage needed', branch_from: 10 }, + { number: 70, short: 'Remediating', branch_from: 50 }, + { number: 71, short: 'Needs author', branch_from: 30 }, + { number: 72, short: 'Returned to contributor', branch_from: 30 }, + { number: 74, short: 'Adopted by hive', branch_from: 50 }, + { number: 85, short: 'Needs human decision', branch_from: 80 }, + { number: 90, short: 'Ready for human merge', branch_from: 80 }, + ]); + const ctx = { nowMs, items, events: {}, noteTuck: false, sharedPRs: {}, workers: {} }; + try { + host.appendChild(stageTrackerRowNode('fixture-columns', stageTrackerHeaderHtml(stages))); + const ordered = stageTrackerPreparationOrderRows(_stageTracker, items, stages); + _stageTrackerRows = ordered; + stageTrackerPreparationVisualSync(_stageTracker, ordered, ordered, stages, nowMs); + const rows = ordered.map(item => ({ key: stageTrackerItemKey(item), html: stageTrackerRowHtml(item, stages, ctx) })); + for (const row of stageTrackerPreparationInlineRows(rows, ordered, stages)) host.appendChild(stageTrackerRowNode(row.key, row.html)); + panel.appendChild(host); + if (panel.dataset.hamWired !== '1') stageTrackerWireRowActions(panel); + } catch (error) { + window.__activityDensityCleanup(); + throw error; + } + host.scrollIntoView(); + return { provenance: input.provenance, mockEvidence: true, observedAt: observed, + additionalScreenshotShape: 'Screenshot 2026-11-03 at 12.36.31 PM.png', + rows: items.map(item => stageTrackerItemKey(item)) }; +} diff --git a/src/scripts/fixtures/dashboard-browser-readiness.mjs b/src/scripts/fixtures/dashboard-browser-readiness.mjs new file mode 100644 index 0000000000..b731382721 --- /dev/null +++ b/src/scripts/fixtures/dashboard-browser-readiness.mjs @@ -0,0 +1,72 @@ +// Serialized into the existing harness's isolated file:// Chrome page only. +export function waitForDashboardPaint({ dedicatedPreview = false, timeoutMs = 10000, stableFrames = 2 } = {}) { + if (!dedicatedPreview) throw new Error('Render readiness requires a dedicated preview page'); + return new Promise((resolve, reject) => { + const started = performance.now(); + let frame, last = null, previous = '', stable = 0; + const finish = (error, value) => { + clearTimeout(timer); + cancelAnimationFrame(frame); + if (error) reject(error); else resolve(value); + }; + const timer = setTimeout(() => finish(new Error(JSON.stringify({ + failures: ['Dashboard render readiness timed out'], timeoutMs, last, + }))), timeoutMs); + const sample = () => { + const body = document.body, root = document.documentElement; + const bodyStyle = body && getComputedStyle(body), rootStyle = root && getComputedStyle(root); + const box = body?.getBoundingClientRect(); + last = { readyState: document.readyState, visibilityState: document.visibilityState, + opacity: bodyStyle?.opacity, visibility: bodyStyle?.visibility, display: bodyStyle?.display, + rootOpacity: rootStyle?.opacity, rootVisibility: rootStyle?.visibility, rootDisplay: rootStyle?.display, + width: box?.width, height: box?.height }; + const ready = document.readyState !== 'loading' && document.visibilityState === 'visible' && + last.opacity === '1' && last.visibility === 'visible' && last.display !== 'none' && + last.rootOpacity === '1' && last.rootVisibility === 'visible' && last.rootDisplay !== 'none' && + last.width > 0 && last.height > 0; + const signature = JSON.stringify(last); + stable = ready ? (signature === previous ? stable + 1 : 1) : 0; + previous = signature; + if (stable >= stableFrames) { + finish(null, { ready: true, elapsedMs: performance.now() - started, stableFrames: stable, state: last }); + } else { + frame = requestAnimationFrame(sample); + } + }; + frame = requestAnimationFrame(sample); + }); +} + +export async function resetDashboardFixtureOverlays({ dedicatedPreview = false, maxDismissals = 32, settleTimeoutMs = 1000 } = {}) { + if (!dedicatedPreview) throw new Error('Fixture cleanup requires a dedicated preview page'); + if (typeof hiveDismissTopOverlay !== 'function' || typeof hiveOverlayIsOpen !== 'function') { + throw new Error('Native dashboard overlay cleanup is unavailable'); + } + // These are the three modal producers in the legacy screenshot sequence. + const ownedSelector = '#config-overlay, #kb-modal-overlay, .hive-dialog-overlay'; + const remaining = () => [...document.querySelectorAll(ownedSelector)] + .filter(overlay => hiveOverlayIsOpen(overlay)) + .map(overlay => overlay.id || overlay.className); + let dismissals = 0; + for (; dismissals < maxDismissals; dismissals++) { + if (!hiveDismissTopOverlay()) break; + } + if (dismissals === maxDismissals) { + throw new Error(JSON.stringify({ failures: ['Native overlay cleanup exceeded its dismissal bound'], + maxDismissals, remaining: remaining() })); + } + // Let the production modal observer release its root/body scroll lock. + await new Promise((resolve, reject) => { + const frame = requestAnimationFrame(() => { clearTimeout(timer); resolve(); }); + const timer = setTimeout(() => { + cancelAnimationFrame(frame); + reject(new Error('Native fixture cleanup observer did not settle before timeout')); + }, settleTimeoutMs); + }); + const state = { dismissals, remaining: remaining(), + scrollLocked: document.documentElement.classList.contains('modal-open') || document.body.classList.contains('modal-open') }; + if (state.remaining.length || state.scrollLocked) { + throw new Error(JSON.stringify({ failures: ['Prior fixture overlay or modal-open scroll lock survived native cleanup'], ...state })); + } + return state; +} diff --git a/src/scripts/fixtures/dashboard-preparation-rail.mjs b/src/scripts/fixtures/dashboard-preparation-rail.mjs index 06950a23f4..648c512df9 100644 --- a/src/scripts/fixtures/dashboard-preparation-rail.mjs +++ b/src/scripts/fixtures/dashboard-preparation-rail.mjs @@ -23,9 +23,7 @@ export function preparationRailLayoutFixture() { html: stageTrackerRowHtml(item, [], { ...ctx, prevRow: items[i - 1], nextRow: items[i + 1] }) })); const block = document.createElement('div'); const rendered = stageTrackerPreparationInlineRows(rows, items, []); - block.innerHTML = rendered.map(row => row.html).join(''); - // The production reconciler stamps keys separately from the row renderer. - [...block.children].forEach((element, index) => { element.dataset.hamKey = rendered[index].key; }); + for (const row of rendered) block.appendChild(stageTrackerRowNode(row.key, row.html)); host.appendChild(block); return block; }; diff --git a/src/scripts/test-comment-merged-refs.sh b/src/scripts/test-comment-merged-refs.sh index 12d139e738..66b32943b5 100755 --- a/src/scripts/test-comment-merged-refs.sh +++ b/src/scripts/test-comment-merged-refs.sh @@ -163,6 +163,11 @@ JSON repos/hivecommons/hive/pulls/133) cat <<'JSON' {"number":133,"merged_at":"2026-09-10T21:35:00Z","html_url":"https://github.com/hivecommons/hive/pull/133","body":"Refs #24"} +JSON + ;; + repos/hivecommons/hive/pulls/134) + cat <<'JSON' +{"number":134,"merged_at":"2026-09-10T21:40:00Z","html_url":"https://github.com/hivecommons/hive/pull/134","body":"Refs #25"} JSON ;; repos/hivecommons/hive/issues/10) @@ -192,6 +197,9 @@ JSON repos/hivecommons/hive/issues/24) printf '{"number":24,"state":"open","user":{"login":"maintainer"},"labels":[]}\n' ;; + repos/hivecommons/hive/issues/25) + printf '{"number":25,"state":"open","user":{"login":"maintainer"},"labels":[]}\n' + ;; repos/hivecommons/hive/collaborators/maintainer/permission) printf 'write\n' ;; @@ -221,6 +229,9 @@ JSON repos/hivecommons/hive/issues/24/timeline*) printf '[[]]\n' ;; + repos/hivecommons/hive/issues/25/timeline*) + printf '[[]]\n' + ;; repos/hivecommons/hive/issues/10/comments*) printf '[[]]\n' ;; @@ -243,6 +254,11 @@ JSON repos/hivecommons/hive/issues/24/comments*) cat <<'JSON' [[{"id":2401,"user":{"login":"somebody","type":"User"},"body":"quoting the card:\n<!-- hive:status -->\n<!-- hive:status:section=issue-partial:133 -->\nPartially addressed by #133.\n<!-- /hive:status:section -->"}]] +JSON + ;; + repos/hivecommons/hive/issues/25/comments*) + cat <<'JSON' +[[{"id":2501,"user":"not-an-object","body":"malformed payload"}]] JSON ;; repos/hivecommons/hive/issues/90/comments*) @@ -543,6 +559,21 @@ else cat "$CALL_LOG" | sed 's/^/ | /' fi +# --- hive:status card: a card read/parse failure is an error, not absence --- +: > "$CALL_LOG" +set +e +card_error_output=$(CALL_LOG="$CALL_LOG" BODY_LOG="$BODY_LOG" GH_BIN="$GH_STUB" bash "$CHECKER" --repo hivecommons/hive --pr 134 2>&1) +card_error_rc=$? +set -e +if [ "$card_error_rc" -ne 0 ] && ! grep -q '^POST repos/hivecommons/hive/issues/25/comments' "$CALL_LOG" \ + && echo "$card_error_output" | grep -q '::error::Skipping #25: could not read its hive:status card'; then + pass "an unreadable hive:status card fails the sweep visibly instead of posting a possible duplicate" +else + bad "expected a non-zero exit, an ::error:: line and no POST on #25 (rc=${card_error_rc})" + echo "$card_error_output" | sed 's/^/ | /' + cat "$CALL_LOG" | sed 's/^/ | /' +fi + # --- hive-status-card.sh upsert: edits only the posting identity's comment --- CARD_HELPER="${HERE}/../../.github/scripts/hive-status-card.sh" UPSERT_BODY="$TMP/upsert-body.md"