diff --git a/changelog.d/added-hub-spoke-pointer.md b/changelog.d/added-hub-spoke-pointer.md new file mode 100644 index 0000000000..db345009fb --- /dev/null +++ b/changelog.d/added-hub-spoke-pointer.md @@ -0,0 +1 @@ +- Hub My Hives: a dismissible "Your hive is ready → Open your hive ↗" callout for owners explains that the hub only lists hives (the Guide, settings and GitHub App install live inside the hive), names any attention item that must be fixed there, and points at the row ⋯ menu; the hive-name link gains an ↗ glyph and tooltip and the ⋮ button a "Manage: permissions, pause, funding, delete…" hint. Dismissal is per user and hive in localStorage and re-arms when a new attention item appears. diff --git a/changelog.d/changed-16668-shared-age-word.md b/changelog.d/changed-16668-shared-age-word.md new file mode 100644 index 0000000000..0b8b89937d --- /dev/null +++ b/changelog.d/changed-16668-shared-age-word.md @@ -0,0 +1 @@ +- The stage tracker's row tooltip and current-stage line now share one relative-age formatter (#16668) diff --git a/changelog.d/changed-activity-monitor-base-pill-by-repo-chip.md b/changelog.d/changed-activity-monitor-base-pill-by-repo-chip.md new file mode 100644 index 0000000000..59402ac43c --- /dev/null +++ b/changelog.d/changed-activity-monitor-base-pill-by-repo-chip.md @@ -0,0 +1 @@ +- Activity Monitor rows now draw a PR's base-branch pill (`v5`, `main`) right after the repo chip at the head of the row, before the issue number, instead of in the right-hand modifier cluster; the pill names its PR on hover ("PR #N targets v5") and rows with no linked PR show none. ([#16620](https://github.com/hivecommons/hive/issues/16620)) diff --git a/changelog.d/changed-hive-permission-pill-wording.md b/changelog.d/changed-hive-permission-pill-wording.md new file mode 100644 index 0000000000..e21b15a3bc --- /dev/null +++ b/changelog.d/changed-hive-permission-pill-wording.md @@ -0,0 +1 @@ +- Activity Monitor: the muted pill a PR wears while the hive's GitHub App is missing a permission now reads "hive bot lacks permission" instead of "unauthorized", and its tooltip, the row hover line, the Needs-attention chip title, the needs-human tip, the human-merge gate word and the decision popover say the same — nobody did anything illegitimate, the App installation lacks one permission (hivecommons/hive#16639). The `hive:unauthorized` label, comment marker and API fields are unchanged. diff --git a/changelog.d/changed-queued-for-merge-wording.md b/changelog.d/changed-queued-for-merge-wording.md new file mode 100644 index 0000000000..fa263a49ef --- /dev/null +++ b/changelog.d/changed-queued-for-merge-wording.md @@ -0,0 +1 @@ +- Activity Monitor: every PR whose only remaining step is the merge itself now reads one chevron word, **Queued for merge**, with a short qualifier after the dot saying why it has not merged yet — *· next pass in 42s*, *· checking now*, *· soak 12m left*, *· 2nd of 3* (merge train), *· next pass* (Approve / Let hive decide), *· after CI* (Approve and let hive merge while checks run, or a merge call refused for unreported checks), *· needs rebase* (head moved under the merge call), *· branch protection pending*. Three adjacent approved rows on hive's own tracker read *Ready for auto merge …*, *Approved · hive will…* and *Approved · merge queu…*; the tooltip keeps the full explanation. *Soaking*, *Merging*, *Rebasing*, *Needs human decision* and a *Merge failed* a person must fix stay their own words (hivecommons/hive#16653). diff --git a/changelog.d/fixed-16629.md b/changelog.d/fixed-16629.md new file mode 100644 index 0000000000..800a14f3ee --- /dev/null +++ b/changelog.d/fixed-16629.md @@ -0,0 +1 @@ +- Merged ledger writes no longer fail with "rename ... no such file or directory" when two writers race on the same temp file (#16629). diff --git a/changelog.d/fixed-16649.md b/changelog.d/fixed-16649.md new file mode 100644 index 0000000000..61934d0b33 --- /dev/null +++ b/changelog.d/fixed-16649.md @@ -0,0 +1 @@ +- Hub SHA poller backs off all commit-message fetches on a 403/429 and warns once per throttle window instead of once per SHA, so a rate-limited token no longer trips the `sha_poll_commit_message_unavailable` fleet report ([#16649](https://github.com/hivecommons/hive/issues/16649)). diff --git a/changelog.d/fixed-16652-sso-failure-shows-login.md b/changelog.d/fixed-16652-sso-failure-shows-login.md new file mode 100644 index 0000000000..ae6b91b982 --- /dev/null +++ b/changelog.d/fixed-16652-sso-failure-shows-login.md @@ -0,0 +1 @@ +- Opening a hosted hive from the hub when the hive cannot verify the hub's single sign-on now shows the "Sign-in didn't complete" page with a GitHub sign-in button, instead of being replaced by the gateway's "Hive is restarting" outage page ([#16652](https://github.com/hivecommons/hive/issues/16652)). diff --git a/changelog.d/fixed-16670-api-reference-activity-fields.md b/changelog.d/fixed-16670-api-reference-activity-fields.md new file mode 100644 index 0000000000..7064d76189 --- /dev/null +++ b/changelog.d/fixed-16670-api-reference-activity-fields.md @@ -0,0 +1 @@ +- API reference now lists the check-count and perspective fields of stage-tracker activity observations ([#16670](https://github.com/hivecommons/hive/issues/16670)). diff --git a/changelog.d/fixed-16674-stage-tracker-ci-comment.md b/changelog.d/fixed-16674-stage-tracker-ci-comment.md new file mode 100644 index 0000000000..125add8378 --- /dev/null +++ b/changelog.d/fixed-16674-stage-tracker-ci-comment.md @@ -0,0 +1 @@ +- Clarify the `StageTrackerActivity` source documentation: CI activity uses the resolved required checks when branch protection is known, otherwise all check runs observed on the head. This corrects the description without changing runtime behavior ([#16674](https://github.com/hivecommons/hive/pull/16674)). diff --git a/changelog.d/fixed-accept-triage-advances-stage.md b/changelog.d/fixed-accept-triage-advances-stage.md new file mode 100644 index 0000000000..f8b1b6ece9 --- /dev/null +++ b/changelog.d/fixed-accept-triage-advances-stage.md @@ -0,0 +1 @@ +- Activity Monitor "Accept triage" now moves the issue to 010 Actionable in the same request: the handler writes `stage/010-actionable` alongside `triage/accepted` when the issue has no stage label or wears `stage/015-triage-needed` (never regressing a later stage, never on a held issue), and the tracker no longer reads an issue carrying `triage/accepted` with no stage label as 000-new while waiting for the engine's next pass. diff --git a/changelog.d/fixed-acmm-install-e2e.md b/changelog.d/fixed-acmm-install-e2e.md new file mode 100644 index 0000000000..6ffe3d45a3 --- /dev/null +++ b/changelog.d/fixed-acmm-install-e2e.md @@ -0,0 +1 @@ +- Recognize install, boot, and explicitly named E2E GitHub Actions workflows in the ACMM E2E prerequisite, retaining web/configuration and directory alternatives without treating unrelated CI workflows as E2E coverage. diff --git a/changelog.d/fixed-ci-activity-unknown-caption.md b/changelog.d/fixed-ci-activity-unknown-caption.md new file mode 100644 index 0000000000..056a4e8cfa --- /dev/null +++ b/changelog.d/fixed-ci-activity-unknown-caption.md @@ -0,0 +1 @@ +- Activity Monitor stage tracker: a PR head whose checks are still reporting now reads `CI running · 4 checks pending` (chevron `CI 7/11 · 4 running`, or the last one or two unfinished names) instead of `CI activity unknown · last observed missing` / `CI unknown · no check results observed` / `no verdict yet`; a required check with no run while others still execute is one sentence in the tooltip rather than the "missing" verdict; the "no check results observed" wording is reserved for a head with zero check runs; and the chevron tooltip states each fact once (count word, detail sentence, head, source, observation time) instead of repeating the unreported check four times (#16630). Check names embedded in captions and chevron text are wrapped in single quotes. diff --git a/changelog.d/fixed-ci-partial-ring-running.md b/changelog.d/fixed-ci-partial-ring-running.md new file mode 100644 index 0000000000..e7c4df5855 --- /dev/null +++ b/changelog.d/fixed-ci-partial-ring-running.md @@ -0,0 +1 @@ +- Activity Monitor: a CI ring that is not yet full now renders the CI chevron active ("CI 13/19 · running") beside a running Review instead of a silent part-green glyph; check-run motion on the head leads red, unreported or ambiguous neighbours, and icon-only green is reserved for a complete ring (hivecommons/hive#16631). diff --git a/changelog.d/fixed-cline-install-retry.md b/changelog.d/fixed-cline-install-retry.md new file mode 100644 index 0000000000..934efb0933 --- /dev/null +++ b/changelog.d/fixed-cline-install-retry.md @@ -0,0 +1 @@ +- Hive and contributor image builds retry Cline installation with fresh npm metadata up to four times to tolerate transient registry propagation failures ([#16666](https://github.com/hivecommons/hive/issues/16666)). diff --git a/changelog.d/fixed-merge-celebration-external.md b/changelog.d/fixed-merge-celebration-external.md new file mode 100644 index 0000000000..92c7d294bd --- /dev/null +++ b/changelog.d/fixed-merge-celebration-external.md @@ -0,0 +1 @@ +- Activity Monitor: a PR merged by anyone — a maintainer's `gh pr merge --admin` as much as the hive's own sweep — now leaves the board with the bee fly-off and a merge toast naming the merger (`#16644 merged by @clubanderson` / `merged by 🐝 hive`); `recently_merged` is the union of the audit log and the merged ledger with `merged_by`, an `issue_comment` on a just-merged PR no longer reads as "closed", and a closed-not-merged exit keeps its quiet toast (hivecommons/hive#16658). diff --git a/changelog.d/fixed-pr-progress-chevron-fallback.md b/changelog.d/fixed-pr-progress-chevron-fallback.md new file mode 100644 index 0000000000..0fc6a63580 --- /dev/null +++ b/changelog.d/fixed-pr-progress-chevron-fallback.md @@ -0,0 +1 @@ +- Activity Monitor: the PR in progress chevron is the row's fallback — it defers (settled, icon only) whenever CI or Review runs, so CI + Review is the only pair ever active together — and its words are the PR's lifecycle (`Unassigned · next: scanner`, `Waiting for @author · fix owed`), never the CI / review verdict — and an active CI / Review chevron has exactly one fill: the stalled-blocker track no longer renders a darker amber, and running checks stay active whatever the poll's age (hivecommons/hive#16643). diff --git a/changelog.d/fixed-rereview-pill-attribution.md b/changelog.d/fixed-rereview-pill-attribution.md new file mode 100644 index 0000000000..6286525ffd --- /dev/null +++ b/changelog.d/fixed-rereview-pill-attribution.md @@ -0,0 +1 @@ +- Activity Monitor: a pushed head with nothing against it now waits on `🐝 hive reviewer · re-review of ` instead of the PR author (`rework.owed_by`), the Review chevron is the lit one once CI is green, and the GraphQL PR batch no longer caches a truncated `statusCheckRollup` page as the head's full check list — which had read `CI 7/11 · required check "test" hasn't reported` on an all-green head with 70+ contexts (#16635). diff --git a/changelog.d/fixed-review-track-never-unknown.md b/changelog.d/fixed-review-track-never-unknown.md new file mode 100644 index 0000000000..03de9b5792 --- /dev/null +++ b/changelog.d/fixed-review-track-never-unknown.md @@ -0,0 +1 @@ +- The Activity Monitor's Review and CI chevrons never say "activity unknown": with no verdict and no reviewer in flight the tooltip states what the head waits on (closed, draft, waiting for CI, not started and who is next, or no data for the head yet · refreshing), a settled verdict names who decided, how long ago and each perspective's verdict with its first finding, and settled verdicts stay known as observations age. diff --git a/changelog.d/fixed-sentinel-pacing-selfreport.md b/changelog.d/fixed-sentinel-pacing-selfreport.md new file mode 100644 index 0000000000..1f3a9c2a04 --- /dev/null +++ b/changelog.d/fixed-sentinel-pacing-selfreport.md @@ -0,0 +1 @@ +- Avoid filing repeated-error fleet reports for sentinel skips caused by GitHub pacing, while retaining the local warnings and reporting other failures. diff --git a/changelog.d/fixed-signoff-rehome-hive-authored.md b/changelog.d/fixed-signoff-rehome-hive-authored.md new file mode 100644 index 0000000000..deff42eba9 --- /dev/null +++ b/changelog.d/fixed-signoff-rehome-hive-authored.md @@ -0,0 +1 @@ +- Hive no longer supersedes its own PRs for a missing sign-off: the automerge DCO stage treats commits on a PR by hive's `ai_author` or App login as self-squash (so an App-signed commit no longer counts as squash-unsafe), `signoff-rehome` keeps hive-authored and operator-approved heads in place instead of re-authoring them as a new PR, the App's signed re-author commit always carries a `Signed-off-by` trailer, and the push relay refuses a hive-identity commit that lacks one. diff --git a/changelog.d/fixed-superseder-signoff-park.md b/changelog.d/fixed-superseder-signoff-park.md new file mode 100644 index 0000000000..90c1ab9a5b --- /dev/null +++ b/changelog.d/fixed-superseder-signoff-park.md @@ -0,0 +1 @@ +- Review aggregation no longer routes a hive-superseding PR to the fixer when every perspective's `requires_human` is a pure approver question with nothing above an informational finding. That route dispatched no-op fix kicks until the cycle was exhausted, then re-authored the same change (#16398 → #16456 → #16607) while the approver the reviewer asked never saw a decision. Such a head keeps its decision question, parks at `stage/085-needs-decision` with approve / request-changes actions, and the tracker's review chevron reads "waiting on a human approver · reviewer verified, needs sign-off". diff --git a/changelog.d/security-16638-workflow-review.md b/changelog.d/security-16638-workflow-review.md new file mode 100644 index 0000000000..7d9fd74cd0 --- /dev/null +++ b/changelog.d/security-16638-workflow-review.md @@ -0,0 +1 @@ +- Require human policy sign-off for reviewer questions on workflow and action edits, including same-repository PRs. diff --git a/src/Dockerfile b/src/Dockerfile index 05b645c17b..48379c25a1 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -319,7 +319,16 @@ RUN timeout 120s npm install -g --ignore-scripts --no-fund --no-audit \ # static list, and non-codex backends are unaffected. ARG CODEX_VERSION=0.166.0 ARG CLINE_VERSION=3.0.74 -RUN npm install -g --ignore-scripts --no-fund --no-audit cline@${CLINE_VERSION} \ +# npm can briefly advertise AWS SDK versions before all registry replicas serve +# them. Wait at most three minutes between attempts and revalidate metadata. +RUN attempt=1; \ + until npm install -g --ignore-scripts --no-fund --no-audit --prefer-online cline@${CLINE_VERSION}; do \ + status=$?; \ + if [ "$attempt" -ge 4 ]; then exit "$status"; fi; \ + echo "Cline install failed (attempt $attempt/4); retrying in 60s" >&2; \ + sleep 60; \ + attempt=$((attempt + 1)); \ + done \ && ln -sf "$(npm root -g)/cline/bin/cline" /usr/local/bin/cline \ && cline --version RUN npm install -g --ignore-scripts --no-fund --no-audit @openai/codex@${CODEX_VERSION} && npm cache clean --force || \ diff --git a/src/Dockerfile.contributor b/src/Dockerfile.contributor index cbf0c3d628..4b98cfff4d 100644 --- a/src/Dockerfile.contributor +++ b/src/Dockerfile.contributor @@ -575,7 +575,16 @@ COPY bin/hive-config.sh /usr/local/bin/ # proactive quota protection with no custom reader and no local hive server. COPY --from=quota-publisher-builder /hive-quota-publisher /usr/local/bin/hive-quota-publisher COPY --from=quota-publisher-builder /crux /usr/local/bin/crux -RUN npm install -g --ignore-scripts --no-fund --no-audit cline@${CLINE_VERSION} \ +# npm can briefly advertise AWS SDK versions before all registry replicas serve +# them. Wait at most three minutes between attempts and revalidate metadata. +RUN attempt=1; \ + until npm install -g --ignore-scripts --no-fund --no-audit --prefer-online cline@${CLINE_VERSION}; do \ + status=$?; \ + if [ "$attempt" -ge 4 ]; then exit "$status"; fi; \ + echo "Cline install failed (attempt $attempt/4); retrying in 60s" >&2; \ + sleep 60; \ + attempt=$((attempt + 1)); \ + done \ && ln -sf "$(npm root -g)/cline/bin/cline" /usr/local/bin/cline \ && cline --version COPY config/backends.conf /usr/local/etc/hive/ diff --git a/src/cmd/crux/main_test.go b/src/cmd/crux/main_test.go index bb7fe83c62..69b61ae46d 100644 --- a/src/cmd/crux/main_test.go +++ b/src/cmd/crux/main_test.go @@ -44,3 +44,21 @@ func TestRunReportsVersion(t *testing.T) { t.Fatalf("code %d, stdout %q", code, stdout.String()) } } + +// A bad OTEL configuration costs telemetry, never the command +// (hivecommons/crux#19): run reports the refusal on stderr and the verb still +// completes with its own exit code. +func TestRunKeepsCommandWhenTelemetryConfigIsBad(t *testing.T) { + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1") + t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc") + var stdout, stderr bytes.Buffer + code := run([]string{"--version"}, strings.NewReader(""), &stdout, &stderr, func() (context.Context, context.CancelFunc) { + return context.WithCancel(context.Background()) + }) + if code != cli.ExitOK || stdout.String() != "crux "+cli.DefaultVersion+"\n" { + t.Fatalf("code %d, stdout %q, stderr %q", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "crux: telemetry disabled:") || !strings.Contains(stderr.String(), "OTEL_EXPORTER_OTLP_PROTOCOL") { + t.Fatalf("stderr = %q, want the telemetry-disabled notice naming the bad variable", stderr.String()) + } +} diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index a79580579e..6fb2b8c5f5 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -146,6 +146,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy AuthorKindLabels: cfg.Governor.Labels.Author.Names(), RelayKnown: contributorRelayKnown, OwnerAuthor: dashboardOwnerLogin(cfg), + HiveAuthor: hiveIdentity(cfg).Matches, SharedCIIncident: stageSharedCIIncident, BaseBranchRed: stageBaseBranchRed, ForkGuard: stageForkGuard, diff --git a/src/crux/cmd/crux/main_test.go b/src/crux/cmd/crux/main_test.go index 709a3ee79b..0ec75b7c97 100644 --- a/src/crux/cmd/crux/main_test.go +++ b/src/crux/cmd/crux/main_test.go @@ -50,6 +50,22 @@ func TestRunReportsVersion(t *testing.T) { } } +// A bad OTEL configuration costs telemetry, never the command +// (hivecommons/crux#19): run reports the refusal on stderr and the verb still +// completes with its own exit code. +func TestRunKeepsCommandWhenTelemetryConfigIsBad(t *testing.T) { + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1") + t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc") + var stdout, stderr bytes.Buffer + code := run([]string{"--version"}, strings.NewReader(""), &stdout, &stderr, testCtx) + if code != cli.ExitOK || stdout.String() != "crux "+cli.DefaultVersion+"\n" { + t.Fatalf("code %d, stdout %q, stderr %q", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "crux: telemetry disabled:") || !strings.Contains(stderr.String(), "OTEL_EXPORTER_OTLP_PROTOCOL") { + t.Fatalf("stderr = %q, want the telemetry-disabled notice naming the bad variable", stderr.String()) + } +} + func TestRunPSFromDefsDirectory(t *testing.T) { dir := t.TempDir() defsDir := filepath.Join(dir, "defs") diff --git a/src/deploy/test_cline_install_retry.py b/src/deploy/test_cline_install_retry.py new file mode 100644 index 0000000000..bb05f66242 --- /dev/null +++ b/src/deploy/test_cline_install_retry.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Exercise the shipped Cline RUN commands without npm, network, or Docker.""" + +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + + +SRC = Path(__file__).resolve().parents[1] +MOCKS = r''' +count=0 +npm() { + if [ "$1" = root ]; then echo /mock/node_modules; return 0; fi + printf 'npm %s\n' "$*" >> "$CALL_LOG" + count=$((count + 1)) + if [ "$count" -le "$FAILURES" ]; then + echo 'npm error code ETARGET: No matching version found' >&2 + return 42 + fi +} +sleep() { echo "sleep $*" >> "$CALL_LOG"; } +ln() { echo "ln $*" >> "$CALL_LOG"; } +cline() { echo "cline $*" >> "$CALL_LOG"; return "$VERSION_STATUS"; } +''' + + +class ClineInstallRetryTest(unittest.TestCase): + def run_install(self, dockerfile, failures, version_status=0): + # Join Docker continuations, then run the actual RUN body under /bin/sh + # just like the images. No copied retry implementation in this test. + text = (SRC / dockerfile).read_text().replace("\\\n", " ") + commands = [ + line.removeprefix("RUN ") + for line in text.splitlines() + if line.startswith("RUN ") + and re.search(r"npm install .*cline@", line) + ] + self.assertEqual(len(commands), 1, dockerfile) + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "calls" + log.touch() + result = subprocess.run( + ["/bin/sh", "-c", MOCKS + commands[0]], + env={**os.environ, "CALL_LOG": str(log), + "FAILURES": str(failures), "CLINE_VERSION": "3.0.74", + "VERSION_STATUS": str(version_status)}, + capture_output=True, text=True, timeout=5, + ) + calls = log.read_text().splitlines() + return result, calls + + def test_install_retry_and_failure(self): + for dockerfile in ("Dockerfile", "Dockerfile.contributor"): + # Includes success on the final allowed attempt and exhaustion. + for failures in (0, 1, 3, 4): + with self.subTest(dockerfile=dockerfile, failures=failures): + result, calls = self.run_install(dockerfile, failures) + self.assertEqual(result.returncode, 42 if failures == 4 else 0, + result.stderr) + installs = [call for call in calls if call.startswith("npm ")] + self.assertEqual(len(installs), min(failures + 1, 4)) + for install in installs: + self.assertEqual(install.split(), [ + "npm", "install", "-g", "--ignore-scripts", "--no-fund", + "--no-audit", "--prefer-online", "cline@3.0.74", + ]) + self.assertEqual(calls.count("sleep 60"), min(failures, 3)) + self.assertEqual([call for call in calls if call.startswith("sleep ")], + ["sleep 60"] * min(failures, 3)) + post_install = [call for call in calls + if call.startswith(("ln ", "cline "))] + self.assertEqual(post_install, [] if failures == 4 else [ + "ln -sf /mock/node_modules/cline/bin/cline /usr/local/bin/cline", + "cline --version", + ]) + + def test_version_failure_is_not_retried_or_masked(self): + for dockerfile in ("Dockerfile", "Dockerfile.contributor"): + with self.subTest(dockerfile=dockerfile): + result, calls = self.run_install(dockerfile, 0, version_status=17) + self.assertEqual(result.returncode, 17, result.stderr) + self.assertEqual(sum(call.startswith("npm ") for call in calls), 1) + self.assertFalse(any(call.startswith("sleep ") for call in calls)) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/deploy/test_supply_chain_pins.sh b/src/deploy/test_supply_chain_pins.sh index 54977b995d..2f4ec322d0 100755 --- a/src/deploy/test_supply_chain_pins.sh +++ b/src/deploy/test_supply_chain_pins.sh @@ -269,6 +269,14 @@ else fi fi +# Execute the real Cline install RUN bodies with mocked npm/links/sleep. This +# keeps the bounded retry covered by the existing supply-chain CI step. +if python3 "$V2_DIR/deploy/test_cline_install_retry.py"; then + pass "Cline installs tolerate transient registry failures and fail closed" +else + fail "Cline install retry behavior" +fi + echo echo "=== $PASS passed, $FAIL failed ===" [ "$FAIL" -eq 0 ] || exit 1 diff --git a/src/docs/acmm-policy-matrix.md b/src/docs/acmm-policy-matrix.md index 0851310179..536a87f4cd 100644 --- a/src/docs/acmm-policy-matrix.md +++ b/src/docs/acmm-policy-matrix.md @@ -16,6 +16,27 @@ issues. The **KB** is the knowledge base of reusable facts; an **RFC** is a request for comments on a proposed design. For a first deployment's trust choices, start with [Securing your hive](securing-your-hive.md). +## Repository E2E detection + +The codebase evaluator's `acmm:prereq-e2e` prerequisite accepts the existing +Playwright/Cypress configuration and E2E directory conventions, as well as +GitHub Actions workflow files named `test*-install*.yml`, `test*-boot*.yml`, +or `*e2e*.yml` (also `.yaml`). These workflow alternatives cover projects +whose end-to-end boundary is installing and booting a system rather than +driving a web browser. + +Workflow patterns use Go `path.Match` semantics on the file basename, only +inside the literal `.github/workflows` directory. They do not recurse, match +directories named like workflow files, or accept an unrelated CI workflow +just because it exists. Detection remains a file-existence heuristic, not +proof that a workflow passes or that its contents implement an E2E test; +maintainers must keep these paths backed by real coverage rather than add +empty directories or dummy workflows to satisfy the criterion. + +An evaluator fix takes effect only after a release containing it is deployed. +After deployment, refresh the ACMM evaluation (subject to its refresh debounce) +before closing an existing false-negative gap issue. + ## Policy Modes The four policy tiers below describe the main autonomy ladder. The roster also diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 5a11d1092c..62f0b3e412 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -5,13 +5,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f `GET /api/stage-tracker` adds independent PR `ci_activity`, `review_activity` and `code_activity` observations, also copied to `linked_prs[]`. Each is -`{head, state, caption, actor?, source, observed_at?, since?, blocker?, url?, active?}`. +`{head, state, caption, detail?, actor?, source, observed_at?, since?, blocker?, url?, active?, checks_passed?, checks_total?, checks_failed?, checks_failing?, checks_pending?, perspectives_done?, perspectives_total?, perspectives?}`. These are display evidence, **not merge authorization**. An absent timestamp means unknown freshness; a different head invalidates the observation. -CI is classified only against the resolved required set from the existing -check snapshot. Review assignment comes from dispatch, current work additionally -requires its actual worker, and approval/findings require verified current-head -review evidence. Authors and claimants are not inferred reviewers. +`detail?` is the longer, plain-language sentence behind caption. `checks_failing?` +and `checks_pending?` are string lists of check names; `perspectives?` list +per-perspective verdicts on the head. CI is classified against the resolved +required set when branch protection is known, otherwise against every check run +observed on the head (checks_total == 0 means no count could be made). Review +assignment comes from dispatch, current work additionally requires its actual +worker, and approval/findings require verified current-head review evidence. +Authors and claimants are not inferred reviewers. `display_column` may be `30` (source repair or explicit owner/adoption wait) or `50` (CI and re-review), without changing native stage identities, counts, filters or routing. Consumers must not turn either display field into a gate. @@ -54,7 +58,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `GET` | `/api/budget-ignore` | Dashboard auth/session | Budget Ignore Get | `pkg/dashboard/api.go:189` | | `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:190` | | `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:202` | -| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Merge queued · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:203` | +| `GET` | `/api/stage-tracker` | Dashboard auth/session | Stage Tracker: every open issue and pull request of the watched repos for the Hive activity monitor — actionable, held, claimed, in-progress, covered-by-PR, filtered (`needs-*`), draft and exempt-labelled items alike, each with `stage`, `stage_since`, `labels`, `created_at`, `author_kind`, `modifiers`, `claimant: {kind: hive-agent|clanker|person, login, agent, hive, since, source: claim-ledger|claim-comment|assignee|kick-history|author}` naming who holds a claimed / in-progress issue or a PR under review or rework (absent when nobody is named; mirrored onto `linked_prs[]`), (PRs) `sentinel_alert` / `sentinel_findings` / `sentinel_reason` when the sentinel flagged the PR, `decision_needed` on a row parked on a person (085 / 045 / 015, the needs-human pill; mirrored onto the issue's `linked_prs[]` entry): `{question, asked_by, since, blocker, blocker_reason, options: [{action, label, enabled, reason_if_disabled}]}` — the reviewer's own decision question when the verdict record has one, the blocker in plain words, and the applicable actions under the row context menu's action ids (`decide:delegate` first), (PRs) `lineage` on the hive's copy of an adopted PR — `{kind: adopted|superseded|rebased-by-hive, from_number, from_url, from_author, from_author_kind, to_number, to_url, at, reason}`, derived from the stage store's adoption record or the `hive/adopt-` head branch, mirrored onto the issue's `linked_prs[]` entry; absent on every other row — and (issues) `linked_prs`; items with no stage yet report stage `0` "Open"; `needs_human_labels` is the "a person must act" label set behind the monitor's Needs human facet (the same list as `/api/status.labelPresets[needs-human]`); `recently_merged` lists the PRs (`repo`, `number`, `merged_at`) whose `pr_merged` audit entry is under 30 minutes old, so a client diffing two payloads can tell a merge from a close; a PR in a conflict-aware merge train carries `merge_train` `{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, length, head_number, head_state, head_reason, head_since, eta_s, eta_at, eta_basis, late, stalled, stalled_s}` — `head_state` one of `needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown` with `head_reason` in plain words; `eta_s` / `eta_at` the estimated wait for this member's own merge attempt (own remaining soak + each PR ahead's remaining soak or one sweep + the next sweep tick; absent while the head waits on a person or CI), `eta_at` anchored to the member's first estimate at its position so a countdown survives polls, `eta_basis` its short reading ("2 ahead · head soaking 12m · next sweep in 40s"), `late` once now has overrun the first estimate twice over, `stalled` / `stalled_s` once the head has sat longer than `governor.merge_train_stall_warn_s` ([#15395](https://github.com/hivecommons/hive/issues/15395)); a PR the queue holds because another open PR declares the same `Fixes #N` carries no `merge_train` and a `merge_gate` of `{state: "duplicate-of:", duplicate_of, duplicate_issue}` plus the `needs-decision` modifier (the queue keeps one PR per issue: green first, then the earlier-opened); a PR GitHub reports conflicting on its own, or one under repair (stage/070, 071, 072, 074, 085, or a red required check), carries no `merge_train` and is not counted in any member's `size` / `length` — a repaired member the view dropped carries `left_train: {why: fixing|needs-author|returned-to-contributor|adopted-by-hive|needs-decision|checks-failing, note}` instead (mirrored onto the issue's `linked_prs[]` entry), and a train left with one member reports no `merge_train` at all; a PR short of the merge queue (below stage/080) the planner ordered rides no train either — it carries `overlap: {behind, with, files, note}` ("overlaps #15637 (sidebar.html, index.html) — will queue behind it") and no `merge_train`, and counts in no member's `size` — the state slugs (`front`, `queued-behind`) are payload values only, the SPA renders ordinal places ("Queued for merge · 1st of 2", with the train's tag when more than one train is on the page). Served from a server-side cache rebuilt at most every `dashboard.stage_tracker.cache_ttl_s` (default `governor.eval_interval_s`) from the spoke's existing snapshot — a request never calls GitHub. Carries `generated_at`, `source` (`cache` or `fresh`), `cache_ttl_s`, an `ETag` and `Cache-Control: private, max-age=`; `If-None-Match` yields 304. Each hit is recorded under REST caller `dashboard:stage-tracker` so `/api/gh-rate-limits` shows it charged nothing. | `pkg/dashboard/api.go:203` | | `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:205` | | `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:391` | | `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:453` | diff --git a/src/docs/dashboard-copy-inventory.md b/src/docs/dashboard-copy-inventory.md index 66ad8b9ebd..b80df3e804 100644 --- a/src/docs/dashboard-copy-inventory.md +++ b/src/docs/dashboard-copy-inventory.md @@ -102,9 +102,9 @@ old name). | Builder | Reaches | Before | After | Held by | |---|---|---|---|---| -| `STAGE_TRACKER_TRAIN_STATE_WORD` (`tracker-words.js`) | chevron label, gate pill | `front` → *Next to merge*, `queued-behind` → *In merge queue* | both *Merge queued*; the place tells them apart | `TestStageTrackerMergeTrainStateSlugsNeverLeak` | -| `stageTrackerTrainWord` | chevron label | *In merge queue · 2 of 6* / *front* (leaked) | *Merge queued · 1st* / *· 2nd* / *· 3rd* … + *· ~4m* countdown | `TestStageTrackerMergeTrainOrdinalWords` | -| `stageTrackerTrainOrdinalOfN` + `stageTrackerTrainTagSuffix` / `stageTrackerTrainTagTip` | chevron label, gate pill, provisional suffix, chevron hover | *Merge queued · 1st* twice over on a page with two trains (owner: "how are there 2 'merge queued 1st'?") | *Merge queued · 1st of 2*; past one train on the page *· train main.go* (overlap basename, else the head `#N`) ends the word and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*; one train → no tag | `TestStageTrackerTrainTagOnTwoTrains` | +| `STAGE_TRACKER_TRAIN_STATE_WORD` (`tracker-words.js`) | chevron label, gate pill | `front` → *Next to merge*, `queued-behind` → *In merge queue* | both *Queued for merge* (was *Merge queued*; one word with 080 and a recorded approval, #16653); the place tells them apart | `TestStageTrackerMergeTrainStateSlugsNeverLeak` | +| `stageTrackerTrainWord` | chevron label | *In merge queue · 2 of 6* / *front* (leaked) | *Queued for merge · 1st* / *· 2nd* / *· 3rd* … + *· ~4m* countdown | `TestStageTrackerMergeTrainOrdinalWords` | +| `stageTrackerTrainOrdinalOfN` + `stageTrackerTrainTagSuffix` / `stageTrackerTrainTagTip` | chevron label, gate pill, provisional suffix, chevron hover | *Merge queued · 1st* twice over on a page with two trains (owner: "how are there 2 'merge queued 1st'?") | *Queued for merge · 1st of 2*; past one train on the page *· train main.go* (overlap basename, else the head `#N`) ends the word and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*; one train → no tag | `TestStageTrackerTrainTagOnTwoTrains` | | `stageTrackerUnderRepair` → `stageTrackerAnchor` (Go: `stageTrackerTrainUnderRepair` → `stageTrackerItemColumn`) | chevron column | *Fixing · @hivecommons-hive[bot]* lit in the **Merge queue** column over the caption *fell back to Fixing — … — conflicting* (hive's own #15574: the refused merge's `merge-failed` gate still promoted the column) | the column follows the current state: under repair → CI / Review, whatever the stale gate or planner train says; the caption keeps the history | `TestStageTrackerItemColumnRatchet`, `TestStageTrackerFixingAfterMergeFailedColumn`, `stage_tracker_fixing_column.test.js` | | `stageTrackerLeftTrainNote` + `STAGE_TRACKER_LEFT_TRAIN_NOTE` (Go: `stageTrackerLeftTrainNote`, `left_train`) | row hover | *merge train · 2 PRs · 1st: #15405* over a row whose chevron read *Fixing* (hive's own #15405, a maintainer requested changes) | the fixing row rides no train (no header, no ordinal, no rail); its hover ends *Merge train: left the merge train while being fixed; rejoins when green*; a train of one is no train | `TestStageTrackerTrainTagOnTwoTrains`, `TestStageTrackerMergeTrainUnderRepairLeaves` | | `stageTrackerOrdinal` | chevron, hover, popover | — | `1st 2nd 3rd 4th … 11th 12th 13th 21st 22nd 23rd` | same | diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 44470479eb..4df187d2d1 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -87,7 +87,7 @@ At 090 the row explains why: `· workflow files`, `· tests removed`, `· manual A verified merge from the canonical merge ledger is terminal whether Hive, a maintainer or another bot performed it. The last known root or linked PR model reaches **Merged** during the existing short terminal/pin window, even without an earlier queue observation. The comment names the actual recorded merger; an unknown actor stays unknown. This does not invent an earlier queue/admission state or close a merely related issue. A stale open refresh cannot undo a verified merge, and repeated delivery or later actor enrichment does not replay the merge or restart its window. Terminal visibility does not re-enable closed-PR actions. -A failing external PR without a recorded Hive stage actor remains **CI failing · author-owned** when its PR author is known, **CI failing · owner recorded** for an observed claimant, or **CI failing · owner unknown** otherwise. Its work activity is unknown; missing internal worker evidence is not evidence that nobody is working. Inline and nested rows use the PR author or claimant, not the related issue's filer or holder. Explicit unclaimed Hive/bot routing and real CI failures remain unchanged. +A failing external PR without a recorded Hive stage actor remains **Fix owed · author-owned** when its PR author is known, **Fix owed · owner recorded** for an observed claimant, or **Fix owed · owner unknown** otherwise (the red verdict itself is the CI chevron's word, never this lane's). Its work activity is unknown; missing internal worker evidence is not evidence that nobody is working. Inline and nested rows use the PR author or claimant, not the related issue's filer or holder. Explicit unclaimed Hive/bot routing and real CI failures remain unchanged. - With no covering PR, an issue has a full strip lit at Open, Actionable or Claimed. - With exactly one covering PR, issue and PR share one continuous strip; early issue steps are passed and the PR supplies the current stage, chip, tooltip and age. @@ -265,7 +265,7 @@ nested PR spacing. An unrelated row or child ends the rail rather than acquiring misleading membership. A missing, closed or stale front is never synthesized as a verified owner; recorded/unverified metadata remains explicit. -When several approved PRs to the same base touch the same files, the automerge lanes merge them one at a time ([#15117](https://github.com/hivecommons/hive/issues/15117)). The tracker renders every train contiguously, in merge order, with a thin left rail linking the rows and a header chip `🚆 merge train · 4 PRs · 1st: #15074` — the glyph is an inline-SVG railcar (14px, currentColor, hover *Merge queue*), the same icon the **Merge queue** column header and its chevrons wear; overlapping files are listed beside it. Pill wording per state is the PR's place in the queue (the owner's words — `front` and `queued-behind` appear nowhere a person reads): the head reads "Merge queued · 1st of 4 · ~13m" (its own soak left plus the next pass); the others "Merge queued · 2nd of 4 · ~4m", "Merge queued · 3rd of 4", … (`1st 2nd 3rd 4th … 11th 12th 13th 21st`, always with the queue length, countdown to its turn); when the page draws more than one train each queue word ends with its train's tag — "Merge queued · 1st of 2 · train main.go" (the first overlapping file's basename, else the head `#N`) — and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*, so two "1st"s on one page tell apart (one train → no tag); the header and every member row of a train share one rail accent (`.ham-train-k0…k3`, cycling in page order); once the front merged and the hive is rebasing a conflicting sibling, "Rebasing · attempt 1/2"; when the loop guard (`auto_merge.merge_train.max_rebase_attempts`) is spent, "Needs human decision · rebase failed twice" at stage/085 with the decision option "Rebase, then merge as maintainer". +When several approved PRs to the same base touch the same files, the automerge lanes merge them one at a time ([#15117](https://github.com/hivecommons/hive/issues/15117)). The tracker renders every train contiguously, in merge order, with a thin left rail linking the rows and a header chip `🚆 merge train · 4 PRs · 1st: #15074` — the glyph is an inline-SVG railcar (14px, currentColor, hover *Merge queue*), the same icon the **Merge queue** column header and its chevrons wear; overlapping files are listed beside it. Pill wording per state is the PR's place in the queue (the owner's words — `front` and `queued-behind` appear nowhere a person reads): the head reads "Queued for merge · 1st of 4 · ~13m" (its own soak left plus the next pass); the others "Queued for merge · 2nd of 4 · ~4m", "Queued for merge · 3rd of 4", … (`1st 2nd 3rd 4th … 11th 12th 13th 21st`, always with the queue length, countdown to its turn); when the page draws more than one train each queue word ends with its train's tag — "Queued for merge · 1st of 2 · train main.go" (the first overlapping file's basename, else the head `#N`) — and the hover leads *Train of 2 PRs overlapping main.go; merges after #15567.*, so two "1st"s on one page tell apart (one train → no tag); the header and every member row of a train share one rail accent (`.ham-train-k0…k3`, cycling in page order); once the front merged and the hive is rebasing a conflicting sibling, "Rebasing · attempt 1/2"; when the loop guard (`auto_merge.merge_train.max_rebase_attempts`) is spent, "Needs human decision · rebase failed twice" at stage/085 with the decision option "Rebase, then merge as maintainer". The tooltip lists the PRs ahead and the overlapping files. Waiting siblings are never red, never `needs human`; a `needs-rebase` label on one is reported under `stale_labels`, the train repairs it. Each item carries `merge_gate.state` (`queued-behind` / `rebasing` / `rebase-exhausted` / `front`, with an honest `reason` such as `behind #15074 in merge train (3rd of 4, overlapping files: stage_tracker.go, index.html)`) and `merge_train{id, state, front, position, size, attempt, max_attempts, overlap_files, ahead, members}`; the id is `#` and `members` is the whole roster in merge order. @@ -277,7 +277,7 @@ The tooltip lists the PRs ahead and the overlapping files. Waiting siblings are **The train starts at 080.** The merge train is a merge-queue concept: only PRs at 080 and beyond — green, approved, soaking or merging — ride one, and the header counts only them. A PR the planner has ordered while it is still at CI / Review (050 / 060) rides no train (`stageTrackerBelowMergeQueue`): hive's own page once led `merge train · 2 PRs · 1st: #15637 — overlapping: sidebar.html, index.html` over #15637 and #15633 while both chevrons read *CI / Review*. Such a row carries `overlap: {behind, with, files, note}` instead of `merge_train` — no rail, no ordinal, no header — and shows one muted badge **overlaps #15637** whose hover is the note, *Not in the merge queue yet: overlaps #15637 (sidebar.html, index.html) — will queue behind it* (the planner's own front reads *overlaps #15633 (…) — merges ahead of it once both are ready*). The members that do ride close ranks around it, and a train left with one 080 member is no train. -**Queue position, countdown, stall** ([#15395](https://github.com/hivecommons/hive/issues/15395)). The queued chip is its place in the queue and nothing else — **Merge queued · 2nd of 6 · ~4m** — so it reads the same whether or not a merge sweep is evaluating it: the sweep is the spinning ⬡ glyph and a *Checking now…* line in the hover, never a change of words (one label per chevron), and no state slug (`queued-behind`, `front`) ever reaches the page. The hover is the place sentence — *2nd of 6 in the merge queue · behind #15253 (soaking, 12m left) · ETA ~25m (2 ahead · head soaking 12m · next pass in 40s). Hive merges one at a time, in order.*; the head's reads *1st of 6 in the merge queue · merges next · ETA ~13m.* — or, when the head is on a person or on CI, the blocker instead of a clock: *… behind #15253 (waiting for a maintainer (untrusted author)) · no estimate until #15253 moves.* Every train state — the 1st included — lights the **Merge queue** column, whatever numeric stage the lane holds the head at (the train's facts are mirrored onto a head still at 050/060; hive's own #15400 once lit CI / Review beside its 2nd-place sibling) — a head under repair is no member (below) and lights CI / Review. The server adds to each member's `merge_train`: `length`, `head_number`, `head_state` (`needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown`), `head_reason` (plain words), `head_since`, `eta_s`, `eta_at`, `eta_basis`, `late`, `stalled`, `stalled_s`. +**Queue position, countdown, stall** ([#15395](https://github.com/hivecommons/hive/issues/15395)). The queued chip is its place in the queue and nothing else — **Queued for merge · 2nd of 6 · ~4m** — so it reads the same whether or not a merge sweep is evaluating it: the sweep is the spinning ⬡ glyph and a *Checking now…* line in the hover, never a change of words (one label per chevron), and no state slug (`queued-behind`, `front`) ever reaches the page. The hover is the place sentence — *2nd of 6 in the merge queue · behind #15253 (soaking, 12m left) · ETA ~25m (2 ahead · head soaking 12m · next pass in 40s). Hive merges one at a time, in order.*; the head's reads *1st of 6 in the merge queue · merges next · ETA ~13m.* — or, when the head is on a person or on CI, the blocker instead of a clock: *… behind #15253 (waiting for a maintainer (untrusted author)) · no estimate until #15253 moves.* Every train state — the 1st included — lights the **Merge queue** column, whatever numeric stage the lane holds the head at (the train's facts are mirrored onto a head still at 050/060; hive's own #15400 once lit CI / Review beside its 2nd-place sibling) — a head under repair is no member (below) and lights CI / Review. The server adds to each member's `merge_train`: `length`, `head_number`, `head_state` (`needs-human` / `ci` / `soaking` / `ready` / `merging` / `fixing` / `unknown`), `head_reason` (plain words), `head_since`, `eta_s`, `eta_at`, `eta_basis`, `late`, `stalled`, `stalled_s`. **One PR per issue** ([#15395](https://github.com/hivecommons/hive/issues/15395)). Two open PRs declaring the same `Fixes #N` never both ride the queue (hive's own #15402 and #15407, both for #15396, once sat side by side as "waiting its turn"). Before the trains are grouped the sweep keeps one PR per closing issue — a green head (not conflicting, not blocked on a red required check) beats a red one; among equals the earlier-opened wins — and holds the other out of every train with the stage reason `merge-train:duplicate-of#:/0:0/0:`. The held row's gate reads `duplicate-of:` (`merge_gate.duplicate_of`, `merge_gate.duplicate_issue`), its chip **Duplicate of #15402 · needs a pick** with no clock, it carries no `merge_train`, and it wears `needs-decision` so both PRs sit under their issue with the hold visible. *Let hive decide* on either row takes the existing supersede path (rule `one-pr-per-issue`): on the held PR it closes it as superseded by the kept one with a credit comment, through the same write gate as every delegate close; on the kept PR it releases it and names the duplicate the queue holds (or, if the kept PR has since gone red, only recommends the fix — the queue re-picks on its next pass, so an earlier red PR yields to a later green one). @@ -334,7 +334,7 @@ An adopted pull request names the hive's superseding copy in its detour word (`a If two copies are closed within an hour the hive stops (`adopted_by_state: "closed-twice"`, park reason `adoption-child-closed-twice`): the row reads "Adopted → #N (closed twice) · needs a person" and the popover question asks you to reopen the last copy, give direction, or close the PR. With close-first supersession (the default, hivecommons/hive#15135) the original is closed in the adopting pass and has **no row** while its copy is open — the copy is the one active PR for the issue, and the original's record is superseded (no chevron, no *Needs human decision*). -A superseded original keeps a muted, chevron-less sub-row under the issue while its superseder is open and listed (hivecommons/hive#15511 showed hive's #15574 *Merge queued* and, beneath it, the still-open #15526 as a greyed line whose note "· Adopted → #15574 · superseded (hive re-authored with sign-off)" wrapped to two lines). The note now reads **"superseded · hive adopted → #M"**, or **"superseded · closed · hive adopted → #M"** once the original is closed, and never wraps — the PR title ellipsizes first; the hover carries the long form ("Hive re-authored this PR as #M with the same commits and sign-off. This PR closes as superseded when #M merges." / "…This PR is closed as superseded."). The tracker sets `superseded_by: M` on the original (omitted for an in-place adoption, cleared when the copy is closed / closed-twice / copy-failed so the original counts again) and `adopted_from.state` / `lineage.from_state` on the copy (`"open"` or `"closed"`). A closed original is listed in this muted form only while #M is open and listed; it leaves the tracker once #M merges or closes. Agent-authored originals close in the adopting pass by policy (`governor.labels.stage.adoption.close_superseded`, default `on_adopt`); a person's PR closes then only with the write-back opt-in label, else when the copy merges — see [hive-merge.md](../hive-merge.md). +A superseded original keeps a muted, chevron-less sub-row under the issue while its superseder is open and listed (hivecommons/hive#15511 showed hive's #15574 *Queued for merge* and, beneath it, the still-open #15526 as a greyed line whose note "· Adopted → #15574 · superseded (hive re-authored with sign-off)" wrapped to two lines). The note now reads **"superseded · hive adopted → #M"**, or **"superseded · closed · hive adopted → #M"** once the original is closed, and never wraps — the PR title ellipsizes first; the hover carries the long form ("Hive re-authored this PR as #M with the same commits and sign-off. This PR closes as superseded when #M merges." / "…This PR is closed as superseded."). The tracker sets `superseded_by: M` on the original (omitted for an in-place adoption, cleared when the copy is closed / closed-twice / copy-failed so the original counts again) and `adopted_from.state` / `lineage.from_state` on the copy (`"open"` or `"closed"`). A closed original is listed in this muted form only while #M is open and listed; it leaves the tracker once #M merges or closes. Agent-authored originals close in the adopting pass by policy (`governor.labels.stage.adoption.close_superseded`, default `on_adopt`); a person's PR closes then only with the write-back opt-in label, else when the copy merges — see [hive-merge.md](../hive-merge.md). A copy that then fails (closed unmerged, or red at two heads) reopens the original: `adopted_by_state: "copy-failed"` renders "Adopted → #N (copy failed) · reopened, needs a person" at 085 with the caption "The hive's copy #N failed; this PR was reopened and needs a person". @@ -436,6 +436,16 @@ The *state pill* says where the item is and what it is waiting on (`hold`, `need Plain words throughout — working / waiting on X / set back by Y / merged — nothing else blinks. +#### Chevron activation — the canonical rules + +An *active* chevron is filled amber and carries words; an inactive one is its icon alone (CI / Review: the ring, green when the last run on this head passed, red when it failed, neutral when not yet run), with the counts in its tooltip. On every strip: + +1. **1 ≤ active ≤ 2.** At least one chevron is active — the column where the item is or where it is stuck. +2. **CI and Review resolve first.** A track is active only while it genuinely runs on the current head (a check-run in progress or queued, a ring not yet full; a reviewer running or queued). If either runs, the PR is waiting on it: the stage chevron (PR in progress, Merge queue …) renders settled-current — filled but still, icon only, its words in the tooltip — and nothing else is active. +3. **CI + Review is the only pair.** Two chevrons are active together only when both tracks run at once; every other combination is exactly one active chevron. The stage chevron is the ≥ 1 fallback: active only when no track is in motion. +4. **The PR in progress chevron speaks the PR's lifecycle** — draft, pushed, rebasing, *Unassigned · next: scanner*, *Waiting for @author · fix owed* — never a CI or review verdict. *CI failing*, *CI 4/11 · 1 failing* and *changes requested* are the CI and Review chevrons' words; the PR in progress tooltip keeps the red reason as detail. +5. **The CI and Review tooltips state what the track waits on — never "activity unknown".** With no verdict and no reviewer in flight the spoke derives the Review statement from what it already knows, in this order: the PR is merged or closed (*Review · n/a (closed)*), it is a draft (*Review · draft, not requested*), CI on the head has not finished (*Review · waiting for CI*), CI is done and nobody started (*Review · not started · hive reviewer next*, or *· needs reviewer* when the repo has no hive reviewer lane). A settled verdict explains itself — *Changes requested by the hive reviewer: 1 perspective posted findings … · 12m ago · quality ✓ · security ✗: token logged* — and stays known as its observation ages. The one no-data wording, *Review · no data for head f269349 yet · refreshing* (CI: *CI · no checks observed for head … yet · refreshing*), appears only when the spoke has fetched nothing for the head, and names the next step. + #### The row's lead action, inline A row whose next move is yours does not hide its answer behind three dots. Beside the chips on the right of the header (and on a nested PR sub-row's own header), the row renders its **lead action** as a real `', stageTrackerTooltip: () => 'tooltip', - stageTrackerPRPillsHtml: ref => `${ref}base v5`, + stageTrackerPRPillsHtml: ref => `${ref}`, stageTrackerActedBadgeHtml: () => '', stageTrackerChipsHtml: () => chips, stageTrackerMoveAttrs: () => '', @@ -42,7 +42,7 @@ function load() { vm.runInContext(pick(new RegExp('const ' + name + ' = [^\\n]*'), name), ctx); } for (const name of ['stageTrackerHeadColsHtml', 'stageTrackerHeaderHtml', 'stageTrackerRowHtml', 'stageTrackerSubRowHtml', - 'stageTrackerPRRef', 'stageTrackerPRIssueSlot', 'stageTrackerTitleHtml', 'stageTrackerSplitTitleTag']) { + 'stageTrackerPRRef', 'stageTrackerPRIssueSlot', 'stageTrackerTitleHtml', 'stageTrackerSplitTitleTag', 'stageTrackerBasePillHtml']) { vm.runInContext(fn(name), ctx); } return ctx; diff --git a/src/pkg/dashboard/stage_tracker_human_attention.test.js b/src/pkg/dashboard/stage_tracker_human_attention.test.js index 31a3812cf3..14808199cd 100644 --- a/src/pkg/dashboard/stage_tracker_human_attention.test.js +++ b/src/pkg/dashboard/stage_tracker_human_attention.test.js @@ -38,7 +38,7 @@ function load() { }); 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); + for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml', 'stageTrackerBasePillHtml']) 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-human-attention'), c); diff --git a/src/pkg/dashboard/stage_tracker_human_attention_test.go b/src/pkg/dashboard/stage_tracker_human_attention_test.go index 3eb6051ebd..0e8673ed55 100644 --- a/src/pkg/dashboard/stage_tracker_human_attention_test.go +++ b/src/pkg/dashboard/stage_tracker_human_attention_test.go @@ -68,7 +68,7 @@ func TestStageTrackerOperatorApprovalDoesNotHideCurrentReviewChanges(t *testing. if d == nil || d.Effect != decidedEffectNone || d.Stage != 0 || d.CurrentBlocker == "" || d.Head != it.Head { t.Fatalf("approval wrongly outranked current review: %+v", d) } - if strings.Contains(d.Text, "merge queue takes it") || !strings.Contains(d.Text, "waiting on @thatguywob") { + if strings.Contains(d.Text, "Queued for merge") || !strings.Contains(d.Text, "waiting on @thatguywob") { t.Fatalf("wrong precedence/explanation: %+v", d) } beforeStage, beforeReason := it.Stage, it.Reason diff --git a/src/pkg/dashboard/stage_tracker_merge_banner_countdown.test.js b/src/pkg/dashboard/stage_tracker_merge_banner_countdown.test.js index 5658259db6..1106c04d96 100644 --- a/src/pkg/dashboard/stage_tracker_merge_banner_countdown.test.js +++ b/src/pkg/dashboard/stage_tracker_merge_banner_countdown.test.js @@ -74,15 +74,17 @@ const src = [ pick(/function stageTrackerIsPrimary\(repo, primary\) \{[\s\S]*?\n \}\n/, 'stageTrackerIsPrimary'), pick(/function stageTrackerRepoChipHtml\(repo, ctx\) \{[\s\S]*?\n \}\n/, 'stageTrackerRepoChipHtml'), pick(/function stageTrackerPrimaryRepo\(\) \{[^\n]*\n/, 'stageTrackerPrimaryRepo'), + pick(/function stageTrackerMergerText\(by\) \{[\s\S]*?\n \}\n/, 'stageTrackerMergerText'), + pick(/function stageTrackerMergedByOf\(key, d\) \{[\s\S]*?\n \}\n/, 'stageTrackerMergedByOf'), pick(/function stageTrackerMergeBannerText\(b, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerMergeBannerText'), pick(/function stageTrackerMergeBanner\(b\) \{[\s\S]*?\n \}\n/, 'stageTrackerMergeBanner'), pick(/function stageTrackerMergeBannerDismiss\(el\) \{[\s\S]*?\n \}\n/, 'stageTrackerMergeBannerDismiss'), pick(/function hamBannerDismiss\(btn\) \{[\s\S]*?\n \}\n/, 'hamBannerDismiss'), ].join('\n'); -function load() { +function load(tracker) { const dom = makeDom(); - const api = new Function('document', 'setTimeout', 'clearTimeout', src + '; return { banner: stageTrackerMergeBanner, dismiss: stageTrackerMergeBannerDismiss, hamBannerDismiss, merged: _stageTrackerMerged, filter: _stageTrackerFilter, chip: stageTrackerRepoChipHtml };')(dom.document, dom.setTimeout, dom.clearTimeout); + const api = new Function('document', 'setTimeout', 'clearTimeout', '_stageTracker', src + '; return { banner: stageTrackerMergeBanner, dismiss: stageTrackerMergeBannerDismiss, hamBannerDismiss, merged: _stageTrackerMerged, filter: _stageTrackerFilter, chip: stageTrackerRepoChipHtml, mergerText: stageTrackerMergerText, mergedByOf: stageTrackerMergedByOf, bannerText: stageTrackerMergeBannerText };')(dom.document, dom.setTimeout, dom.clearTimeout, tracker || null); return Object.assign(dom, api); } @@ -198,3 +200,44 @@ test('merge repo chips use the existing escaping and preview behavior', () => { assert.ok(!el.innerHTML.includes('Open on GitHub'), 'preview does not invent a GitHub URL'); assert.ok(el.innerHTML.includes('(test)')); }); + +// hivecommons/hive#16658: a PR merged by anyone celebrates, and the head +// names the merger — "merged by @login" for a human, "merged by 🐝 hive" +// for the hive's own merge — so an external merge reads like the hive's. +test('#16658: merger text names a human by @login and the hive by 🐝', () => { + const d = load(); + assert.strictEqual(d.mergerText('clubanderson'), '@clubanderson'); + assert.strictEqual(d.mergerText('hive'), '🐝 hive'); + assert.strictEqual(d.mergerText(''), ''); + assert.strictEqual(d.mergerText(undefined), ''); + assert.strictEqual(d.mergerText(' '), ''); +}); + +test('#16658: banner head reads "#N merged by " and falls back to plain "merged" when unknown', () => { + const d = load(); + const at = Date.now(); + const human = d.bannerText({ key: 'hivecommons/hive/pr#16644', repo: 'hivecommons/hive', number: 16644, merged_by: 'clubanderson', at }, at); + assert.strictEqual(human.head, '#16644 merged by @clubanderson'); + assert.strictEqual(human.merger, '@clubanderson'); + const hive = d.bannerText({ key: 'hivecommons/hive/pr#16645', repo: 'hivecommons/hive', number: 16645, merged_by: 'hive', at }, at); + assert.strictEqual(hive.head, '#16645 merged by 🐝 hive'); + const unknown = d.bannerText({ key: 'hivecommons/hive/pr#1', repo: 'hivecommons/hive', number: 1, at }, at); + assert.strictEqual(unknown.head, '#1 merged'); + assert.strictEqual(unknown.merger, ''); + const preview = d.bannerText({ key: 'hivecommons/hive/pr#2', repo: 'hivecommons/hive', number: 2, merged_by: 'hive', preview: true, at }, at); + assert.strictEqual(preview.head, '#2 merged by 🐝 hive (test)'); +}); + +test('#16658: mergedByOf resolves the merger from recently_merged, then the ledger, then the held terminal fact', () => { + const tracker = { + recently_merged: [{ repo: 'hivecommons/hive', number: 16644, merged_by: 'clubanderson' }], + merged: { recent: [{ repo: 'hive', number: 16645, merged_by: 'hive' }, { repo: 'acme/other', number: 16644, merged_by: 'someone-else' }] }, + }; + const d = load(tracker); + assert.strictEqual(d.mergedByOf('hivecommons/hive/pr#16644', tracker), 'clubanderson', 'audit/ledger union wins, repo-scoped'); + assert.strictEqual(d.mergedByOf('hivecommons/hive/pr#16645', tracker), 'hive', 'short repo name in the ledger matches the key'); + assert.strictEqual(d.mergedByOf('acme/other/pr#16644', tracker), 'someone-else', 'colliding numbers stay repo-scoped'); + assert.strictEqual(d.mergedByOf('hivecommons/hive/pr#9999', tracker), '', 'unknown PR is empty, never a guess'); + assert.strictEqual(d.mergedByOf('', tracker), ''); + assert.strictEqual(d.mergedByOf('hivecommons/hive/pr#16644', null), '', 'no payload, no held fact → empty'); +}); diff --git a/src/pkg/dashboard/stage_tracker_merge_failed_column_test.go b/src/pkg/dashboard/stage_tracker_merge_failed_column_test.go index 54a28f6ae2..864ee28197 100644 --- a/src/pkg/dashboard/stage_tracker_merge_failed_column_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_failed_column_test.go @@ -13,7 +13,7 @@ import ( // "PUT https://api.github.com/…" error spilling out of it. An actual queue // outcome lights the Merge gate; a premature call waiting for head checks // does not admit a 050/060 PR. The chip is a fixed short phrase -// (no URL, no verb, ≤ 5 words) with GitHub's words in the tooltip's +// (no URL, no verb, ≤ 6 words) with GitHub's words in the tooltip's // Details line; pending CI is "CI running", never "red"; and the cue // names the stage in plain words, not "stage/060-reviewed". func TestStageTrackerMergeFailedColumnNode(t *testing.T) { @@ -83,26 +83,27 @@ assert.strictEqual(stageTrackerAnchor(50, stages, 'pr', prepared), 50, 'preparat assert.strictEqual(stageTrackerAnchor(100, stages, 'pr', prepared), STAGE_TRACKER_MERGE_COLUMN, 'an actual queue-stage outcome stays at the gate'); // 2. The chip for this exact payload (Go translated the 405): the sweep -// called too early, so it is "Waiting for CI · 4 checks", not a failure. +// called too early, so it is "Queued for merge · after CI", not a failure. let info = stageTrackerMergeGateInfo(row(gate({ merge_failed_kind: 'checks-pending', merge_failed_text: "4 required checks haven't finished", merge_failed_checks: 4 })), now); -assert.strictEqual(info.word, 'Waiting for CI'); -assert.strictEqual(info.detail, '4 checks'); +assert.strictEqual(info.word, 'Queued for merge'); +assert.strictEqual(info.detail, 'after CI', 'the check count rides the hover, not the chip'); assert.strictEqual(info.cue, 'running', 'the sweep is on it'); assert.ok(info.tip.includes("before its required checks had reported — 4 required checks haven't finished"), info.tip); assert.ok(info.tip.includes('Details: ' + raw), 'raw error only after Details: ' + info.tip); assert.ok(!info.tip.startsWith('stage/'), info.tip); // Older payload without the translated fields: the SPA classifies the raw text itself. info = stageTrackerMergeGateInfo(row(gate()), now); -assert.strictEqual(info.word + ' · ' + info.detail, 'Waiting for CI · 4 checks', 'raw-only payload'); +assert.strictEqual(info.word + ' · ' + info.detail, 'Queued for merge · after CI', 'raw-only payload'); assert.ok(info.tip.includes("4 required checks haven't finished"), info.tip); -// 3. Every merge-failed chip is a fixed short phrase: no URL, no verb, ≤ 5 words. +// 3. Every merge-failed chip is a fixed short phrase: no URL, no verb, ≤ 6 words +// (the three-word queue word plus a qualifier of at most three, #16653). const cases = [ - [gate(), 'Waiting for CI · 4 checks'], - [gate({ sweep_running: false }), 'Waiting for CI · 4 checks'], + [gate(), 'Queued for merge · after CI'], + [gate({ sweep_running: false }), 'Queued for merge · after CI'], [gate({ merge_failed: '405 Pull Request is not mergeable' }), 'Merge failed · retrying'], - [gate({ merge_failed: '405 Pull Request is not mergeable', sweep_running: false }), 'Merge failed · branch protection'], - [gate({ merge_failed: '409 Head branch was modified. Review and try the merge again.', sweep_running: false }), 'Merge failed · needs rebase'], + [gate({ merge_failed: '405 Pull Request is not mergeable', sweep_running: false }), 'Queued for merge · branch protection pending'], + [gate({ merge_failed: '409 Head branch was modified. Review and try the merge again.', sweep_running: false }), 'Queued for merge · needs rebase'], [gate({ merge_failed: '403 Resource not accessible by integration', sweep_running: false }), 'Merge failed · not allowed'], [gate({ merge_failed: 'context deadline exceeded', sweep_running: false }), 'Merge failed · GitHub refused'], [gate({ merge_failed: 'context deadline exceeded', merge_failed_kind: 'refused', merge_failed_text: 'GitHub refused the merge', sweep_running: false }), 'Merge failed · GitHub refused'], @@ -114,7 +115,7 @@ for (const [mg, want] of cases) { const label = i.word + (i.detail ? ' · ' + i.detail : ''); assert.strictEqual(label, want); assert.ok(plain(label), 'no raw error in the chip: ' + label); - assert.ok(words(label).length <= 5, 'chip ≤ 5 words: ' + label); + assert.ok(words(label).length <= 6, 'chip ≤ 6 words: ' + label); const html = stageTrackerMergeGateWordHtml(row(mg), now); assert.ok(html.includes('') && plain(html), html); if (mg.merge_failed) assert.ok(i.tip.includes('Details: ' + mg.merge_failed), 'raw text rides the tooltip: ' + i.tip); diff --git a/src/pkg/dashboard/stage_tracker_merge_failed_stale_test.go b/src/pkg/dashboard/stage_tracker_merge_failed_stale_test.go index fdfe9fc14c..bfa66fe76b 100644 --- a/src/pkg/dashboard/stage_tracker_merge_failed_stale_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_failed_stale_test.go @@ -130,6 +130,6 @@ assert.strictEqual(stageTrackerPriorHeadMergeFailedNote({}), ''); // A live refusal on the current head still reads "Merge failed". const liveInfo = stageTrackerMergeGateInfo(row({ state: 'merge-failed', merge_failed: raw, merge_failed_kind: 'protection', merge_failed_text: 'branch protection blocks it', merge_failed_at: new Date(now - 9000).toISOString(), sweep_running: false }), now); -assert.strictEqual(liveInfo.word + ' · ' + liveInfo.detail, 'Merge failed · branch protection'); +assert.strictEqual(liveInfo.word + ' · ' + liveInfo.detail, 'Queued for merge · branch protection pending'); `) } diff --git a/src/pkg/dashboard/stage_tracker_merge_gate_test.go b/src/pkg/dashboard/stage_tracker_merge_gate_test.go index 6f84e6be6f..34ffd69bf8 100644 --- a/src/pkg/dashboard/stage_tracker_merge_gate_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_gate_test.go @@ -145,8 +145,8 @@ func TestStageTrackerMergeGateInPayload(t *testing.T) { func TestStageTrackerMergeGateNode(t *testing.T) { html := indexHTML(t) for _, want := range []string{ - `const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Ready for auto merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' };`, - `60: 'Review passed', 80: 'Ready for auto merge', 95: 'Soaking', 100: 'Merging'`, + `const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Queued for merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' };`, + `60: 'Review passed', 80: 'Queued for merge', 95: 'Soaking', 100: 'Merging'`, `const gateCue = gateWord && typeof stageTrackerGateCueHtml === 'function' ? stageTrackerGateCueHtml(item, nowMs, trains) : '';`, `const caption = gateWord || word;`, `const text = decision ? stageTrackerDecisionTriggerHtml(decision, caption, fullTip) : caption;`, @@ -164,7 +164,7 @@ func TestStageTrackerMergeGateNode(t *testing.T) { if err != nil { t.Fatal(err) } - for _, want := range []string{"**Merge queue pills — legend**", "Awaiting merge gate", "Ready for auto merge", "**Soaking**", "**Merging**", "next pass in"} { + for _, want := range []string{"**Merge queue pills — legend**", "Awaiting merge gate", "Queued for merge", "**Soaking**", "**Merging**", "next pass in"} { if !strings.Contains(string(docs), want) { t.Errorf("docs/dashboard-sections/activity-monitor.md missing merge-gate legend %q", want) } @@ -205,7 +205,7 @@ const pr15044 = { repo: 'hivecommons/hive', number: 15044, kind: 'pr', base_ref: const ready = { repo: 'hivecommons/hive', number: 15060, kind: 'pr', stage: 80, merge_gate: { state: 'ready', last_sweep_at: iso(now - 10000), next_sweep_at: iso(now + 42000) } }; const merging = { repo: 'hivecommons/hive', number: 15061, kind: 'pr', stage: 100, merge_gate: { state: 'merging', last_sweep_at: iso(now - 1000) } }; -// Both 060 rows read the same word — neither is "Ready for auto merge" with CI pending. +// Both 060 rows read the same word — neither is "Queued for merge" with CI pending. let a = stageTrackerMergeGateInfo(pr15042, now), b = stageTrackerMergeGateInfo(pr15054, now); assert.strictEqual(a.word, 'Review passed'); assert.strictEqual(b.word, 'Review passed'); assert.strictEqual(a.cue, 'running'); assert.strictEqual(a.detail, 'CI in progress'); @@ -226,7 +226,7 @@ assert.strictEqual(stageTrackerGateCueHtml({ repo: 'r', number: 1, kind: 'pr', s assert.strictEqual(stageTrackerGateCueHtml({ repo: 'r', number: 1, kind: 'pr', stage: STAGE_TRACKER_TERMINAL }, now), '', 'merged: no glyph'); // The pill word with the live detail; the waiting row says what it waits for. -assert.strictEqual(stageTrackerMergeGateWordHtml(ready, now), 'Ready for auto merge · next pass in 42s'); +assert.strictEqual(stageTrackerMergeGateWordHtml(ready, now), 'Queued for merge · next pass in 42s'); // The soak detail carries its clock (data-ham-soak…) so the tick redoes the words and the hover. const soakHtml = stageTrackerMergeGateWordHtml(pr15044, now); assert.ok(soakHtml.startsWith('Soaking /^Merge queue/.test(String(s || '')) ? 'queue' : 'stage'; +const classOf = s => /^(Queued for merge|Merge queue)/.test(String(s || '')) ? 'queue' : 'stage'; for (const stage of stages) for (const state of ['front', 'queued-behind']) for (const flag of [true, false, undefined]) { const pos = state === 'front' ? 1 : 2; const mt = { id: 'v5#15577', state, front: 15577, head_number: 15577, position: pos, size: 2, length: 2, head_state: stage < 80 ? 'ci' : 'ready', head_reason: stage < 80 ? 'waiting for CI' : '' }; @@ -61,7 +61,7 @@ for (const stage of stages) for (const state of ['front', 'queued-behind']) for assert.ok(!/merges next/.test(info.tip), label + ' hover promises merges next: ' + info.tip); assert.ok(info.until === 0, label + ' no ETA countdown ahead of readiness'); } else { - assert.ok(/^Merge queued · (1st|2nd)( of \d+)?$/.test(word), label + ' place word: ' + JSON.stringify(word)); + assert.ok(/^Queued for merge · (1st|2nd)( of \d+)?$/.test(word), label + ' place word: ' + JSON.stringify(word)); } } // hive's own #15577 exactly: 050, front, CI running — the chevron leads with CI / Review. diff --git a/src/pkg/dashboard/stage_tracker_merge_train_queue_test.go b/src/pkg/dashboard/stage_tracker_merge_train_queue_test.go index 4fe7c2297e..479d4eae8b 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train_queue_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_train_queue_test.go @@ -280,7 +280,7 @@ const quiet = mk(15319, 'fleetreport: slog feed', Object.assign({ state: 'queued const busy = mk(15319, 'fleetreport: slog feed', Object.assign({ state: 'queued-behind', position: 2, ahead: [15315] }, headFacts), { sweep_running: true }); const a = stageTrackerMergeGateInfo(quiet, now), b = stageTrackerMergeGateInfo(busy, now); // Stability: the sweep flag changes neither the word nor the detail. -assert.strictEqual(a.word, 'Merge queued · 2nd of 3'); +assert.strictEqual(a.word, 'Queued for merge · 2nd of 3'); assert.strictEqual(b.word, a.word, 'sweep_running must not change the chip label'); assert.strictEqual(a.detail, ''); assert.strictEqual(b.detail, ''); assert.strictEqual(stageTrackerMergeGateWordHtml(quiet, now), stageTrackerMergeGateWordHtml(busy, now), 'identical chip markup'); @@ -294,7 +294,7 @@ assert.ok(stageTrackerGateCueHtml(busy, now).includes('cue-spin') && !stageTrack // A soaking head: the estimate is the head's soak plus one slot per PR ahead. const soakHead = mk(15374, 'tracker: queue', { state: 'queued-behind', position: 3, ahead: [15315, 15319], head_state: 'soaking', head_reason: 'soaking, 12m left', eta_s: 25 * 60 }, { sweep_running: true }); const s = stageTrackerMergeGateInfo(soakHead, now); -assert.strictEqual(s.word, 'Merge queued · 3rd of 3'); +assert.strictEqual(s.word, 'Queued for merge · 3rd of 3'); assert.ok(s.tip.startsWith('3rd of 3 in the merge queue · behind #15315 (soaking, 12m left) · ETA ~25m. Hive merges one at a time, in order. Checking now…'), s.tip); // Stalled: the chip says so, names the head and how long; the markup wears the stalled class. const stalled = mk(15374, 'tracker: queue', Object.assign({ state: 'queued-behind', position: 3, ahead: [15315, 15319], stalled: true, stalled_s: 3 * 3600 }, headFacts), { sweep_running: true }); @@ -304,7 +304,7 @@ assert.ok(stageTrackerMergeGateWordHtml(stalled, now).includes('class="ham-seg-t assert.strictEqual(stageTrackerMergeGateInfo(mk(15374, 't', Object.assign({ state: 'queued-behind', position: 3, stalled: true, stalled_s: 3 * 3600 }, headFacts), { sweep_running: false }), now).word, st.word, 'stalled label is sweep-stable too'); // The front row reads its place too. const head = mk(15315, 'fleetreport: head', Object.assign({ state: 'front', position: 1, ahead: [] }, headFacts)); -assert.strictEqual(stageTrackerMergeGateInfo(head, now).word, 'Merge queued · 1st of 3'); +assert.strictEqual(stageTrackerMergeGateInfo(head, now).word, 'Queued for merge · 1st of 3'); assert.ok(stageTrackerMergeGateInfo(head, now).tip.startsWith('1st of 3 in the merge queue · merges next (waiting for a maintainer (untrusted author)). Hive merges one at a time, in order.'), stageTrackerMergeGateInfo(head, now).tip); // hive's own #15406 read the bare slug "front" while the front sat in its // soak (the mirrored soak clock returned the raw state). A front in soak @@ -312,20 +312,20 @@ assert.ok(stageTrackerMergeGateInfo(head, now).tip.startsWith('1st of 3 in the m const frontSoak = mk(15406, 'in soak at the front', { state: 'front', position: 1, size: 4, length: 4, head_number: 15406, front: 15406, ahead: [], head_state: 'soaking', head_reason: 'soaking, 12m left', eta_s: 760, eta_at: new Date(now + 760 * 1000).toISOString(), eta_basis: 'own soak 12m · next pass in 40s' }, { state: 'front', soak_until: new Date(now + 12 * 60 * 1000).toISOString(), soak_started_at: new Date(now - 18 * 60 * 1000).toISOString(), sweep_running: true }); const fs = stageTrackerMergeGateInfo(frontSoak, now); -assert.strictEqual(fs.word, 'Merge queued · 1st of 4', fs.word); assert.strictEqual(fs.detail, '~13m'); +assert.strictEqual(fs.word, 'Queued for merge · 1st of 4', fs.word); assert.strictEqual(fs.detail, '~13m'); assert.strictEqual(stageTrackerMergeGateInfo(Object.assign({}, frontSoak, { merge_gate: Object.assign({}, frontSoak.merge_gate, { sweep_running: false }) }), now).word, fs.word); -assert.strictEqual(stageTrackerMergeGateWordHtml(frontSoak, now).replace(/<[^>]+>/g, ''), 'Merge queued · 1st of 4 · ~13m'); +assert.strictEqual(stageTrackerMergeGateWordHtml(frontSoak, now).replace(/<[^>]+>/g, ''), 'Queued for merge · 1st of 4 · ~13m'); // Countdown to auto-merge: eta_at drives "· ~4m" on the chip; the detail carries // the clock so the shared tick keeps counting and a re-render lands on the same // instant (no reset on poll). const etaAt = new Date(now + 4 * 60 * 1000).toISOString(); const timed = mk(15319, 'fleetreport: slog feed', { state: 'queued-behind', position: 2, ahead: [15315], head_state: 'soaking', head_reason: 'soaking, 3m left', eta_s: 240, eta_at: etaAt, eta_basis: '1 ahead · head soaking 3m · next pass in 40s' }, { sweep_running: false }); const ti = stageTrackerMergeGateInfo(timed, now); -assert.strictEqual(ti.word, 'Merge queued · 2nd of 3'); assert.strictEqual(ti.detail, '~4m'); assert.strictEqual(ti.until, now + 4 * 60 * 1000); +assert.strictEqual(ti.word, 'Queued for merge · 2nd of 3'); assert.strictEqual(ti.detail, '~4m'); assert.strictEqual(ti.until, now + 4 * 60 * 1000); assert.ok(ti.tip.includes('· ETA ~4m (1 ahead · head soaking 3m · next pass in 40s).'), ti.tip); const chipHtml = stageTrackerMergeGateWordHtml(timed, now); -assert.ok(chipHtml.includes('>Merge queued · 2nd of 3 · ~4m'), chipHtml); -assert.strictEqual(chipHtml.replace(/<[^>]+>/g, ''), 'Merge queued · 2nd of 3 · ~4m'); +assert.ok(chipHtml.includes('>Queued for merge · 2nd of 3 · ~4m'), chipHtml); +assert.strictEqual(chipHtml.replace(/<[^>]+>/g, ''), 'Queued for merge · 2nd of 3 · ~4m'); // The same payload 90s later (a poll re-render) reads 2m30s, not 4m again. assert.strictEqual(stageTrackerMergeGateInfo(timed, now + 90 * 1000).detail, '~3m'); assert.strictEqual(stageTrackerMergeGateInfo(timed, now + 150 * 1000).detail, '~2m'); @@ -520,7 +520,7 @@ assert.strictEqual(stageTrackerTrainWord(headRow), 'Merge queue · stalled — n assert.strictEqual(stageTrackerTrainStallWhy({ head_state: 'needs-human', head_reason: 'waiting for a human decision' }), 'needs a human decision'); // An unmapped head_state falls back to the head's plain-word reason. assert.strictEqual(stageTrackerTrainStallWhy({ head_state: 'something-new', head_reason: 'doing a thing; details' }), 'doing a thing'); -assert.strictEqual(stageTrackerMergeGateStateWord('front'), 'Merge queued'); +assert.strictEqual(stageTrackerMergeGateStateWord('front'), 'Queued for merge'); assert.strictEqual(stageTrackerMergeGateStateWord('duplicate-of:15402'), 'Duplicate of #15402'); // The held duplicate's chip: "Duplicate of #15402 · needs a pick", the hover names the issue and the pick rule. const heldDup = { repo: 'hivecommons/hive', number: 15407, kind: 'pr', title: 't', stage: 80, modifiers: ['needs-decision'], merge_gate: { state: 'duplicate-of:15402', duplicate_of: 15402, duplicate_issue: 15396, sweep_running: true } }; diff --git a/src/pkg/dashboard/stage_tracker_merge_train_tag_test.go b/src/pkg/dashboard/stage_tracker_merge_train_tag_test.go index d92ab88431..e1eddd06ba 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train_tag_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_train_tag_test.go @@ -56,30 +56,30 @@ assert.strictEqual(stageTrackerTrainIndex([]).count, 0); assert.strictEqual(stageTrackerTrainIndex([{ group: { key: 'g' } }, { group: { key: 'g' }, item: a1 }, { item: b2 }]).count, 2); // "1st of 2" always; the tag only past one train. -assert.strictEqual(stageTrackerTrainWord(a1), 'Merge queued · 1st of 2'); -assert.strictEqual(stageTrackerTrainWord(a1, 1), 'Merge queued · 1st of 2'); -assert.strictEqual(stageTrackerTrainWord(a1, 2), 'Merge queued · 1st of 2 · train main.go'); -assert.strictEqual(stageTrackerTrainWord(a2, 2), 'Merge queued · 2nd of 2 · train main.go'); -assert.strictEqual(stageTrackerTrainWord(b1, 2), 'Merge queued · 1st of 2 · train stage_tracker.go'); -assert.strictEqual(stageTrackerTrainWord(b2, 2), 'Merge queued · 2nd of 2 · train stage_tracker.go'); +assert.strictEqual(stageTrackerTrainWord(a1), 'Queued for merge · 1st of 2'); +assert.strictEqual(stageTrackerTrainWord(a1, 1), 'Queued for merge · 1st of 2'); +assert.strictEqual(stageTrackerTrainWord(a1, 2), 'Queued for merge · 1st of 2 · train main.go'); +assert.strictEqual(stageTrackerTrainWord(a2, 2), 'Queued for merge · 2nd of 2 · train main.go'); +assert.strictEqual(stageTrackerTrainWord(b1, 2), 'Queued for merge · 1st of 2 · train stage_tracker.go'); +assert.strictEqual(stageTrackerTrainWord(b2, 2), 'Queued for merge · 2nd of 2 · train stage_tracker.go'); // Two trains never yield the same chevron word for the same place. assert.notStrictEqual(stageTrackerTrainWord(a1, two.count), stageTrackerTrainWord(b1, two.count)); assert.notStrictEqual(stageTrackerTrainWord(a2, two.count), stageTrackerTrainWord(b2, two.count)); // No overlap list: the head names the train. const bare = mk(15600, 'v5#15600', 1, 3, [], 15600); assert.strictEqual(stageTrackerTrainTag(bare.merge_train), '#15600'); -assert.strictEqual(stageTrackerTrainWord(bare, 2), 'Merge queued · 1st of 3 · train #15600'); +assert.strictEqual(stageTrackerTrainWord(bare, 2), 'Queued for merge · 1st of 3 · train #15600'); assert.strictEqual(stageTrackerTrainTag({}), ''); // The gate chip reads the same word, and its hover names the train. const chipA2 = stageTrackerMergeGateInfo(a2, now, 2); -assert.strictEqual(chipA2.word, 'Merge queued · 2nd of 2 · train main.go'); +assert.strictEqual(chipA2.word, 'Queued for merge · 2nd of 2 · train main.go'); assert.ok(chipA2.tip.startsWith('Train of 2 PRs overlapping main.go; merges after #15567. 2nd of 2 in the merge queue · behind #15567'), chipA2.tip); const chipB1 = stageTrackerMergeGateInfo(b1, now, 2); -assert.strictEqual(chipB1.word, 'Merge queued · 1st of 2 · train stage_tracker.go'); +assert.strictEqual(chipB1.word, 'Queued for merge · 1st of 2 · train stage_tracker.go'); assert.ok(chipB1.tip.startsWith('Train of 2 PRs overlapping stage_tracker.go; merges first. 1st of 2 in the merge queue · merges next'), chipB1.tip); assert.ok(!stageTrackerMergeGateInfo(a2, now, 1).tip.includes('Train of'), 'one train: no train sentence'); assert.ok(!stageTrackerMergeGateInfo(a2, now).tip.includes('Train of'), 'no count: no train sentence'); -assert.strictEqual(stageTrackerMergeGateWordHtml(a2, now, 2).replace(/<[^>]+>/g, ''), 'Merge queued · 2nd of 2 · train main.go'); +assert.strictEqual(stageTrackerMergeGateWordHtml(a2, now, 2).replace(/<[^>]+>/g, ''), 'Queued for merge · 2nd of 2 · train main.go'); assert.ok(stageTrackerGateCueHtml(a2, now, 2).includes('Train of 2 PRs overlapping main.go'), stageTrackerGateCueHtml(a2, now, 2)); // A provisional slot (#15581) keeps blocker-first and still names its train. const p1 = mk(15577, 'v5#15577', 1, 2, ['tracker-words.js'], 15577, 50); diff --git a/src/pkg/dashboard/stage_tracker_merge_train_test.go b/src/pkg/dashboard/stage_tracker_merge_train_test.go index 1c6b554697..99e7584e3c 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_train_test.go @@ -302,19 +302,19 @@ const other = { repo: 'hivecommons/hive', number: 15100, kind: 'pr', title: 'Doc // Pill wording per state: the place in the owner's words (#15395 — // "'front' should be 'merge queued - 1st' and so on"). -assert.strictEqual(stageTrackerTrainWord(front), 'Merge queued · 1st of 4'); -assert.strictEqual(stageTrackerTrainWord(second), 'Merge queued · 2nd of 4'); +assert.strictEqual(stageTrackerTrainWord(front), 'Queued for merge · 1st of 4'); +assert.strictEqual(stageTrackerTrainWord(second), 'Queued for merge · 2nd of 4'); assert.strictEqual(stageTrackerTrainWord(third), 'Rebasing · attempt 1/2'); assert.strictEqual(stageTrackerTrainWord(fourth), 'Needs human decision · rebase failed twice'); assert.strictEqual(stageTrackerTrainWord(other), ''); for (const [n, w] of [[1, '1st'], [2, '2nd'], [3, '3rd'], [4, '4th'], [11, '11th'], [12, '12th'], [13, '13th'], [21, '21st'], [22, '22nd'], [111, '111th']]) assert.strictEqual(stageTrackerOrdinal(n), w, 'ordinal ' + n); // The lit chevron carries the word: 080 for the members, the 085 detour for the exhausted one. const lit = it => stageTrackerSegments(it, stages, now).find(s => s.state === 'active'); -assert.strictEqual(lit(front).short, 'Merge queued · 1st of 4'); -assert.strictEqual(lit(second).short, 'Merge queued · 2nd of 4'); +assert.strictEqual(lit(front).short, 'Queued for merge · 1st of 4'); +assert.strictEqual(lit(second).short, 'Queued for merge · 2nd of 4'); assert.strictEqual(lit(third).short, 'Rebasing · attempt 1/2'); assert.strictEqual(lit(fourth).detour.text, 'Needs human decision · rebase failed twice'); -assert.strictEqual(lit(other).short, 'Ready for auto merge'); +assert.strictEqual(lit(other).short, 'Queued for merge'); // Tooltip: the queue ahead and the overlapping files. const tip = stageTrackerTooltip(third, now); @@ -334,12 +334,12 @@ const sorted = [fourth, other, third, { repo: 'x/y', number: 1, kind: 'issue', s // Queue facts (#15395): the chip is the position, never the slug; the // hover sentence names the head, what it waits on and the estimate. const queued = mk(15319, 80, { state: 'queued-behind', position: 2, ahead: [15315], length: 3, head_number: 15315, head_state: 'soaking', head_reason: 'soaking, 12m left', eta_s: 1500 }); -assert.strictEqual(stageTrackerTrainWord(queued), 'Merge queued · 2nd of 3'); +assert.strictEqual(stageTrackerTrainWord(queued), 'Queued for merge · 2nd of 3'); assert.strictEqual(stageTrackerTrainQueueTip(queued.merge_train), '2nd of 3 in the merge queue · behind #15315 (soaking, 12m left) · ETA ~25m. Hive merges one at a time, in order.'); const firstQ = mk(15315, 80, { state: 'front', position: 1, length: 3, head_number: 15315, head_state: 'soaking', head_reason: 'soaking, 12m left', eta_s: 780 }); assert.strictEqual(stageTrackerTrainQueueTip(firstQ.merge_train), '1st of 3 in the merge queue · merges next (soaking, 12m left) · ETA ~13m. Hive merges one at a time, in order.'); const thirdQ = mk(15374, 80, { state: 'queued-behind', position: 3, ahead: [15315, 15319], length: 3, head_number: 15315, head_state: 'needs-human', head_reason: 'waiting for a maintainer (untrusted author)', eta_s: 0 }); -assert.strictEqual(stageTrackerTrainWord(thirdQ), 'Merge queued · 3rd of 3'); +assert.strictEqual(stageTrackerTrainWord(thirdQ), 'Queued for merge · 3rd of 3'); assert.strictEqual(stageTrackerTrainQueueTip(thirdQ.merge_train), '3rd of 3 in the merge queue · behind #15315 (waiting for a maintainer (untrusted author)) · no estimate until #15315 moves. Hive merges one at a time, in order.'); const stalledQ = mk(15374, 80, { state: 'queued-behind', position: 3, ahead: [15315, 15319], length: 3, head_number: 15315, head_state: 'ci', head_reason: 'waiting for CI', stalled: true, stalled_s: 3 * 3600 }); assert.strictEqual(stageTrackerTrainWord(stalledQ), 'Merge queue · stalled — waiting on #15315 (waiting for CI) · 3h'); @@ -352,14 +352,14 @@ for (const it of [queued, firstQ, thirdQ, stalledQ, front, second, third, fourth assert.ok(!/front|queued-behind|rebase-exhausted/i.test(seen), 'no slug or "front" for #' + it.number + ': ' + seen); } // Ordinal places beyond the first few. -for (const [pos, w] of [[11, '11th'], [12, '12th'], [13, '13th'], [21, '21st'], [22, '22nd'], [23, '23rd']]) assert.strictEqual(stageTrackerTrainWord(mk(1, 80, { state: 'queued-behind', position: pos, length: 30 })), 'Merge queued · ' + w + ' of 30'); +for (const [pos, w] of [[11, '11th'], [12, '12th'], [13, '13th'], [21, '21st'], [22, '22nd'], [23, '23rd']]) assert.strictEqual(stageTrackerTrainWord(mk(1, 80, { state: 'queued-behind', position: pos, length: 30 })), 'Queued for merge · ' + w + ' of 30'); // Every train state — the 1st included — lights the Merge queue column, // whatever stage the lane holds the head at (hive #15400 at 050 lit CI / Review). for (const st of ['front', 'queued-behind', 'rebasing', 'rebase-exhausted']) for (const stage of [50, 60, 70, 74, 80, 95]) assert.strictEqual(stageTrackerAnchor(stage, stages, 'pr', mk(2, stage, { state: st, position: 1 })), 80, st + ' at ' + stage); assert.strictEqual(stageTrackerAnchor(50, stages, 'pr', other), 50, 'no train: stage rules as before'); // The 1st-in-train head at 050 lights the Merge queue column, but its // word leads with the stage's blocker — the slot is provisional until -// CI and the verdict are in (hive #15577 read "Merge queued · 1st" over +// CI and the verdict are in (hive #15577 read "Queued for merge · 1st" over // a caption saying build-and-test was still running). const headAt50 = mk(15400, 50, { state: 'front', position: 1 }); assert.strictEqual(lit(headAt50).number, 80); diff --git a/src/pkg/dashboard/stage_tracker_merging_hold_test.go b/src/pkg/dashboard/stage_tracker_merging_hold_test.go index 24929f956e..382c00f5a7 100644 --- a/src/pkg/dashboard/stage_tracker_merging_hold_test.go +++ b/src/pkg/dashboard/stage_tracker_merging_hold_test.go @@ -370,8 +370,8 @@ info = stageTrackerMergeGateInfoFor(item({ state: 'merging' }), null, now); assert.strictEqual(info.detail, '', 'legacy 100 record: word alone'); info = stageTrackerMergeGateInfoFor(Object.assign(item({ state: 'merge-failed', merge_failed: 'merging PR o/r#1 (abc): 405 Pull Request is not mergeable\nmore', merge_failed_at: new Date(now - 9000).toISOString(), merge_path: 'relay' }), { stage: 90 }), null, now); assert.strictEqual(info.state, 'merge-failed'); -assert.strictEqual(info.word, 'Merge failed'); -assert.strictEqual(info.detail, 'branch protection', 'kind words, never the raw error'); +assert.strictEqual(info.word, 'Queued for merge', 'a refusal the lane retries keeps the queue word (#16653)'); +assert.strictEqual(info.detail, 'branch protection pending', 'kind words, never the raw error'); assert.strictEqual(info.cue, 'waiting'); assert.ok(info.tip.includes('hive-merge relay') && info.tip.includes('GitHub refused — branch protection blocks it') && info.tip.includes('Details: merging PR o/r#1 (abc): 405 Pull Request is not mergeable'), info.tip); assert.strictEqual(stageTrackerMergeFailedShort(''), 'GitHub refused the merge'); diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index 7e761a97d2..97cabbc3cf 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -436,6 +436,7 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsFunc(t, html, "stageTrackerShortAgo"), jsFunc(t, html, "stageTrackerWaitingOnPerson"), jsFunc(t, html, "stageTrackerTrackRunning"), + jsFunc(t, html, "stageTrackerAgoWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), @@ -457,6 +458,7 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerSubRowHtml"), jsFunc(t, html, "stageTrackerPRPillsHtml"), + jsFunc(t, html, "stageTrackerBasePillHtml"), jsFunc(t, html, "stageTrackerLinkedPRItem"), jsFunc(t, html, "stageTrackerLinkedPROpen"), jsFunc(t, html, "stageTrackerNestedOpenPRs"), @@ -496,8 +498,8 @@ assert.deepStrictEqual(ols(stageTrackerRowHtml(next[2], stages, ctx)), [''], 'an assert.deepStrictEqual(ols(stageTrackerRowHtml(next[1], stages, ctx)), ['', ' data-ham-prev-col="4" data-ham-col="6"', ''], 'only the nested PR that moved is stamped (sub-rows sort furthest first)'); assert.deepStrictEqual(ols(stageTrackerRowHtml(next[0], stages, { nowMs: now })), [''], 'no moves in ctx → no stamp'); ` - cmd := exec.Command(node, "-e", script) - if out, err := cmd.CombinedOutput(); err != nil { + // Over stdin: the lifted harness is past Linux's -e argument limit. + if out, err := runNodeStdin(node, script); err != nil { t.Fatalf("node row stamp fixture failed: %v\n%s", err, out) } } @@ -573,6 +575,7 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerSoakLeft"), jsFunc(t, html, "stageTrackerWaitingOnPerson"), jsFunc(t, html, "stageTrackerTrackRunning"), + jsFunc(t, html, "stageTrackerAgoWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), @@ -592,6 +595,7 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { stageTrackerActedJS(t, html), jsFunc(t, html, "stageTrackerSubRowHtml"), jsFunc(t, html, "stageTrackerPRPillsHtml"), + jsFunc(t, html, "stageTrackerBasePillHtml"), jsFunc(t, html, "stageTrackerLinkedPRItem"), jsFunc(t, html, "stageTrackerLinkedPROpen"), jsFunc(t, html, "stageTrackerNestedOpenPRs"), diff --git a/src/pkg/dashboard/stage_tracker_new_test.go b/src/pkg/dashboard/stage_tracker_new_test.go index 70e3d96be9..a1206ecc1b 100644 --- a/src/pkg/dashboard/stage_tracker_new_test.go +++ b/src/pkg/dashboard/stage_tracker_new_test.go @@ -299,6 +299,7 @@ func TestStageTrackerNewRowRendering(t *testing.T) { jsFunc(t, html, "stageTrackerSegments"), jsFunc(t, html, "stageTrackerWaitingOnPerson"), jsFunc(t, html, "stageTrackerTrackRunning"), + jsFunc(t, html, "stageTrackerAgoWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerTooltip"), diff --git a/src/pkg/dashboard/stage_tracker_pills_gate_test.go b/src/pkg/dashboard/stage_tracker_pills_gate_test.go index b3f805643d..9024aaa40a 100644 --- a/src/pkg/dashboard/stage_tracker_pills_gate_test.go +++ b/src/pkg/dashboard/stage_tracker_pills_gate_test.go @@ -133,7 +133,7 @@ func TestStageTrackerDeferredPillsPayload(t *testing.T) { if !strings.Contains(string(raw), `"modifiers":[],"deferred_modifiers":["sentinel","needs-human"]`) || !strings.Contains(string(raw), `"sentinel_alert":true`) { t.Fatalf("payload: %s", raw) } - if held := trackerItem(t, resp, "pr", 141); held.Stage != 72 || !hasMod(held, modUnauthorized) || len(held.DeferredModifiers) != 0 || held.UnauthorizedStep != "approve workflow runs" || !strings.Contains(held.Unauthorized, "`actions: write`") { + if held := trackerItem(t, resp, "pr", 141); held.Stage != 72 || !hasMod(held, modUnauthorized) || len(held.DeferredModifiers) != 0 || held.UnauthorizedStep != "approve workflow runs" || !strings.Contains(held.Unauthorized, "'actions: write'") { t.Fatalf("PR 141 = stage %d mods %v deferred %v step %q", held.Stage, held.Modifiers, held.DeferredModifiers, held.UnauthorizedStep) } if refused := trackerItem(t, resp, "pr", 142); refused.Stage != 50 || hasMod(refused, modUnauthorized) || !slices.Equal(refused.DeferredModifiers, []string{modUnauthorized}) || refused.UnauthorizedStep != "merge" { @@ -225,7 +225,7 @@ const gate80 = { kind: 'pr', stage: 80, modifiers: [], sentinel_alert: true, hea assert.ok(stageTrackerChipsHtml(gate80).includes('ham-badge-sentinel'), 'sentinel chip at 080'); // Actionable-now pills show wherever the row stands. assert.ok(stageTrackerChipsHtml({ kind: 'pr', stage: 50, modifiers: ['hold'], deferred_modifiers: ['needs-human'] }).includes('>hold<')); -assert.ok(stageTrackerChipsHtml({ kind: 'pr', stage: 72, modifiers: ['unauthorized'], unauthorized: 'needs actions: write' }).includes('>unauthorized<')); +assert.ok(stageTrackerChipsHtml({ kind: 'pr', stage: 72, modifiers: ['unauthorized'], unauthorized: 'needs actions: write' }).includes('>hive bot lacks permission<')); assert.ok(stageTrackerNeedsAttention({ kind: 'pr', stage: 50, modifiers: ['hold'], deferred_modifiers: ['needs-human'] })); // A payload without the field (older server) renders exactly as before. assert.ok(stageTrackerChipsHtml({ kind: 'pr', stage: 50, modifiers: ['needs-human'], sentinel_alert: true }).includes('ham-badge-sentinel')); diff --git a/src/pkg/dashboard/stage_tracker_preparation_visual.test.js b/src/pkg/dashboard/stage_tracker_preparation_visual.test.js index 5fabcc1322..f7a0b9a932 100644 --- a/src/pkg/dashboard/stage_tracker_preparation_visual.test.js +++ b/src/pkg/dashboard/stage_tracker_preparation_visual.test.js @@ -52,7 +52,7 @@ function load() { for (const name of ['stageTrackerTrainIconHtml', 'stageTrackerTrainAccentClass', 'stageTrackerOrdinal']) vm.runInContext(fn('tracker-words-core', name), ctx); for (const name of ['stageTrackerLinkedSuperseder', 'stageTrackerLinkedSupersededGone', 'stageTrackerLinkedSupersededText', 'stageTrackerLinkedSupersededTip']) vm.runInContext(fn('tracker-words-gate', name), ctx); for (const name of ['stageTrackerPRKey', 'stageTrackerItemKey', 'stageTrackerRowPRKeys']) vm.runInContext(fn('tracker-merged', name), ctx); - for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerAdoptOrphanPRs', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml']) vm.runInContext(fn('tracker-row-layout', name), ctx); + for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerAdoptOrphanPRs', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml', 'stageTrackerBasePillHtml']) vm.runInContext(fn('tracker-row-layout', name), ctx); vm.runInContext(fn('tracker-row-render', 'stageTrackerRowHtml'), ctx); for (const name of ['stageTrackerPreparationWord', 'stageTrackerPreparationAge', 'stageTrackerPreparationChipHtml']) vm.runInContext(fn('tracker-queue', name), ctx); for (const name of ['stageTrackerSort', 'stageTrackerPage', 'stageTrackerPRIssueSlot']) vm.runInContext(fn('tracker-filter', name), ctx); diff --git a/src/pkg/dashboard/stage_tracker_presence.test.js b/src/pkg/dashboard/stage_tracker_presence.test.js index 70c2aadb61..97b58da05b 100644 --- a/src/pkg/dashboard/stage_tracker_presence.test.js +++ b/src/pkg/dashboard/stage_tracker_presence.test.js @@ -40,6 +40,15 @@ const src = [ pick(/function stageTrackerPresenceInPillHtml\(item, text\) \{[\s\S]*?\n \}\n/, 'stageTrackerPresenceInPillHtml'), pick(/function stageTrackerPresenceChipText\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerPresenceChipText'), pick(/function stageTrackerPresenceChipHtml\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerPresenceChipHtml'), + pick(/const STAGE_TRACKER_REWORK_WORDS = [^\n]*\n/, 'STAGE_TRACKER_REWORK_WORDS'), + pick(/function stageTrackerReworkOf\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerReworkOf'), + pick(/function stageTrackerReworkWord\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerReworkWord'), + pick(/const STAGE_TRACKER_REWORK_OWED_BY_HIVE = [^\n]*\n/, 'STAGE_TRACKER_REWORK_OWED_BY_HIVE'), + pick(/function stageTrackerReReviewOwedByHive\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerReReviewOwedByHive'), + pick(/function stageTrackerReReviewWord\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerReReviewWord'), + pick(/function stageTrackerHiveReviewerChipText\(item\) \{[\s\S]*?\n \}\n/, 'stageTrackerHiveReviewerChipText'), + pick(/function stageTrackerReworkSuffix\(text, item\) \{[\s\S]*?\n \}\n/, 'stageTrackerReworkSuffix'), + pick(/function stageTrackerReworkTip\(item, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerReworkTip'), ].join('\n'); // The clock the tooltips are rendered against, and the stubs the lifted @@ -52,7 +61,7 @@ const stubs = ` Date.now = () => ${NOW}; `; const api = new Function(stubs + src + `; return { of: stageTrackerPresenceOf, tip: stageTrackerPresenceTip, aria: stageTrackerPresenceAria, dot: stageTrackerPresenceDotHtml, - inPill: stageTrackerPresenceInPillHtml, chipText: stageTrackerPresenceChipText, chip: stageTrackerPresenceChipHtml, adoptionChip: stageTrackerAdoptionChipHtml, icons: STAGE_TRACKER_ICONS };`)(); + inPill: stageTrackerPresenceInPillHtml, chipText: stageTrackerPresenceChipText, chip: stageTrackerPresenceChipHtml, adoptionChip: stageTrackerAdoptionChipHtml, adoptionChipText: stageTrackerAdoptionChipText, reworkTip: stageTrackerReworkTip, icons: STAGE_TRACKER_ICONS };`)(); // Collapse an inline SVG's body so the surrounding markup can be matched exactly. const flat = (h) => h.replace(/]*)>[\s\S]*?<\/svg>/g, ''); @@ -170,3 +179,39 @@ test('style ratchet: the indicator uses classes and tokens, no inline styles; re assert.match(html, /\.ham-presence-unknown \.ham-presence-dot \{[^\n]*border: var\(--line-width\) solid var\(--text-faint\)[^\n]*background: transparent/); assert.match(html, /@media \(prefers-reduced-motion: reduce\) \{ \.ham-presence-online \.ham-presence-dot \{ animation: none; \} \}/); }); + +// hivecommons/hive#16615: @thatguywob (a clanker) pushed d88928e after the +// ask; every check on it is green and no findings stand against it. The +// re-review is the HIVE reviewer's to deliver — the pill must not say the +// hive waits on the clanker. +const head16615 = 'd88928e16f21ab6e653e5d06f137926bc0db1c0d'; +const pushed16615 = { repo: 'hivecommons/hive', number: 16615, kind: 'pr', stage: 72, head: head16615, author: 'thatguywob', author_kind: 'clanker', + adoption: { author: 'thatguywob', due: false, since: iso(NOW - 4 * MIN), nudges: 1, author_online: false, author_registered: true, policy: 'adopt', text: 'waiting on @thatguywob (offline 4m, 1 nudge)' }, + presence: { login: 'thatguywob', state: 'offline', kind: 'clanker', since: iso(NOW - 4 * MIN), last_seen: iso(NOW - 10 * MIN), next: 'adopt', adopt_at: iso(NOW + 11 * MIN) }, + rework: { state: 'pushed', actor: 'thatguywob', requested_at: iso(NOW - 4 * MIN), since: iso(NOW - 3 * MIN), evidence: 'commit', head: head16615, owed_by: 'hive-reviewer' }, + ci_activity: { head: head16615, state: 'passing', caption: 'CI green' }, + review_activity: { head: head16615, state: 'unknown', perspectives_done: 0, perspectives_total: 5 } }; + +test('#16615: a pushed, green head waits on the hive reviewer, not the clanker that pushed it', () => { + assert.strictEqual(api.adoptionChipText(pushed16615), 'waiting on 🐝 hive reviewer · re-review of d88928e'); + assert.strictEqual(api.chipText(pushed16615), 'waiting on 🐝 hive reviewer · re-review of d88928e'); + const chip = api.adoptionChip(pushed16615); + assert.match(chip, />waiting on 🐝 hive reviewer · re-review of d88928e { + const owes = (extra) => api.adoptionChipText({ ...pushed16615, rework: { ...pushed16615.rework, owed_by: undefined }, ...extra }); + assert.strictEqual(owes({ ci_activity: { head: head16615, state: 'failing' } }), 'waiting on @thatguywob · re-review pending', 'red CI on the pushed head is theirs to fix'); + assert.strictEqual(owes({ review_activity: { head: head16615, state: 'changes_requested' } }), 'waiting on @thatguywob · re-review pending', 'findings on the pushed head are theirs'); + assert.strictEqual(owes({ reason: 'conflicting' }), 'waiting on @thatguywob · re-review pending', 'a conflict nobody rebases is theirs'); + assert.strictEqual(owes({ reason: 'conflicting', rebase: { attempt: 1, max: 2 } }), 'waiting on 🐝 hive reviewer · re-review of d88928e', 'the hive rebasing it is the hive\'s move'); + assert.strictEqual(api.adoptionChipText({ ...pushed16615, rework: { ...pushed16615.rework, owed_by: 'author' } }), 'waiting on @thatguywob · re-review pending', 'the server\'s word wins over the activities'); + assert.strictEqual(api.adoptionChipText({ ...pushed16615, rework: { ...pushed16615.rework, owed_by: undefined, state: 'acknowledged' } }), 'waiting on @thatguywob · acknowledged', 'before the push the author owes the rework'); + const authorChip = api.adoptionChip({ ...pushed16615, rework: { ...pushed16615.rework, owed_by: undefined }, ci_activity: { head: head16615, state: 'failing' } }); + assert.match(authorChip, /ham-presence-dot/, 'the author pill keeps its presence glyph'); +}); diff --git a/src/pkg/dashboard/stage_tracker_recently_closed.go b/src/pkg/dashboard/stage_tracker_recently_closed.go index a74ba1e5ef..bc116ea952 100644 --- a/src/pkg/dashboard/stage_tracker_recently_closed.go +++ b/src/pkg/dashboard/stage_tracker_recently_closed.go @@ -29,6 +29,7 @@ func (s *Server) noteClosedSnapshots(snaps []github.WebhookItemSnapshot) { } now := time.Now() qualify := s.mergedRepoQualifier() + ledger := s.mergedLedger() s.recentlyClosedMu.Lock() defer s.recentlyClosedMu.Unlock() for _, snap := range snaps { @@ -36,6 +37,12 @@ func (s *Server) noteClosedSnapshots(snaps []github.WebhookItemSnapshot) { continue } repo := qualify(snap.Repo) + // A snapshot that cannot tell merged from closed (a hint from a + // delivery without the PR object) must not contradict a merge the + // ledger already holds: "closed" would be the SPA's final word. + if ledger.Has(repo, snap.Number) { + continue + } at := snap.UpdatedAt if at.IsZero() || at.After(now) { at = now @@ -55,6 +62,35 @@ func (s *Server) noteClosedSnapshots(snaps []github.WebhookItemSnapshot) { s.pruneRecentlyClosedLocked(now) } +// forgetClosedSnapshots drops from the list every PR snaps now report +// merged: an earlier closed-unmerged read was wrong (or arrived before the +// merge fact), and the SPA must see the merge, not the close. +func (s *Server) forgetClosedSnapshots(snaps []github.WebhookItemSnapshot) { + if s == nil || len(snaps) == 0 { + return + } + qualify := s.mergedRepoQualifier() + s.recentlyClosedMu.Lock() + defer s.recentlyClosedMu.Unlock() + if len(s.recentlyClosed) == 0 { + return + } + for _, snap := range snaps { + if !snap.IsPR || !snap.Merged || snap.Number <= 0 || snap.Repo == "" { + continue + } + repo := qualify(snap.Repo) + kept := s.recentlyClosed[:0] + for _, e := range s.recentlyClosed { + if e.Number == snap.Number && strings.EqualFold(e.Repo, repo) { + continue + } + kept = append(kept, e) + } + s.recentlyClosed = kept + } +} + // pruneRecentlyClosedLocked drops entries older than the window and, past // the cap, the oldest. Caller holds recentlyClosedMu. func (s *Server) pruneRecentlyClosedLocked(now time.Time) { diff --git a/src/pkg/dashboard/stage_tracker_remediation.go b/src/pkg/dashboard/stage_tracker_remediation.go index 3aa21534e6..362dd629cc 100644 --- a/src/pkg/dashboard/stage_tracker_remediation.go +++ b/src/pkg/dashboard/stage_tracker_remediation.go @@ -86,6 +86,15 @@ func stageTrackerRedSince(it *StageTrackerItem) (time.Time, string, bool) { // head has no review / CI verdict recorded yet. const stageTrackerFixRequestedWord = "Fix requested" +// PR in progress chevron words for a red PR nobody has picked up. They +// name the PR's lifecycle state — who owes the next head — never the CI +// or review verdict, which is the CI / Review chevron's information and +// stays in the detail (hivecommons/hive#16643). +const ( + prProgressUnassignedWord = "Unassigned" + prProgressFixOwedWord = "fix owed" +) + // stageTrackerRemediationEvidence is the one place pickup evidence is read. // Each source is independent; the most recent evidence wins so a kick that // follows a push (the agent iterating) reads as remediating again. @@ -320,7 +329,10 @@ func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.Dispatch out.Detail += ")." it.DisplayColumn = trackerNumberPRInProgress case out.State == "waiting_owner": - out.Caption = strings.Replace(out.Caption, " · not observed coding", " · "+strings.ToLower(redWord), 1) + // The PR in progress chevron speaks the PR's own lifecycle; the red + // word (CI failing / changes requested) is the CI or Review + // chevron's and rides only in the detail (hivecommons/hive#16643). + out.Caption = strings.Replace(out.Caption, " · not observed coding", " · "+prProgressFixOwedWord, 1) out.Detail = redWord + redAt + "; no push, claim or fix kick seen since. A new head from @" + it.Author + ", a clanker claim or a hive adoption would move it." it.DisplayColumn = trackerNumberPRInProgress default: @@ -329,7 +341,7 @@ func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.Dispatch if redSince.IsZero() { out.Since = nil } - out.Caption = redWord + " · unassigned" + out.Caption = prProgressUnassignedWord if r := it.Rework; r != nil && r.Evidence == reworkEvidenceQueued && r.Actor != "" { out.Caption += fmt.Sprintf(" · fixer queued, %d ahead", r.Ahead) next = "@" + r.Actor + "'s clanker" diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index 9775682398..ff2ffec02d 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -1,5 +1,5 @@ // The PR in progress chevron on a red PR (hivecommons/hive stage -// stage_tracker_remediation.go): "Changes requested · unassigned" bright +// stage_tracker_remediation.go): "Unassigned · next: scanner" bright // and still, "Remediating · " pulsing on pickup evidence, and a // done-style "Fix pushed · re-review pending" once a head lands after // the red signal. Functions are lifted from static-src as the activity @@ -33,7 +33,7 @@ function constLine(source, 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 trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerAgoWord', '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 segments = new Function('stageTrackerAnchor', globals + ` @@ -65,12 +65,12 @@ const redPR = extra => ({ }); test('unassigned: PR in progress is lit, bright and still, with the pickup rule in its tooltip', () => { - const item = redPR({ display_column: 30, code_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Changes requested · unassigned · next: scanner', source: 'no-pickup-evidence', since: red, detail: 'Changes requested at ' + red + '; no fix kick, claim or new head seen since. It switches to Remediating when a hive fix kick for this head runs, a clanker claims it or scanner pushes.' } }); + const item = redPR({ display_column: 30, code_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Unassigned · next: scanner', source: 'no-pickup-evidence', since: red, detail: 'Changes requested at ' + red + '; no fix kick, claim or new head seen since. It switches to Remediating when a hive fix kick for this head runs, a clanker claims it or scanner pushes.' } }); const c = cells(item); const pr = c[3]; assert.match(pr, /class="ham-seg active[^"]*ham-remediation-unassigned/); assert.match(pr, /data-remediation="unassigned"/); - assert.match(pr, /Changes requested · unassigned · next: scanner/); + assert.match(pr, /Unassigned · next: scanner/); assert.doesNotMatch(pr, /data-motion="active"/, 'nobody is on it: no pulse'); assert.match(pr, /switches to Remediating when a hive fix kick/); assert.match(c[5], /data-activity-state="changes_requested"/, 'the Review track keeps its own red state'); @@ -104,7 +104,7 @@ test('fix pushed: PR in progress is done-style with its word while CI / Review i }); test('a red PR with a stale code head renders no remediation attributes', () => { - const item = redPR({ display_column: 30, code_activity: { head: 'older', state: 'unassigned', caption: 'Changes requested · unassigned · next: scanner' } }); + const item = redPR({ display_column: 30, code_activity: { head: 'older', state: 'unassigned', caption: 'Unassigned · next: scanner' } }); const html = renderStrip(item, stages, null, now, {}); assert.doesNotMatch(html, /data-remediation=/); }); @@ -161,27 +161,27 @@ const seen = '2026-11-04T02:44:00Z'; test('#16509 row: adopted, CI 7/11 unreported, review 5/5 decided → one amber chevron', () => { const item = redPR({ stage: 74, display_column: 30, code_activity: { head: 'abc1234def', state: 'adopted', caption: 'Adopted by hive · activity', source: 'adoption', observed_at: seen }, - ci_activity: { head: 'abc1234def', 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 }, + ci_activity: { head: 'abc1234def', 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 }, review_activity: { head: 'abc1234def', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }); const c = cells(item); assert.match(c[3], /class="ham-seg active detoured"/, 'the stage chevron is the one lit chevron'); // #16599: unreported checks are not motion and not the stage's track → // neutral glyph alone, count words in the tooltip. assert.match(c[4], /class="ham-seg ham-activity-track todo"/, 'unreported checks are not motion'); - assert.match(c[4], /title="CI: CI 7\/11 · test not reported · /); - assert.doesNotMatch(c[4], /test not reported { const owner = { head: 'abc1234def', state: 'waiting_owner', caption: 'Waiting for @hanthor · not observed coding', actor: 'hanthor', source: 'native-author-wait', observed_at: seen }; - const ci = { head: 'abc1234def', 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 ci = { head: 'abc1234def', 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 approved = { head: 'abc1234def', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen }; const c = cells(redPR({ stage: 71, display_column: 30, author: 'hanthor', author_kind: 'human', code_activity: owner, ci_activity: ci, review_activity: approved })); assert.match(c[3], /class="ham-seg active detoured"/); - assert.match(c[4], /class="ham-seg ham-activity-track todo"[^>]*title="CI: CI 7\/11 · test not reported · /); - assert.doesNotMatch(c[4], /test not reported]*title="CI: CI 7\/11 · 'test' not reported · /); + assert.doesNotMatch(c[4], /'test' not reported<\/span>/); assert.equal(litCount(c.join('')), 1); // Even a queued check does not light CI while the row waits on a person. @@ -198,20 +198,54 @@ test('three qualify: CI and review running on a lit PR in progress → tracks wi const both = cells(redPR({ display_column: 30, ...running })); assert.match(both[3], /class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/); assert.doesNotMatch(both[3], /data-motion=/); - assert.match(both[3], /Remediating · scanner · 4m/, 'the words stay'); + assert.match(both[3], /aria-label="[^"]*Remediating · scanner · 4m/, 'the words ride the tooltip'); + assert.doesNotMatch(both[3], /ham-chevron-copy/, 'icon only (hivecommons/hive#16643)'); assert.match(both[3], /Waiting on CI and review, both running/); assert.match(both[4], /ham-activity-track active"[^]*data-motion="active"/); assert.match(both[5], /ham-activity-track active"[^]*data-motion="active"/); assert.equal(litCount(both.join('')), 2); - // One track running: the stage chevron keeps its own fill and pulse. + // One track running (hivecommons/hive#16643): the PR waits on it, so the + // stage chevron defers too — settled-current, icon only — and the row + // has exactly one active chevron, the running track. const one = cells(redPR({ display_column: 30, ...running, review_activity: { ...running.review_activity, state: 'changes_requested', active: false } })); - assert.match(one[3], /class="ham-seg active ham-remediation-remediating detoured"[^>]*data-motion="active"/); - assert.equal(litCount(one.join('')), 2); + assert.match(one[3], /class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/); + assert.doesNotMatch(one[3], /data-motion=|ham-chevron-copy/); + assert.match(one[3], /title="Waiting on CI, running — /); + assert.match(one[4], /ham-activity-track active ham-current"|ham-activity-track active"/); + assert.equal(litCount(one.join('')), 1); +}); + +// hivecommons/hive#16643: the PR in progress chevron never speaks CI; it is +// the ≥ 1 fallback, active only when no track runs. +test('#16634 shape: CI 4/11 · 1 failing still running + unassigned → CI is the one active chevron, PR in progress icon only', () => { + const base = { display_column: 30, + code_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Unassigned · next: scanner', source: 'no-pickup-evidence', since: seen, observed_at: seen }, + ci_activity: { head: 'abc1234def', state: 'running', active: true, caption: 'CI running · 6 checks pending · 1 failing', checks_passed: 4, checks_total: 11, checks_failed: 1, checks_failing: ['Sign-off survives'], source: 'checks', observed_at: seen }, + review_activity: { head: 'abc1234def', state: 'changes_requested', caption: 'Review 5/5 · changes requested', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }; + const a = cells(redPR(base)); + assert.match(a[4], /class="ham-seg ham-activity-track active"[^]*CI 4\/11 · [^<]*1 failing \('Sign-off survives'\) { const c = cells(redPR({ display_column: 30, - code_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Changes requested · unassigned · next: scanner', source: 'no-pickup-evidence', since: red, observed_at: seen }, + code_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Unassigned · next: scanner', source: 'no-pickup-evidence', since: red, observed_at: seen }, ci_activity: { head: 'abc1234def', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, review_activity: { head: 'abc1234def', state: 'changes_requested', caption: 'Review findings', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: red } })); assert.match(c[3], /class="ham-seg active ham-remediation-unassigned detoured"/); @@ -229,3 +263,54 @@ test('#16539 shape: a queued swarm reads 0/5 and, as the stage\'s own track, is assert.doesNotMatch(c[5], /data-motion=/, 'queued is lit but still'); assert.equal(litCount(c.join('')), 1, 'the Review column is where the item is: the one lit chevron'); }); + +// hivecommons/hive#16631: a CI ring that is not full is a running ring. +// 13/19 with checks still pending is active with its count beside the +// running Review; only a complete 19/19 ring is the silent green glyph. +test('#16628 shape: CI 13/19 with pending checks + review in progress → both tracks active with words', () => { + const review = { head: 'abc1234def', state: 'reviewing', active: true, caption: 'Review 0/5 · in progress', perspectives_done: 0, perspectives_total: 5, source: 'dispatch', observed_at: seen }; + for (const state of ['running', 'unknown', 'queued']) { + const c = cells(redPR({ display_column: 50, stage: 50, + ci_activity: { head: 'abc1234def', state, caption: 'CI ' + state, checks_passed: 13, checks_total: 19, source: 'checks', observed_at: seen }, + review_activity: review })); + assert.match(c[4], /class="ham-seg ham-activity-track active ham-current"/, state + ': a part-filled ring is lit'); + assert.match(c[4], /CI 13\/19 · 6 (running|queued) { + const fs = require('node:fs'); + const path = require('node:path'); + const css = fs.readFileSync(path.join(__dirname, 'static-src/css/tracker.css'), 'utf8'); + const rules = Array.from(css.matchAll(/([^{}]+)\{([^}]*)\}/g)).filter(m => /ham-activity-track[^,{]*\.active|\.active[^,{]*ham-activity-track/.test(m[1]) && /background/.test(m[2])); + assert.deepEqual(rules.map(m => m[1].trim()), [], 'no selector restyles the active track fill beyond .ham-seg.active: ' + rules.map(m => m[1].trim()).join(' | ')); + assert.match(css, /\.ham-seg\.active \{ background: var\(--amber\); color: var\(--surface-0\); \}/); + const stalled = cells(redPR({ display_column: 50, stage: 50, + ci_activity: { head: 'abc1234def', state: 'missing', caption: 'CI waiting · 1 workflow run needs approval on GitHub', blocker: 'workflow-approval-required:1', checks_passed: 1, checks_total: 11, source: 'checks', observed_at: '2026-11-04T01:00:00Z' }, + review_activity: { head: 'abc1234def', state: 'approved', caption: 'Review 5/5 approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } })); + assert.match(stalled[4], /class="ham-seg ham-activity-track active ham-stalled ham-current"[^]*CI 1\/11 · waiting on workflow approval([^]*?)<\/span>/.exec(li); + const words = m ? m[2].replace(/<[^>]+>/g, '').trim() : ''; + if (words) assert.ok(/\bactive\b/.test(m[1]) && !/\b(pending|todo|done|failing|ham-settled-current)\b/.test(m[1]), 'text without the one active fill: ' + m[1]); + } +}); diff --git a/src/pkg/dashboard/stage_tracker_remediation_test.go b/src/pkg/dashboard/stage_tracker_remediation_test.go index 70fa11369f..d952c4e2bb 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_test.go +++ b/src/pkg/dashboard/stage_tracker_remediation_test.go @@ -37,7 +37,7 @@ func TestStageTrackerRemediationUnassignedWithoutEvidence(t *testing.T) { t.Fatalf("no evidence must yield no remediation record: %+v", it.Remediation) } ca := it.CodeActivity - if ca.State != codeStateUnassigned || ca.Caption != "Changes requested · unassigned · next: scanner" || it.DisplayColumn != trackerNumberPRInProgress { + if ca.State != codeStateUnassigned || ca.Caption != "Unassigned · next: scanner" || it.DisplayColumn != trackerNumberPRInProgress { t.Fatalf("unassigned word: state=%s caption=%q col=%d", ca.State, ca.Caption, it.DisplayColumn) } if !strings.Contains(ca.Detail, "switches to Remediating when") || ca.Since == nil || !ca.Since.Equal(now.Add(-40*time.Minute)) { @@ -56,7 +56,7 @@ func TestStageTrackerRemediationCIFailingWordAndPersonNext(t *testing.T) { it.CIActivity = &StageTrackerActivity{Head: it.Head, State: "failing", Since: &red} it.AuthorKind, it.Author, it.Claimant = authorKindHuman, "alice", nil stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) - if got := it.CodeActivity.Caption; got != "CI failing · unassigned · next: @alice" { + if got := it.CodeActivity.Caption; got != "Unassigned · next: @alice" { t.Fatalf("CI-only red names CI and the author: %q", got) } } @@ -146,7 +146,7 @@ func TestStageTrackerRemediationEvidenceClaim(t *testing.T) { it = remediationRedPR(now) it.Rework = &StageTrackerRework{State: reworkStateRequested, Actor: "bob", Evidence: reworkEvidenceQueued, Ahead: 3} stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) - if it.Remediation != nil || it.CodeActivity.Caption != "Changes requested · unassigned · fixer queued, 3 ahead · next: @bob's clanker" { + if it.Remediation != nil || it.CodeActivity.Caption != "Unassigned · fixer queued, 3 ahead · next: @bob's clanker" { t.Fatalf("queued fix is waiting, not remediating: %+v %q", it.Remediation, it.CodeActivity.Caption) } } @@ -191,7 +191,7 @@ func TestStageTrackerRemediationKeepsOwnerWaitAndObservedWork(t *testing.T) { stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) ca := it.CodeActivity - if ca.State != "waiting_owner" || ca.Caption != "Waiting for @erin · changes requested" || it.DisplayColumn != trackerNumberPRInProgress || it.Remediation != nil { + if ca.State != "waiting_owner" || ca.Caption != "Waiting for @erin · fix owed" || it.DisplayColumn != trackerNumberPRInProgress || it.Remediation != nil { t.Fatalf("person-owned wait keeps its word with the red reason: state=%s caption=%q col=%d ev=%+v", ca.State, ca.Caption, it.DisplayColumn, it.Remediation) } // Observed code work already reads Remediating · agent; untouched. @@ -263,3 +263,44 @@ func TestStageTrackerAdoptedRowRewordsHumanDecision(t *testing.T) { }) } } + +// hivecommons/hive#16643: the PR in progress chevron never carries the CI +// or Review chevron's verdict. Whatever is red, an unpicked-up PR reads +// its lifecycle word (Unassigned / Waiting for @author · fix owed) and the +// red word rides only in the detail. +func TestStageTrackerRemediationCaptionNeverNamesTrackVerdict(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + red := now.Add(-40 * time.Minute) + for _, tc := range []struct { + name string + ci string + review string + }{{"ci red", "failing", "approved"}, {"review red", "passing", "changes_requested"}, {"both red", "failing", "changes_requested"}} { + for _, owner := range []bool{false, true} { + it := remediationRedPR(now) + it.CIActivity = &StageTrackerActivity{Head: it.Head, State: tc.ci, Since: &red} + it.ReviewActivity = &StageTrackerActivity{Head: it.Head, State: tc.review, Since: &red} + if owner { + it.Stage, it.Author, it.AuthorKind, it.Push = trackerNumberReturned, "erin", authorKindClanker, nil + stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) + } + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + ca := it.CodeActivity + for _, word := range []string{"CI failing", "Changes requested", "changes requested", "CI "} { + if strings.Contains(ca.Caption, word) { + t.Fatalf("%s owner=%v: PR in progress caption carries the track verdict %q: %q", tc.name, owner, word, ca.Caption) + } + } + want := prProgressUnassignedWord + if owner { + want = "Waiting for @erin · " + prProgressFixOwedWord + } + if !strings.HasPrefix(ca.Caption, want) { + t.Fatalf("%s owner=%v: caption = %q, want prefix %q", tc.name, owner, ca.Caption, want) + } + if ca.Detail == "" || !(strings.Contains(ca.Detail, "CI failing") || strings.Contains(ca.Detail, "Changes requested")) { + t.Fatalf("%s owner=%v: the red word must ride in the detail: %q", tc.name, owner, ca.Detail) + } + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index 2db448c4c1..61182e97ff 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -155,6 +155,7 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerSoakLeft"), jsFunc(t, html, "stageTrackerWaitingOnPerson"), jsFunc(t, html, "stageTrackerTrackRunning"), + jsFunc(t, html, "stageTrackerAgoWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), @@ -173,6 +174,7 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerSinceHtml"), jsFunc(t, html, "stageTrackerSubRowHtml"), jsFunc(t, html, "stageTrackerPRPillsHtml"), + jsFunc(t, html, "stageTrackerBasePillHtml"), jsFunc(t, html, "stageTrackerLinkedPRItem"), jsFunc(t, html, "stageTrackerLinkedPROpen"), jsFunc(t, html, "stageTrackerNestedOpenPRs"), diff --git a/src/pkg/dashboard/stage_tracker_review_fallback.go b/src/pkg/dashboard/stage_tracker_review_fallback.go new file mode 100644 index 0000000000..248e56963a --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_review_fallback.go @@ -0,0 +1,199 @@ +package dashboard + +import ( + "fmt" + "slices" + "strings" + + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" +) + +// Review-track states the fallback derivation produces for a head with no +// verdict and no reviewer in flight (hivecommons/hive#16661). Each names +// what the row waits on, so the tooltip never reads "activity unknown". +const ( + reviewStateWaitingCI = "waiting_ci" + reviewStateNotStarted = "not_started" + reviewStateNotRequested = "not_requested" + reviewStateClosed = "closed" + reviewStateUnverified = "unverified" + reviewSourceDerived = "derived-from-pr-state" +) + +// stageTrackerReviewFallbackInputs is what the fallback can consult besides +// the review evidence itself: the PR's lifecycle, its CI track on the same +// head and whether a hive reviewer lane is configured for the repo. +type stageTrackerReviewFallbackInputs struct { + Head string + Draft bool + Closed bool + Merged bool + CI *StageTrackerActivity + ReviewerLane bool +} + +func stageTrackerReviewFallbackInputsFor(it *StageTrackerItem, pr github.PullRequest, reviewerLane bool) stageTrackerReviewFallbackInputs { + in := stageTrackerReviewFallbackInputs{Head: it.Head, CI: it.CIActivity, ReviewerLane: reviewerLane} + in.Draft = pr.Draft || slices.Contains(it.Modifiers, modDraft) + in.Merged = !pr.MergedAt.IsZero() + in.Closed = in.Merged || !pr.ClosedAt.IsZero() || strings.EqualFold(pr.State, "closed") + return in +} + +// stageTrackerReviewFallbackState replaces a Review track still "unknown" +// after the verdict, dispatch and review-pending derivations with the +// concrete statement the data supports, in this order: the PR is closed or +// merged (review is moot), it is a draft (review not requested), CI on the +// head has not finished (the reviewer waits for it), CI is done but no +// reviewer started (who is next), or nothing at all has been fetched for +// the head — the one case that may still read as no data, and it says the +// next poll refreshes it (hivecommons/hive#16661). +func stageTrackerReviewFallbackState(out *StageTrackerActivity, in stageTrackerReviewFallbackInputs) { + if out == nil || out.State != "unknown" { + return + } + sha7 := stageTrackerShortSHA(in.Head) + if sha7 == "" { + sha7 = "unknown" + } + out.Source = reviewSourceDerived + switch { + case in.Merged: + out.State, out.Caption = reviewStateClosed, "Review · n/a (merged)" + out.Detail = "The PR merged; no further review is requested for this head." + case in.Closed: + out.State, out.Caption = reviewStateClosed, "Review · n/a (closed)" + out.Detail = "The PR is closed; no review is requested for this head." + case in.Draft: + out.State, out.Caption = reviewStateNotRequested, "Review · draft, not requested" + out.Detail = "Review is requested when the author marks the draft ready for review." + default: + ci := stageTrackerReviewFallbackCI(in) + switch ci { + case "running": + out.State, out.Caption = reviewStateWaitingCI, "Review · waiting for CI" + out.Detail = fmt.Sprintf("No review has started on %s: the reviewer is requested once CI reports on this commit.", sha7) + case "done": + next := "needs reviewer" + out.Detail = fmt.Sprintf("CI has reported on %s and no reviewer has picked the head up; this repo has no hive reviewer lane, so a person must review.", sha7) + if in.ReviewerLane { + next = "hive reviewer next" + out.Detail = fmt.Sprintf("CI has reported on %s and no reviewer has picked the head up yet; the hive reviewer is next in line.", sha7) + } + out.State, out.Caption = reviewStateNotStarted, "Review · not started · "+next + default: + out.Caption = stageTrackerReviewNoDataCaption(in.Head) + out.Detail = "The spoke has not fetched checks or reviews for this commit yet; the next poll refreshes it." + out.Source = "unavailable" + } + } +} + +// stageTrackerReviewFallbackCI classifies the CI track on the same head: +// "running" (checks queued, running or not all reported), "done" (a pass, +// a failure or a skip) or "" when nothing has been observed for the head. +func stageTrackerReviewFallbackCI(in stageTrackerReviewFallbackInputs) string { + ci := in.CI + if ci == nil || in.Head == "" || !strings.EqualFold(ci.Head, in.Head) { + return "" + } + switch ci.State { + case "passing", "failing", "skipped": + return "done" + case "running", "queued", "missing": + return "running" + } + if ci.ChecksTotal > 0 { + if ci.ChecksPassed+ci.ChecksFailed < ci.ChecksTotal { + return "running" + } + return "done" + } + return "" +} + +// stageTrackerReviewVerdictDetail is the tooltip sentence behind a settled +// verdict on the head: who decided and on how many perspectives, so the +// inactive icon still explains itself. The age rides on since/observed_at +// (the UI renders "12m ago"); the sentence itself is stable across polls. +func stageTrackerReviewVerdictDetail(out *StageTrackerActivity, bundle *evidence.Bundle) string { + if out == nil || bundle == nil { + return "" + } + verdicts := trackerLatestBundleVerdicts(bundle) + by := "the hive reviewer" + n := len(verdicts) + switch out.State { + case "approved": + return fmt.Sprintf("Approved by %s on %s for this head.", by, plural(n, "perspective")) + case "changes_requested": + return fmt.Sprintf("Changes requested by %s: %s posted findings on this head; the fix is owed before a re-review.", by, plural(reviewFindingCount(verdicts), "perspective")) + case "human_decision": + return fmt.Sprintf("%s posted on this head; the review asks a person to decide.", plural(n, "perspective")) + } + return "" +} + +func reviewFindingCount(verdicts []evidence.Verdict) int { + n := 0 + for _, v := range verdicts { + if v.Verdict == "changes_requested" || v.Verdict == "reject" || v.Verdict == "requires_human" { + n++ + } + } + return n +} + +// trackerReviewPerspectives folds the bundle's latest verdicts to one per +// perspective. A blocking verdict outranks an approval from another +// backend on the same perspective, so dissent that still holds the head +// is not hidden; among equals the newest wins. +func trackerReviewPerspectives(bundle *evidence.Bundle) []StageTrackerPerspective { + latest := map[string]evidence.Verdict{} + blocking := func(v string) bool { return v != "approve" } + for _, verdict := range trackerLatestBundleVerdicts(bundle) { + if verdict.Perspective == "" { + continue + } + previous, ok := latest[verdict.Perspective] + if !ok || (!blocking(previous.Verdict) && blocking(verdict.Verdict)) || + (blocking(previous.Verdict) == blocking(verdict.Verdict) && verdict.RecordedAt.After(previous.RecordedAt)) { + latest[verdict.Perspective] = verdict + } + } + names := make([]string, 0, len(latest)) + for name := range latest { + names = append(names, name) + } + slices.Sort(names) + out := make([]StageTrackerPerspective, 0, len(names)) + for _, name := range names { + v := latest[name] + p := StageTrackerPerspective{Name: name, Verdict: v.Verdict} + if len(v.Findings) > 0 { + p.Summary = v.Findings[0].Summary + } + out = append(out, p) + } + return out +} + +// stageTrackerCINoDataCaption is the CI track's words when no check result +// has been observed for the head: the head and the next step, never +// "unknown" (hivecommons/hive#16661). +func stageTrackerCINoDataCaption(head string) string { + sha7 := stageTrackerShortSHA(head) + if sha7 == "" { + sha7 = "unknown" + } + return "CI · no checks observed for head " + sha7 + " yet · refreshing" +} + +func stageTrackerReviewNoDataCaption(head string) string { + sha7 := stageTrackerShortSHA(head) + if sha7 == "" { + sha7 = "unknown" + } + return "Review · no data for head " + sha7 + " yet · refreshing" +} diff --git a/src/pkg/dashboard/stage_tracker_review_fallback_test.go b/src/pkg/dashboard/stage_tracker_review_fallback_test.go new file mode 100644 index 0000000000..1e01d593ed --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_review_fallback_test.go @@ -0,0 +1,120 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" +) + +// hivecommons/hive#16661: a Review track with no verdict and no reviewer in +// flight states what it waits on, derived from the PR's own lifecycle and +// its CI track — one case per evidence source, never "activity unknown". +func TestStageTrackerReviewFallbackStateDerivesAConcreteStatement(t *testing.T) { + head := "f269349abcdef0123456789" + ci := func(state string, passed, failed, total int) *StageTrackerActivity { + return &StageTrackerActivity{Head: head, State: state, ChecksPassed: passed, ChecksFailed: failed, ChecksTotal: total} + } + cases := []struct { + name string + in stageTrackerReviewFallbackInputs + state string + caption string + source string + }{ + {"merged PR", stageTrackerReviewFallbackInputs{Head: head, Merged: true, Closed: true, Draft: true, CI: ci("running", 1, 0, 5)}, reviewStateClosed, "Review · n/a (merged)", reviewSourceDerived}, + {"closed PR", stageTrackerReviewFallbackInputs{Head: head, Closed: true, Draft: true, CI: ci("passing", 5, 0, 5)}, reviewStateClosed, "Review · n/a (closed)", reviewSourceDerived}, + {"draft outranks CI", stageTrackerReviewFallbackInputs{Head: head, Draft: true, CI: ci("running", 1, 0, 5)}, reviewStateNotRequested, "Review · draft, not requested", reviewSourceDerived}, + {"CI running", stageTrackerReviewFallbackInputs{Head: head, CI: ci("running", 3, 0, 11)}, reviewStateWaitingCI, "Review · waiting for CI", reviewSourceDerived}, + {"CI queued", stageTrackerReviewFallbackInputs{Head: head, CI: ci("queued", 0, 0, 11)}, reviewStateWaitingCI, "Review · waiting for CI", reviewSourceDerived}, + {"checks not all reported", stageTrackerReviewFallbackInputs{Head: head, CI: ci("missing", 7, 0, 11)}, reviewStateWaitingCI, "Review · waiting for CI", reviewSourceDerived}, + {"partial ring without a word", stageTrackerReviewFallbackInputs{Head: head, CI: ci("unknown", 13, 0, 19)}, reviewStateWaitingCI, "Review · waiting for CI", reviewSourceDerived}, + {"CI passed, hive reviewer lane", stageTrackerReviewFallbackInputs{Head: head, CI: ci("passing", 11, 0, 11), ReviewerLane: true}, reviewStateNotStarted, "Review · not started · hive reviewer next", reviewSourceDerived}, + {"CI failed, no reviewer lane", stageTrackerReviewFallbackInputs{Head: head, CI: ci("failing", 10, 1, 11)}, reviewStateNotStarted, "Review · not started · needs reviewer", reviewSourceDerived}, + {"CI skipped counts as done", stageTrackerReviewFallbackInputs{Head: head, CI: ci("skipped", 0, 0, 0), ReviewerLane: true}, reviewStateNotStarted, "Review · not started · hive reviewer next", reviewSourceDerived}, + {"full ring without a word counts as done", stageTrackerReviewFallbackInputs{Head: head, CI: ci("unknown", 19, 0, 19), ReviewerLane: true}, reviewStateNotStarted, "Review · not started · hive reviewer next", reviewSourceDerived}, + {"nothing fetched for the head", stageTrackerReviewFallbackInputs{Head: head, CI: ci("unknown", 0, 0, 0)}, "unknown", "Review · no data for head f269349 yet · refreshing", "unavailable"}, + {"CI from another head is no evidence", stageTrackerReviewFallbackInputs{Head: head, CI: &StageTrackerActivity{Head: "old", State: "passing"}}, "unknown", "Review · no data for head f269349 yet · refreshing", "unavailable"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := trackerUnknownActivity(head, stageTrackerReviewNoDataCaption(head)) + stageTrackerReviewFallbackState(out, tc.in) + if out.State != tc.state || out.Caption != tc.caption || out.Source != tc.source { + t.Fatalf("got %s %q (%s), want %s %q (%s)", out.State, out.Caption, out.Source, tc.state, tc.caption, tc.source) + } + if out.Detail == "" || strings.Contains(out.Detail, "unknown") && tc.state != "unknown" { + t.Fatalf("detail must explain the wait: %q", out.Detail) + } + if out.Active { + t.Fatalf("a derived wait is not motion: %+v", out) + } + }) + } + // A settled or in-flight track is left alone. + for _, state := range []string{"approved", "changes_requested", "human_decision", "reviewing", "assigned", "unassigned", reviewStateUnverified} { + out := &StageTrackerActivity{Head: head, State: state, Caption: "kept"} + stageTrackerReviewFallbackState(out, stageTrackerReviewFallbackInputs{Head: head, Merged: true}) + if out.State != state || out.Caption != "kept" { + t.Fatalf("%s was rewritten: %+v", state, out) + } + } +} + +func TestStageTrackerReviewFallbackInputsReadThePR(t *testing.T) { + now := time.Date(2026, 11, 4, 19, 0, 0, 0, time.UTC) + it := &StageTrackerItem{Head: "abc", Modifiers: []string{modDraft}, CIActivity: &StageTrackerActivity{Head: "abc", State: "passing"}} + in := stageTrackerReviewFallbackInputsFor(it, github.PullRequest{HeadSHA: "abc"}, true) + if !in.Draft || in.Closed || in.Merged || in.CI != it.CIActivity || !in.ReviewerLane || in.Head != "abc" { + t.Fatalf("draft modifier not read: %+v", in) + } + in = stageTrackerReviewFallbackInputsFor(&StageTrackerItem{Head: "abc"}, github.PullRequest{HeadSHA: "abc", MergedAt: now, ClosedAt: now, State: "closed"}, false) + if !in.Merged || !in.Closed || in.Draft { + t.Fatalf("merged PR not read: %+v", in) + } + in = stageTrackerReviewFallbackInputsFor(&StageTrackerItem{Head: "abc"}, github.PullRequest{HeadSHA: "abc", State: "closed"}, false) + if in.Merged || !in.Closed { + t.Fatalf("closed state not read: %+v", in) + } +} + +func TestStageTrackerCINoDataCaptionNamesTheHead(t *testing.T) { + if got := stageTrackerCINoDataCaption("f269349abcdef"); got != "CI · no checks observed for head f269349 yet · refreshing" { + t.Fatalf("caption = %q", got) + } + if got := stageTrackerCINoDataCaption(""); !strings.Contains(got, "head unknown") || strings.Contains(got, "CI unknown") { + t.Fatalf("caption = %q", got) + } +} + +// hivecommons/hive#16617: one entry per perspective, a blocking verdict on +// the same perspective outranking another backend's approval, newest among +// equals; the first finding rides as the summary. +func TestTrackerReviewPerspectivesPreserveDissent(t *testing.T) { + now := time.Date(2026, 11, 4, 19, 0, 0, 0, time.UTC) + bundle := &evidence.Bundle{Verdicts: []evidence.Verdict{ + {Perspective: "security", Backend: "a", Model: "m", Verdict: "changes_requested", RecordedAt: now.Add(-2 * time.Minute), Findings: []evidence.Finding{{Summary: "token logged"}}}, + {Perspective: "security", Backend: "b", Model: "m", Verdict: "approve", RecordedAt: now}, + {Perspective: "quality", Backend: "a", Model: "m", Verdict: "approve", RecordedAt: now.Add(-3 * time.Minute)}, + {Perspective: "quality", Backend: "a", Model: "m", Verdict: "approve", RecordedAt: now}, + {Perspective: "", Backend: "a", Model: "m", Verdict: "approve", RecordedAt: now}, + }} + got := trackerReviewPerspectives(bundle) + if len(got) != 2 || got[0].Name != "quality" || got[0].Verdict != "approve" || got[0].Summary != "" || + got[1].Name != "security" || got[1].Verdict != "changes_requested" || got[1].Summary != "token logged" { + t.Fatalf("perspectives = %+v", got) + } + out := &StageTrackerActivity{State: "changes_requested"} + if d := stageTrackerReviewVerdictDetail(out, bundle); !strings.Contains(d, "Changes requested by the hive reviewer") || !strings.Contains(d, "1 perspective posted findings") { + t.Fatalf("detail = %q", d) + } + out.State = "approved" + if d := stageTrackerReviewVerdictDetail(out, bundle); !strings.Contains(d, "Approved by the hive reviewer on") { + t.Fatalf("detail = %q", d) + } + if d := stageTrackerReviewVerdictDetail(out, nil); d != "" { + t.Fatalf("no bundle, no detail: %q", d) + } +} diff --git a/src/pkg/dashboard/stage_tracker_rework.go b/src/pkg/dashboard/stage_tracker_rework.go index dc6588529e..fcd7511ea4 100644 --- a/src/pkg/dashboard/stage_tracker_rework.go +++ b/src/pkg/dashboard/stage_tracker_rework.go @@ -68,6 +68,51 @@ type StageTrackerRework struct { Ahead int `json:"ahead,omitempty"` // Head is the new head on a pushed state. Head string `json:"head,omitempty"` + // OwedBy names who owes the next move on a pushed state + // (hivecommons/hive#16615): "hive-reviewer" when the new head needs the + // hive's re-review and nothing on it is the author's to fix, so the + // waiting-on pill names the hive, not the author; "author" when they + // still owe something on the pushed head — red CI, changes requested on + // it, or a conflict nobody in the hive is rebasing. Empty on the other + // states (and from older servers, which the dashboard reads from the + // activities instead). + OwedBy string `json:"owed_by,omitempty"` +} + +// Who owes the next move on a pushed head. +const ( + reworkOwedByHiveReviewer = "hive-reviewer" + reworkOwedByAuthor = "author" +) + +// stageTrackerApplyReworkOwedBy fills Rework.OwedBy once the row's CI and +// review activity are known (they are derived after the rework field). +func stageTrackerApplyReworkOwedBy(it *StageTrackerItem) { + if it == nil || it.Rework == nil || it.Rework.State != reworkStatePushed { + return + } + it.Rework.OwedBy = stageTrackerReworkOwedBy(*it) +} + +// stageTrackerReworkOwedBy answers "who owes the next move on the pushed +// head?" The author owes it only when the head itself asks them for +// something: CI failing on it, review findings against it, or a merge +// conflict the hive is not rebasing. Otherwise the re-review of the new +// head is the hive reviewer's to deliver. +func stageTrackerReworkOwedBy(it StageTrackerItem) string { + onHead := func(a *StageTrackerActivity) bool { + return a != nil && (a.Head == "" || it.Head == "" || strings.EqualFold(a.Head, it.Head)) + } + if onHead(it.CIActivity) && it.CIActivity.State == "failing" { + return reworkOwedByAuthor + } + if onHead(it.ReviewActivity) && it.ReviewActivity.State == "changes_requested" { + return reworkOwedByAuthor + } + if strings.Contains(strings.ToLower(it.Reason), "conflict") && it.Rebase == nil { + return reworkOwedByAuthor + } + return reworkOwedByHiveReviewer } // StageTrackerFixWork is the hub's fix-queue standing for one PR and one diff --git a/src/pkg/dashboard/stage_tracker_rework_test.go b/src/pkg/dashboard/stage_tracker_rework_test.go index 4e31912617..ce47bbd4cb 100644 --- a/src/pkg/dashboard/stage_tracker_rework_test.go +++ b/src/pkg/dashboard/stage_tracker_rework_test.go @@ -207,6 +207,10 @@ func TestStageTrackerReworkJS(t *testing.T) { jsConstLine(t, html, "STAGE_TRACKER_REWORK_WORDS"), jsFunc(t, html, "stageTrackerReworkOf"), jsFunc(t, html, "stageTrackerReworkWord"), + jsConstLine(t, html, "STAGE_TRACKER_REWORK_OWED_BY_HIVE"), + jsFunc(t, html, "stageTrackerReReviewOwedByHive"), + jsFunc(t, html, "stageTrackerReReviewWord"), + jsFunc(t, html, "stageTrackerHiveReviewerChipText"), jsFunc(t, html, "stageTrackerReworkSuffix"), jsFunc(t, html, "stageTrackerReworkTip"), jsFunc(t, html, "stageTrackerReworkJoinTip"), @@ -240,12 +244,14 @@ assert.strictEqual(stageTrackerPresenceChipText(requested), 'waiting on @Danatha assert.strictEqual(stageTrackerPresenceChipText(queued), 'waiting on @Danathar · queued'); assert.strictEqual(stageTrackerPresenceChipText(acked), 'waiting on @Danathar · acknowledged'); assert.strictEqual(stageTrackerPresenceChipText(working), 'waiting on @Danathar · working'); -assert.strictEqual(stageTrackerPresenceChipText(pushed), 'waiting on @Danathar · re-review pending'); +// A pushed head with nothing against it waits on the hive's reviewer (hivecommons/hive#16615). +assert.strictEqual(stageTrackerPresenceChipText(pushed), 'waiting on 🐝 hive reviewer · re-review of bbb'); +assert.strictEqual(stageTrackerPresenceChipText(w(Object.assign({}, pushed.rework, { owed_by: 'author' }))), 'waiting on @Danathar · re-review pending', 'the server says the author still owes it'); assert.match(stageTrackerReworkTip(requested, NOW), /^rework requested 1 hour ago \(\S+ .*\) · no response from @Danathar yet$/); assert.match(stageTrackerReworkTip(queued, NOW), /^rework queued for @Danathar's clanker · 2 ahead · queued 10 min ago \(/); assert.match(stageTrackerReworkTip(acked, NOW), /^@Danathar acknowledged · activity on the PR 20 min ago \(/); assert.match(stageTrackerReworkTip(working, NOW), /^@Danathar's clanker picked up the rework 5 min ago \(.*\) \(spawn\)$/); -assert.match(stageTrackerReworkTip(pushed, NOW), /^@Danathar pushed a new head 1 min ago \(.*\) · re-review pending$/); +assert.match(stageTrackerReworkTip(pushed, NOW), /^@Danathar pushed a new head 1 min ago \(.*\) · hive reviewer owes the re-review of bbb$/); // The pill keeps its class, dot and login; title and aria carry the rework line after the presence line. const chip = stageTrackerPresenceChipHtml(acked); assert.ok(/^waiting on ]*>[\s\S]*<\/span>@Danathar · acknowledged<\/span>$/.test(chip), chip); @@ -271,3 +277,64 @@ assert.strictEqual(states([issue])[lk].rework, 'acknowledged'); `}, "\n") runStageTrackerRowActionsScript(t, script) } + +// hivecommons/hive#16615: @thatguywob's clanker pushed d88928e; every check +// on it is green and no findings stand against it. "re-review pending" is +// the HIVE reviewer's debt, so the row says so (`owed_by`) and the pill +// stops naming the author. The author keeps the pill only when the pushed +// head asks them for something. +func TestStageTrackerReworkOwedBy16615(t *testing.T) { + const head = "d88928e16f21ab6e653e5d06f137926bc0db1c0d" + base := func() StageTrackerItem { + return StageTrackerItem{Kind: "pr", Number: 16615, Head: head, Author: "thatguywob", AuthorKind: "clanker", Stage: 72, + Rework: &StageTrackerRework{State: reworkStatePushed, Actor: "thatguywob", Evidence: reworkEvidenceCommit, Head: head}, + CIActivity: &StageTrackerActivity{Head: head, State: "passing", ChecksPassed: 11, ChecksTotal: 11}, + ReviewActivity: &StageTrackerActivity{Head: head, State: "unknown", PerspectivesTotal: 5}} + } + it := base() + stageTrackerApplyReworkOwedBy(&it) + if it.Rework.OwedBy != reworkOwedByHiveReviewer { + t.Fatalf("green pushed head: owed_by = %q, want %q", it.Rework.OwedBy, reworkOwedByHiveReviewer) + } + raw, _ := json.Marshal(it.Rework) + if !strings.Contains(string(raw), `"owed_by":"hive-reviewer"`) { + t.Fatalf("payload lacks owed_by: %s", raw) + } + + for name, mutate := range map[string]func(*StageTrackerItem){ + "red CI on the pushed head": func(it *StageTrackerItem) { it.CIActivity.State = "failing" }, + "findings on the pushed head": func(it *StageTrackerItem) { it.ReviewActivity.State = "changes_requested" }, + "conflict nobody in the hive rebases": func(it *StageTrackerItem) { it.Reason = "conflicting" }, + } { + it := base() + mutate(&it) + stageTrackerApplyReworkOwedBy(&it) + if it.Rework.OwedBy != reworkOwedByAuthor { + t.Fatalf("%s: owed_by = %q, want %q so the author keeps the pill", name, it.Rework.OwedBy, reworkOwedByAuthor) + } + } + // The hive rebasing the conflict is the hive's move. + it = base() + it.Reason, it.Rebase = "conflicting", &StageTrackerRebase{Attempt: 1, Max: 2} + stageTrackerApplyReworkOwedBy(&it) + if it.Rework.OwedBy != reworkOwedByHiveReviewer { + t.Fatalf("hive rebasing: owed_by = %q, want %q", it.Rework.OwedBy, reworkOwedByHiveReviewer) + } + // Red CI on an OLDER head says nothing about the pushed one. + it = base() + it.CIActivity = &StageTrackerActivity{Head: "6384f9b", State: "failing"} + stageTrackerApplyReworkOwedBy(&it) + if it.Rework.OwedBy != reworkOwedByHiveReviewer { + t.Fatalf("stale red CI: owed_by = %q, want %q", it.Rework.OwedBy, reworkOwedByHiveReviewer) + } + // Before the push the author owes the rework; nothing to attribute. + it = base() + it.Rework.State = reworkStateAcknowledged + stageTrackerApplyReworkOwedBy(&it) + if it.Rework.OwedBy != "" { + t.Fatalf("acknowledged: owed_by = %q, want empty", it.Rework.OwedBy) + } + var none *StageTrackerItem + stageTrackerApplyReworkOwedBy(none) + stageTrackerApplyReworkOwedBy(&StageTrackerItem{}) +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 19ec78f7e4..2ad454b870 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1391,7 +1391,7 @@ assert.deepStrictEqual(req.body, { decision: 'merge-now', comment: '', type: 'pr assert.deepStrictEqual(stageTrackerActionRequest(pr317, 'decide:queue-merge', {}).body, { decision: 'queue-merge', comment: '', type: 'pr' }); assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:merge-now'], 'Merging…'); assert.strictEqual(STAGE_TRACKER_ACTION_WORDS.merged, 'merged'); -assert.strictEqual(STAGE_TRACKER_ACTION_WORDS['queued-for-merge'], 'approved — hive will merge on the next tick once CI is green'); +assert.strictEqual(STAGE_TRACKER_ACTION_WORDS['queued-for-merge'], 'queued for merge — hive merges it on its next pass once CI is green'); assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:queue-merge'], 'Recording approval…'); assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:queue-merge'], 'Approve and let hive merge'); assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:merge-now'], 'Merge now as maintainer'); diff --git a/src/pkg/dashboard/stage_tracker_single_note.test.js b/src/pkg/dashboard/stage_tracker_single_note.test.js index 408c03f461..81c541de56 100644 --- a/src/pkg/dashboard/stage_tracker_single_note.test.js +++ b/src/pkg/dashboard/stage_tracker_single_note.test.js @@ -53,7 +53,7 @@ function load() { 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); + for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml', 'stageTrackerBasePillHtml']) 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); diff --git a/src/pkg/dashboard/stage_tracker_status_collection_test.go b/src/pkg/dashboard/stage_tracker_status_collection_test.go index 1c8daa6229..0f071ce61b 100644 --- a/src/pkg/dashboard/stage_tracker_status_collection_test.go +++ b/src/pkg/dashboard/stage_tracker_status_collection_test.go @@ -172,7 +172,7 @@ func TestStageTrackerRESTCommitStatusCollectionAndRequiredBinding(t *testing.T) staleChecks := time.Now().Add(-trackerActivityFreshWindow - time.Second) a.ObservedAt = &staleChecks got := stageTrackerCIActivity(pr, time.Now()) - if got.ObservedAt == nil || !got.ObservedAt.Equal(*a.StatusesObservedAt) || got.Active { + if got.ObservedAt == nil || !got.ObservedAt.Equal(*a.StatusesObservedAt) || got.Active != (got.State == "running" || got.State == "queued") { t.Fatalf("status freshness inherited the unrelated check snapshot: %+v", got) } } diff --git a/src/pkg/dashboard/stage_tracker_superseded_row_test.go b/src/pkg/dashboard/stage_tracker_superseded_row_test.go index ea4f3e6960..4ef9827c5f 100644 --- a/src/pkg/dashboard/stage_tracker_superseded_row_test.go +++ b/src/pkg/dashboard/stage_tracker_superseded_row_test.go @@ -192,7 +192,7 @@ func TestStageTrackerSupersededRowRatchetJS(t *testing.T) { const since = new Date(now - 3600000).toISOString(); const pr = (n, extra) => Object.assign({ repo: 'hivecommons/hive', number: n, kind: 'pr', title: 'dashboard: split stage_tracker.go into 4 files, a very long title that must ellipsize before the note does', url: 'https://x/' + n, stage: 74, stage_since: since, caption: 'Adopted', author: 'odttlnt', author_kind: 'clanker', modifiers: [] }, extra || {}); const issue = (n, prs, extra) => Object.assign({ repo: 'hivecommons/hive', number: n, kind: 'issue', title: 'Issue ' + n, url: 'https://x/i' + n, stage: 40, stage_since: since, linked_prs: prs }, extra || {}); -const copy = (n, from, extra) => pr(n, Object.assign({ author: 'hivecommons-hive[bot]', author_kind: 'hive', stage: 80, caption: 'Merge queued', adopted_from: { number: from, url: 'https://x/' + from, author: 'odttlnt', state: 'open', text: '↳ adopted from #' + from } }, extra || {})); +const copy = (n, from, extra) => pr(n, Object.assign({ author: 'hivecommons-hive[bot]', author_kind: 'hive', stage: 80, caption: 'Queued for merge', adopted_from: { number: from, url: 'https://x/' + from, author: 'odttlnt', state: 'open', text: '↳ adopted from #' + from } }, extra || {})); const noteOf = (sub) => (/]*>([^<]*)<\/span>/.exec(sub) || [])[1] || ''; const subsOf = (row) => row.split('
Array.from(s.matchAll(/
  • { + const lit = litChevrons(s); + if (lit > 1) assert.strictEqual(stageLitChevrons(s), 0, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' lights a stage chevron beside a running track: ' + s); + Array.from(s.matchAll(/
  • /g)).forEach(m => { + const words = ((/([\s\S]*?)<\/span>/.exec(m[0]) || [])[1] || '').replace(/<[^>]+>/g, ''); + assert.ok(!/\b(CI failing|CI \d+\/\d+|Changes requested)\b/.test(words), 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' stage chevron speaks a track verdict: ' + words); + }); +}; +// hivecommons/hive#16661: a CI / Review tooltip states what the track waits +// on; "activity unknown" / "CI unknown" / "Review unknown" never appear. +const neverActivityUnknown = (item, s, i) => Array.from(s.matchAll(/
  • /g)).forEach(m => { + const tip = ((/role="tooltip">([\s\S]*?)<\/span>/.exec(m[0]) || [])[1] || '').replace(/<[^>]+>/g, ''); + assert.ok(!/activity unknown|\b(?:CI|Review) unknown\b/.test(tip), 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' track tooltip says unknown: ' + tip); }); 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); + onlyTracksPair(item, s, i); 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); + neverActivityUnknown(item, s, i); }); const rawRowHtml = stageTrackerRowHtml; stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); const row = rawRowHtml(item, stages, ctx); atMostTwoLit(item, row); return row; }; diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 8a297d0ff5..8a751c50d5 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -264,7 +264,7 @@ assert.ok(tooltip(row).includes('Flags: needs-rebase, needs-human') && tooltip(r row = stageTrackerRowHtml({ repo: 'acme/console', number: 107, kind: 'pr', stage: 60 }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, D, 'active', T, 'todo cap'], '060 reviewed lights CI / Review, not the merge gate: ' + row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 109, kind: 'pr', stage: 80, caption: 'soak 20m left' }, stages, ctx); -assert.ok(row.includes('Ready for auto merge') && strip(row).includes('title="Awaiting merge admission — not yet admitted — soak 20m left · Next move: hive"'), 'chevron tooltip carries 080: ' + row); +assert.ok(row.includes('Queued for merge') && strip(row).includes('title="Awaiting merge admission — not yet admitted — soak 20m left · Next move: hive"'), 'chevron tooltip carries 080: ' + row); // PR regressed from the queue back to review-pending: Review lit, "Sent back" in the tooltip. row = stageTrackerRowHtml({ repo: 'acme/console', number: 103, kind: 'pr', stage: 70, modifiers: ['regressed', 'needs-rebase'], history: [{number:80,slug:'awaiting-merge-admission'},{number:100,slug:'merge-queue'},{number:70,slug:'fixing',from:100,regressed:true}] }, stages, ctx); @@ -332,7 +332,7 @@ assert.ok(row.includes('ham-mod-needs-decision">needs human decision') && assert.ok(row.includes('data-track="ci"') && row.includes('data-track="review"') && !row.includes('ham-actor-ico'), 'a native stage cannot identify the actual reviewer: ' + row); assert.ok(!row.includes('ham-author-ico ham-actor') && !row.includes('ham-actor-ico ham-author-'), 'actor icon must not carry the author colour classes: ' + row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 108, kind: 'pr', stage: 72, author_kind: 'clanker' }, stages, ctx); -assert.ok(row.includes('Review unknown') && row.includes('CI unknown'), 'legacy author waits do not fabricate observed activity: ' + row); +assert.ok(row.includes('Review · no data for head') && row.includes('CI · no data for head') && !row.includes('activity unknown'), 'legacy author waits do not fabricate observed activity: ' + row); // 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']); @@ -461,7 +461,15 @@ assert.ok(!row.includes('ham-issue-refs-chip'), 'closing link draws no refs chip row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', title: 'Tracker', stage: 40, claim_reference: true, is_tracker: true, children: { total: 3, completed: 1 }, linked_prs: [{ number: 203, title: 'Draft work', stage: 10, base_ref: 'v6' }] }, stages, ctx); assert.ok(row.includes('refs'), 'issue refs chip: ' + row); assert.ok(row.includes('tracker 1/3'), 'tracker progress: ' + row); -assert.ok(row.includes('v6'), 'covering PR base: ' + row); +// The base pill sits at the row head by the repo chip, before the issue #N, +// with the PR it describes in its tooltip — not in the PR column's cluster. +assert.ok(row.includes('v6'), 'covering PR base pill: ' + row); +assert.ok(row.indexOf('ham-base-pill') < row.indexOf('>#9'), 'base pill precedes the issue ref: ' + row); +assert.ok(!row.includes('v6'), 'base no longer a right-hand badge: ' + row); +assert.ok(!row.slice(row.indexOf('ham-head-pr'), row.indexOf('ham-since')).includes('>v6<'), 'base absent from the PR column: ' + row); +// No PR, no pill; a PR row carries its own base. +assert.ok(!stageTrackerRowHtml({ repo: 'acme/console', number: 10, kind: 'issue', title: 'Bare', stage: 10 }, stages, ctx).includes('ham-base-pill'), 'no PR → no base pill'); +assert.ok(stageTrackerRowHtml({ repo: 'acme/console', number: 204, kind: 'pr', title: 'Own row', stage: 60, base_ref: 'v5' }, stages, ctx).includes('v5'), 'PR row base pill'); // 040 shares the PR in progress column with 030; the chevron tooltip names the real stage. row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', title: 'Ordering drifts', stage: 40, linked_prs: [{ number: 103, title: 'Backport', author_kind: 'clanker', stage: 30 }, { number: 102, title: 'Fix it', url: 'u', author_kind: 'human', stage: 70, stage_since: new Date(now - 3600000).toISOString(), modifiers: ['needs-rebase'], caption: 'Rebasing onto main' }] }, stages, ctx); @@ -493,23 +501,24 @@ sr = subs(row); const cell = (head.match(/
  • ]*>([\s\S]*?)<\/li>/) || [])[1] || ''; assert.ok(cell, 'sub-row header has one PR cell: ' + head); assert.ok(!/v5')]; - assert.ok(order.every((i, k) => i >= 0 && (k === 0 || i > order[k - 1])), 'connector, PR link, lineage chip, base pill in that order as siblings: ' + cell); - assert.ok(cell.indexOf('v5') > cell.indexOf('', cell.indexOf('v5'), cell.indexOf(' i >= 0 && (k === 0 || i > order[k - 1])), 'connector, base pill, PR link, lineage chip in that order as siblings: ' + cell); + assert.ok(!cell.includes('v5'), 'the base is no longer a trailing badge: ' + cell); assert.ok(/]*title="docs: remove duplicate README run routes · /.test(cell), 'the PR link hover starts with the full title: ' + cell); 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 -// before the base pill, both after the PR link. +// after the PR link; the base pill leads the row by the repo chip instead. row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', title: 'One PR', stage: 40, linked_prs: [{ number: 15343, title: 'T', stage: 50, base_ref: 'v5', lineage: { kind: 'adopted', from_number: 15226 } }] }, stages, ctx); { const cell = prCell(row); - assert.ok(cell.indexOf('v5'), 'PR link, lineage, base pill: ' + cell); + assert.ok(cell.indexOf('v5'), 'PR link, lineage; no base pill in the PR cell: ' + cell); + assert.ok(row.indexOf('v5') < row.indexOf('>#9'), 'base pill ahead of the issue ref: ' + row); } // An incomplete lineage has no chip and must not add an extra separator. row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', title: 'Empty lineage', stage: 40, linked_prs: [{ number: 15343, title: 'T', stage: 50, base_ref: 'v5', lineage: { kind: 'adopted' } }] }, stages, ctx); -assert.match(prCell(row), /<\/a> v5<\/span>/, 'empty lineage leaves one separator before the base pill'); +assert.match(prCell(row), /<\/a>/, 'empty lineage leaves no stray separator after the PR link'); assert.ok(!prCell(row).includes('ham-lineage'), 'empty lineage renders no chip'); row = stageTrackerRowHtml({ repo: 'acme/console', number: 10, kind: 'issue', stage: 30 }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, 'active', T, T, 'todo cap'], 'kick running, no PR yet: the issue lights PR in progress and draws the steps ahead'); @@ -550,11 +559,11 @@ assert.deepStrictEqual(segStates(row), ['active', T, T, T, T, T, 'todo cap']); // is what the chevron says, the actor is whose move it is. The active // chevron now leads with its stage icon, so the regex skips that svg. const prWords = {}; -for (const [st, word, actor] of [[50, 'CI / Review', 'hive'], [60, 'Review passed', 'hive'], [70, 'Fixing', 'author'], [71, 'Needs author', 'author'], [72, 'Returned to contributor', 'author'], [74, 'Adopted by hive', 'hive'], [80, 'Ready for auto merge', 'hive'], [85, 'Needs human decision', 'human'], [90, 'Ready for human merge', 'human'], [100, 'Merging', 'hive']]) { +for (const [st, word, actor] of [[50, 'CI / Review', 'hive'], [60, 'Review passed', 'hive'], [70, 'Fixing', 'author'], [71, 'Needs author', 'author'], [72, 'Returned to contributor', 'author'], [74, 'Adopted by hive', 'hive'], [80, 'Queued for merge', 'hive'], [85, 'Needs human decision', 'human'], [90, 'Ready for human merge', 'human'], [100, 'Merging', 'hive']]) { const r = stageTrackerRowHtml({ repo: 'acme/console', number: 500 + st, kind: 'pr', stage: st, author_kind: 'clanker' }, stages, ctx); if ([50, 60, 70, 71, 72, 74].includes(st)) { assert.ok(r.includes('data-track="ci"') && r.includes('data-track="review"'), 'pre-gate tracks remain separate at ' + st); - assert.ok(r.includes('CI unknown') && r.includes('Review unknown'), 'legacy labels alone cannot supply activity at ' + st); + assert.ok(r.includes('CI · no data for head') && r.includes('Review · no data for head'), 'legacy labels alone cannot supply activity at ' + st); continue; } const m = /aria-current="step">]*>]*>[\s\S]*?<\/svg>([^<]*)<\/span><\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); @@ -651,9 +660,9 @@ expectTitles(row, ['a.ham-ref', 'span.ham-title', 'a.ham-pr-ref'], 'issue with o assert.ok(/]*title="The one PR Author: hive · @hive-bot · linked PR, shown on its issue's row"/.test(row), 'the PR link also explains the shared row: ' + row); // tracker-cues: with no agent on the item the chevron is static (waiting); // the pulse and the "Working now" lead need a worker in ctx.workers. -assert.ok(row.includes('CI unknown') && row.includes('Review unknown') && !strip(row).includes('data-motion='), 'a stage label alone supplies no activity: ' + row); +assert.ok(row.includes('CI · no data for head') && row.includes('Review · no data for head') && !strip(row).includes('data-motion='), 'a stage label alone supplies no activity: ' + row); row = stageTrackerRowHtml(g[1], stages, Object.assign({}, ctx, { workers: { 'g/r#21': { agent: 'scout', action: 'agent_comment_created', at: new Date(now - 120000).toISOString() } } })); -assert.ok(row.includes('Review unknown') && !strip(row).includes('data-motion='), 'a generic commenter is not a current-head reviewer: ' + row); +assert.ok(row.includes('Review · no data for head') && !strip(row).includes('data-motion='), 'a generic commenter is not a current-head reviewer: ' + row); assert.ok(/class="ham-row cue-working"/.test(row), 'the row carries the working cue: ' + row); assert.ok(!/
  • ]*title="Claimed"/.test(stageTrackerRowHtml(g[0], stages, ctx)), 'Claimed is static: no data-motion'); // Issue with two PRs: #N link + title on the issue line, nothing lit there; @@ -697,19 +706,19 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ // 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 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(/
  • ]*title="CI: CI 7\/11 · test not reported · /.test(three), 'unreported checks are the neutral icon, words in the tooltip: ' + three); + assert.ok(/
  • ]*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(/
  • ]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); - assert.ok(/
  • ]*title="CI: CI 7\/11 · test not reported · /.test(owner) && /
  • ]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict">]*>[\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); + assert.ok(/
  • ]*title="CI: CI 7\/11 · 'test' not reported · /.test(owner) && /
  • ]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict">]*>[\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 }, @@ -719,7 +728,7 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ // 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 }, + code_activity: { head: 'f269349', state: 'unassigned', caption: '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)); @@ -797,13 +806,13 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ 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(/
  • ]*data-motion="active"[^>]*>[\s\S]*?Review 2\/5 · in progress<\/span>/.test(progress), progress); - assert.ok(/
  • ]*>[\s\S]*?]*data-ring-done="7"[\s\S]*?<\/svg><\/span>]*>[\s\S]*?]*data-ring-done="7"[\s\S]*?<\/svg><\/span>]*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') && both.includes('Review 5/5 · adjudicating'), both); + assert.ok(both.includes('CI 4/11 · 7 running') && both.includes('Review 5/5 · adjudicating'), 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); diff --git a/src/pkg/dashboard/stage_tracker_unauthorized_test.go b/src/pkg/dashboard/stage_tracker_unauthorized_test.go index 2fd5d63a1f..4f57a14db2 100644 --- a/src/pkg/dashboard/stage_tracker_unauthorized_test.go +++ b/src/pkg/dashboard/stage_tracker_unauthorized_test.go @@ -31,11 +31,11 @@ func TestStageTrackerUnauthorizedFromReason(t *testing.T) { for _, tc := range []struct { name, reason, wantStep, wantTip string }{ - {name: "approve workflow runs", reason: approve, wantStep: "approve workflow runs", wantTip: "`actions: write`"}, + {name: "approve workflow runs", reason: approve, wantStep: "approve workflow runs", wantTip: "'actions: write'"}, {name: "human-approved suffix is stripped", reason: approve + ":human-approved@pat", wantStep: "approve workflow runs", wantTip: "Approve and run"}, - {name: "another step", reason: prstage.StageReasonUnauthorizedPrefix + "update-branch", wantStep: "update branch", wantTip: "permission to update branch"}, - {name: "label without a reason", reason: "contributor-lane:soaking(1h)", wantTip: "lacks a permission for the next step"}, - {name: "empty", reason: "", wantTip: "lacks a permission for the next step"}, + {name: "another step", reason: prstage.StageReasonUnauthorizedPrefix + "update-branch", wantStep: "update branch", wantTip: "permission needed to update branch"}, + {name: "label without a reason", reason: "contributor-lane:soaking(1h)", wantTip: "missing a permission needed for the next step"}, + {name: "empty", reason: "", wantTip: "missing a permission needed for the next step"}, } { t.Run(tc.name, func(t *testing.T) { step, tip := stageTrackerUnauthorized(tc.reason) @@ -63,7 +63,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { s.statusMu.Unlock() resp := s.buildStageTracker(s.status, store, now) it := trackerItem(t, resp, "pr", 130) - if it.Stage != 85 || !hasMod(it, modUnauthorized) || it.UnauthorizedStep != "approve workflow runs" || !strings.Contains(it.Unauthorized, "`actions: write`") { + 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.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" { @@ -73,7 +73,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { if err != nil { t.Fatal(err) } - if !strings.Contains(string(raw), `"unauthorized_step":"approve workflow runs"`) || !strings.Contains(string(raw), `"unauthorized":"The hive's GitHub App lacks`) { + if !strings.Contains(string(raw), `"unauthorized_step":"approve workflow runs"`) || !strings.Contains(string(raw), `"unauthorized":"The hive bot's GitHub App is missing`) { t.Fatalf("payload lacks the unauthorized fields: %s", raw) } if clean := trackerItem(t, resp, "pr", 101); clean.UnauthorizedStep != "" || clean.Unauthorized != "" || hasMod(clean, modUnauthorized) { @@ -118,15 +118,15 @@ func TestStageTrackerUnauthorizedJS(t *testing.T) { jsFunc(t, html, "stageTrackerChipsHtml"), jsFunc(t, html, "stageTrackerNeedsAttention"), }, "\n") + ` -const tip = "The hive's GitHub App lacks \u0060actions: write\u0060, so it cannot approve the workflow runs."; +const tip = "The hive bot's GitHub App is missing the 'actions: write' permission needed to approve the workflow runs."; const item = { kind: 'pr', stage: 85, modifiers: ['unauthorized'], unauthorized_step: 'approve workflow runs', unauthorized: tip }; const pill = stageTrackerChipsHtml(item); -assert.ok(pill.includes('ham-mod-unauthorized') && pill.includes('>unauthorized<'), pill); +assert.ok(pill.includes('ham-mod-unauthorized') && pill.includes('>hive bot lacks permission<'), pill); assert.ok(pill.includes('title="' + esc(tip) + '"'), pill); assert.ok(STAGE_TRACKER_HUMAN_MODS.includes('unauthorized') && STAGE_TRACKER_MOTION_HUMAN_MODS.includes('unauthorized')); assert.ok(stageTrackerNeedsAttention(item)); // unauthorized outranks the needs-* chips but yields to hold, a human instruction. -assert.ok(stageTrackerChipsHtml({ stage: 85, modifiers: ['needs-decision', 'unauthorized'] }).includes('>unauthorized +1<')); +assert.ok(stageTrackerChipsHtml({ stage: 85, modifiers: ['needs-decision', 'unauthorized'] }).includes('>hive bot lacks permission +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), 'Waiting for a maintainer · approve workflow runs on GitHub'); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 170584d39d..e44bef15fe 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -179,6 +179,8 @@ .ham-repo-tint-4 { --ham-repo-tint: var(--ham-repo-tint-4); } .ham-repo-tint-5 { --ham-repo-tint: var(--ham-repo-tint-5); } .ham-repo-chip.ham-repo-primary { --ham-repo-tint: var(--text-muted); } + /* The PR's base branch: same height and type as the repo chip it follows, muted border, no tint. */ + .ham-base-pill { flex: 0 0 auto; display: inline-block; font: inherit; font-family: var(--font-mono); font-size: var(--fs-2xs); line-height: 1.5; padding: 0 var(--sp-2); border-radius: var(--r-sm); border: var(--line-width) solid var(--line-subtle); color: var(--text-faint); white-space: nowrap; max-width: 9em; overflow: hidden; text-overflow: ellipsis; vertical-align: baseline; } .ham-pr-line { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; } /* Group-by-repo header row: sticky under the column header while its rows scroll, caret toggle, chip, owner/repo, counts, and a mini @@ -402,12 +404,14 @@ .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; } + /* A stalled blocker track (nothing moves; the row waits on a person + or a late check) is ACTIVE like any other text-bearing track: the one + bright amber fill (hivecommons/hive#16643 — "an active chevron has + exactly one fill"). It is still, not pulsing; the person glyph and + the tooltip say why. + Active-track fill invariant: no rule sets a background on + .ham-activity-track.active beyond .ham-seg.active. */ + .ham-seg.ham-activity-track.active.ham-stalled { 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, @@ -720,6 +724,7 @@ .merge-banner-ico { color: var(--green); font-weight: var(--fw-bold); } .merge-banner-head { font-weight: var(--fw-semibold); } .merge-banner-head .merge-banner-num { color: var(--amber); font-variant-numeric: tabular-nums; } + .merge-banner-head .merge-banner-by { font-weight: 500; } .merge-banner-text { margin-top: var(--sp-1); color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .merge-banner-links { margin-top: var(--sp-2); display: flex; gap: var(--sp-4); font-size: var(--fs-xs); } .merge-banner-links button, .merge-banner-links a { border: 0; padding: 0; background: transparent; color: var(--accent); cursor: pointer; font: inherit; text-decoration: none; } diff --git a/src/pkg/dashboard/static-src/html/tracker.html b/src/pkg/dashboard/static-src/html/tracker.html index d23229c213..7e2363a704 100644 --- a/src/pkg/dashboard/static-src/html/tracker.html +++ b/src/pkg/dashboard/static-src/html/tracker.html @@ -24,7 +24,7 @@

    Hive activity moni - + diff --git a/src/pkg/dashboard/static-src/js/agent-now.js b/src/pkg/dashboard/static-src/js/agent-now.js index c09df5ea3b..700418a59d 100644 --- a/src/pkg/dashboard/static-src/js/agent-now.js +++ b/src/pkg/dashboard/static-src/js/agent-now.js @@ -486,7 +486,7 @@ // "workflow-files" / "untrusted-author" / "branch-protection", falling // back to "policy"); the tooltip carries the payload's one-sentence // human_merge_reason_text (hivecommons/hive#14658). - const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; + const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'hive bot lacks permission', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; // 090 under the breaking-change rule (human_merge_reason // "breaking-change": a ⚠️ title or needs-owner-merge label, // hivecommons/hive#15442): no approval lets the hive merge it, so the diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 7752bc80bb..9dcb6f83e6 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -2105,7 +2105,7 @@ }; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', - merged: 'merged', 'queued-for-merge': 'approved — hive will merge on the next tick once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', + merged: 'merged', 'queued-for-merge': 'queued for merge — hive merges it on its next pass once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: 'no effect yet', }; diff --git a/src/pkg/dashboard/static-src/js/tracker-merged.js b/src/pkg/dashboard/static-src/js/tracker-merged.js index c0343bf2a9..ad841187e6 100644 --- a/src/pkg/dashboard/static-src/js/tracker-merged.js +++ b/src/pkg/dashboard/static-src/js/tracker-merged.js @@ -116,7 +116,11 @@ // no count — instead of letting the row vanish in silence. const closed = stageTrackerNewlyClosed(d, _stageTrackerMergeState, next, _stageTrackerPRItems, _stageTrackerClosedNoted); const closedItems = closed.map(k => prevItems[k] || _stageTrackerPRLast[k]); - closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete next[k]; delete _stageTrackerPRLast[k]; }); + // The closed key stays comparable (false), not deleted: a close the + // server later corrects to a merge — a bot's comment on a just-merged + // PR read as "closed" before the merge fact landed — still flips + // false → true and celebrates (hivecommons/hive#16658). + closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete _stageTrackerPRLast[k]; }); _stageTrackerMergeState = next; // A merged PR is no longer in this payload, so its last host survives. if (typeof stageTrackerPRHosts === 'function') Object.assign(_stageTrackerPRHost, stageTrackerPRHosts(d)); @@ -484,6 +488,30 @@ if (!by) return ''; return by === 'hive' ? 'by hive' : 'by @' + by; } + // Pure: the merger as the merge toast's head names them — "🐝 hive" + // for the hive's own merge, "@login" for anyone else, '' unknown. + function stageTrackerMergerText(by) { + by = String(by || '').trim(); + if (!by) return ''; + return by === 'hive' ? '🐝 hive' : '@' + by; + } + // Pure: who merged the PR at key, from the payload's terminal facts — + // recently_merged (audit + ledger, any merger) and the ledger's recent + // list — then the terminal fact this tab already holds. '' unknown. + function stageTrackerMergedByOf(key, d) { + const n = Number(String(key || '').slice(String(key || '').lastIndexOf('/pr#') + 4)) || 0; + const repo = String(key || '').slice(0, String(key || '').lastIndexOf('/pr#')).toLowerCase(); + if (!n || !repo) return ''; + const short = repo.slice(repo.lastIndexOf('/') + 1); + const ledger = d && d.merged && Array.isArray(d.merged.recent) ? d.merged.recent : []; + for (const m of (d && Array.isArray(d.recently_merged) ? d.recently_merged : []).concat(ledger)) { + if (!m || Number(m.number) !== n || !m.merged_by) continue; + const r = String(m.repo || '').toLowerCase(); + if (r === repo || (r.indexOf('/') < 0 && r === short)) return String(m.merged_by).trim(); + } + const fact = typeof _stageTrackerTerminalFacts !== 'undefined' && _stageTrackerTerminalFacts ? _stageTrackerTerminalFacts[key] : null; + return fact && fact.merged_by ? String(fact.merged_by).trim() : ''; + } // Pure: the popover's inner HTML. function stageTrackerMergedPopHtml(txt, nowMs) { const fmtAt = at => { if (!at) return ''; const d = new Date(at); const sameDay = stageTrackerLocalMidnight(at) === stageTrackerLocalMidnight(nowMs); const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; return sameDay ? hm : `${typeof formatDashboardDate === 'function' ? formatDashboardDate(d, { month: 'short', day: 'numeric' }) : d.toISOString().slice(5, 10)} ${hm}`; }; @@ -996,7 +1024,7 @@ const banner = stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); setTimeout(() => { const row = rowKey && el ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; - if (row) celebrateRow(row, { kind: 'merged', key, number, merged_by: fact && fact.merged_by }); + if (row) celebrateRow(row, { kind: 'merged', key, number, merged_by: (fact && fact.merged_by) || stageTrackerMergedByOf(key, typeof _stageTracker !== 'undefined' ? _stageTracker : null) }); else celebrateDetached(key, banner); }, i * STAGE_TRACKER_CELEBRATE_STAGGER_MS); }); @@ -1148,13 +1176,17 @@ const url = String(b.url || (b.pr && b.pr.url) || '').match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/\d+(?:[?#].*)?$/); return url ? url[1] : repo; } + // The head names the merger whoever they are — "#16644 merged by + // @clubanderson", "#16645 merged by 🐝 hive" — a merge by hand is + // celebrated exactly like the hive's own (hivecommons/hive#16658). function stageTrackerMergeBannerText(b, nowMs) { const d = new Date(b.at || nowMs); const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; const who = stageTrackerMergedByText(b.merged_by); + const merger = stageTrackerMergerText(b.merged_by); const paren = [b.lane || '', who, hm].filter(Boolean).join(', '); const num = stageTrackerMergeBannerNumber(b); - return { number: num, head: `${num ? '#' + num + ' ' : ''}merged${b.preview ? ' (test)' : ''}`, text: `${b.title || b.repo || ''}${paren ? ' (' + paren + ')' : ''}`.trim() }; + return { number: num, merger, head: `${num ? '#' + num + ' ' : ''}merged${merger ? ' by ' + merger : ''}${b.preview ? ' (test)' : ''}`, text: `${b.title || b.repo || ''}${paren ? ' (' + paren + ')' : ''}`.trim() }; } // Stateful: a persistent banner, bottom right, for one merge — stays // until dismissed or stageTrackerMergeBannerMs() (twice the info toast @@ -1170,6 +1202,7 @@ const repo = stageTrackerMergeBannerRepo(b); const recent = repo ? ((_stageTrackerMerged.server && _stageTrackerMerged.server.recent) || []).find(e => stageTrackerMergeBannerRepo(e).toLowerCase() === repo.toLowerCase() && stageTrackerMergeBannerNumber(e) === stageTrackerMergeBannerNumber(b)) : null; const info = Object.assign({ title: _stageTrackerPRTitle[b.key] || '', merged_by: '', lane: '', url: '' }, recent || {}, b, { repo }); + if (!info.merged_by && !b.preview) info.merged_by = stageTrackerMergedByOf(b.key, typeof _stageTracker !== 'undefined' ? _stageTracker : null); const num = stageTrackerMergeBannerNumber(info); const repoChip = stageTrackerRepoChipHtml(repo, { repoChips: { primary: stageTrackerPrimaryRepo(), active: _stageTrackerFilter.repo } }); // A live merge the ledger has not listed yet still links: the key carries owner/name. @@ -1179,7 +1212,7 @@ el.className = 'merge-banner'; el.setAttribute('role', 'status'); if (b.rowKey) el.setAttribute('data-ham-row', b.rowKey); - el.innerHTML = `
    ${repoChip ? repoChip + ' ' : ''}${num ? `#${esc(num)} ` : ''}merged${info.preview ? ' (test)' : ''}
    ${esc(t.text)}
    `; + el.innerHTML = `
    ${repoChip ? repoChip + ' ' : ''}${num ? `#${esc(num)} ` : ''}merged${t.merger ? ` by ${esc(t.merger)}` : ''}${info.preview ? ' (test)' : ''}
    ${esc(t.text)}
    `; box.appendChild(el); while (box.children.length > STAGE_TRACKER_MERGE_BANNER_MAX) { toastCountdownCancel(box.children[0]); box.children[0].remove(); } toastCountdownBar(el, stageTrackerMergeBannerMs(), () => stageTrackerMergeBannerDismiss(el)); 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 fe51617565..a9fdf2c3c9 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-acted.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-acted.js @@ -49,7 +49,7 @@ case 'applied': return 'done' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'no-op': return 'nothing changed' + (action.detail ? ': ' + stageTrackerActedPlain(action.detail) : ''); case 'failed': return 'failed' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); - case 'pending': return action.action === 'merge-now' ? 'rebasing, then merging…' : (action.action === 'queue-merge' ? 'approved — hive will merge on the next tick once CI is green' : 'the hive is deciding…'); + case 'pending': return action.action === 'merge-now' ? 'rebasing, then merging…' : (action.action === 'queue-merge' ? 'queued for merge — hive merges it on its next pass once CI is green' : 'the hive is deciding…'); case 'executing': return (action.detail ? stageTrackerActedPlain(action.detail) : 'decided — the hive is carrying it out…'); case 'no-effect': return "hasn't taken effect" + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'blocked': return 'blocked' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); 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 2e8f1fb7e3..b39b8b470c 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -220,9 +220,18 @@ ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; return stageTrackerLeadActionHtml(item, ctx, subRows); } - // PR link, then the lineage chip (null = none), then the base pill. - function stageTrackerPRPillsHtml(ref, lineage, baseRef) { - return ref + (lineage == null ? '' : ' ' + lineage) + (baseRef ? ` ${esc(baseRef)}` : ''); + // PR link, then the lineage chip (null = none). The base pill sits by + // the repo chip at the row's head (stageTrackerBasePillHtml), not here. + function stageTrackerPRPillsHtml(ref, lineage) { + return ref + (lineage == null ? '' : ' ' + lineage); + } + // Pure: the PR's base branch as a quiet sibling of the repo chip — + // `[hive][v5] #16603 …` — so the target reads with the repo, not in the + // right-hand modifier cluster. '' when the row has no PR (or no base). + function stageTrackerBasePillHtml(baseRef, prNumber) { + if (!baseRef) return ''; + const tip = (Number(prNumber) ? 'PR #' + Number(prNumber) + ' targets ' : 'Targets ') + baseRef; + return `${esc(baseRef)}`; } function stageTrackerSubRowHtml(lp, issue, stages, nowMs, ctx) { const pr = stageTrackerLinkedPRItem(issue, lp); @@ -234,9 +243,9 @@ // 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) : ''; + const chip = (ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : '') + stageTrackerBasePillHtml(lp.base_ref, pr.number); if (chip) ref = `${chip}${ref}`; - ref = stageTrackerPRPillsHtml(ref, !superseded && typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref); + ref = stageTrackerPRPillsHtml(ref, !superseded && typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null)); ref = STAGE_TRACKER_LINKED_GLYPH + ref; if (superseded) { // The adopted original: one muted line, no chevron track, no row 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 f555fcc5e2..9108c5ca79 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -93,9 +93,11 @@ const nowMs = Number(ctx.nowMs) || Date.now(); const isIssue = item.kind === 'issue'; const title = item.title || ''; - let prRefs = [], shown = item, range = null, subs = '', subRows = null, prTargetKey = ''; + let prRefs = [], shown = item, range = null, subs = '', subRows = null, prTargetKey = '', basePill = ''; if (isIssue) { const linked = stageTrackerLinkedSorted(item, stages); + // The primary (first-sorted) PR's base; an issue with no PR shows none. + if (linked.length) basePill = stageTrackerBasePillHtml(linked[0].base_ref, linked[0].number); if (linked.length === 1) { // One covering PR: a single entry whose strip the PR's stage drives. const lp = linked[0]; @@ -103,7 +105,7 @@ prTargetKey = stageTrackerItemKey(pr); const who = (lp.author_kind || 'hive') + (lp.author ? ' · @' + lp.author : ''); const lineage = (lp.lineage && typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(lp, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(lp, nowMs) : ''); - prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref)]; + prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null))]; const fin = lp.finisher ? lp : item; 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, @@ -131,8 +133,10 @@ // as one (hivecommons/hive#15232) — and the PR stays in the PR column // rather than taking the issue slot. A not-planned close adds a chip // saying the PR may be moot. - // The repo chip (when on) leads the row, before the issue slot's #N. - const chip = ctx.repoChips ? stageTrackerRepoChipHtml(item.repo, ctx) : ''; + // The repo chip (when on) leads the row, before the issue slot's #N; + // the PR's base pill follows it as a quieter sibling. + if (!isIssue) basePill = stageTrackerBasePillHtml(item.base_ref, item.number); + const chip = (ctx.repoChips ? stageTrackerRepoChipHtml(item.repo, ctx) : '') + basePill; let leadHtml; if (isIssue) { leadHtml = `
    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 bed5934905..fd757a4345 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -15,6 +15,15 @@ return ``; } + // The backend's word that the pushed head waits on the hive's own + // reviewer, not the author (`rework.owed_by`, hivecommons/hive#16615): + // the re-review is the hive's move, so the row is not parked on a + // person and the Review track reads "re-review of ". + function stageTrackerHiveOwesReReview(item) { + const r = item && item.rework; + return !!(r && r.state === 'pushed' && r.owed_by === 'hive-reviewer' && (!r.head || !item.head || r.head === item.head)); + } + // 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 @@ -28,7 +37,7 @@ 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)); + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head) || (typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))); 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; @@ -40,7 +49,7 @@ // 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 + // re-review of d88928e", "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. @@ -48,7 +57,7 @@ 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 ''; + if (state === 'unknown' && !current && !stageTrackerTrackRunning(item, kind)) return ''; const n = k => matches ? Number(a[k]) || 0 : 0; if (kind === 'ci') { const total = n('checks_total'); @@ -56,19 +65,36 @@ 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 ? ', …' : '') + ')' : '') : ''; + // A check name inside the words wears single quotes ('test' not + // reported) so it stands apart from the words around it. + const q = n => "'" + n + "'"; + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).map(q).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; const blocker = matches && a.blocker ? String(a.blocker) : ''; + // The unfinished count carries information; "no verdict yet" or a + // bare "running" beside 12/66 did not (hivecommons/hive#16630). The + // last one or two unfinished names are spelled out. + const pendingNames = matches && Array.isArray(a.checks_pending) ? a.checks_pending.map(String).filter(Boolean) : []; + const pendingCount = total ? Math.max(total - passed - failed, pendingNames.length) : pendingNames.length; + const pending = verb => !pendingCount ? verb : pendingNames.length && pendingNames.length <= STAGE_TRACKER_PENDING_CHECKS_NAMED ? pendingNames.map(q).join(', ') + ' ' + verb : pendingCount + ' ' + verb; 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 'failing': return count + ' · ' + (failing || 'failing' + (blocker ? ' (' + q(blocker) + ')' : '')); + case 'running': return count + ' · ' + pending('running') + (failing ? ' · ' + failing : ''); + case 'queued': return count + ' · ' + pending('queued') + (failing ? ' · ' + failing : ''); + case 'skipped': return count + ' · ' + (blocker ? q(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 : ''); + return count + ' · ' + (passed ? (blocker ? q(blocker) + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } + default: { + if (!total) return count + ' · no checks reported yet'; + if (failing) return count + ' · ' + failing + (pendingCount ? ' · ' + pending('running') : ''); + // A blocker here is a phrase ("commit statuses not observed") or + // the one check whose result cannot be read. + if (blocker) return count + ' · ' + (/\s/.test(blocker) ? blocker : q(blocker) + ' unclear'); + if (pendingCount) return count + ' · ' + pending('running'); + return count + ' · required set unknown'; } - default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } const total = n('perspectives_total'); @@ -77,7 +103,10 @@ 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)); + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head) || (typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))); + // "re-review of d88928e": the hive reviewer's owed pass, named by + // head so it never reads as the author's turn (hivecommons/hive#16615). + const reReview = 're-review of ' + String(item.head || '').slice(0, 7); switch (state) { case 'approved': return count + ' approved'; case 'changes_requested': return count + ' · changes requested'; @@ -98,7 +127,11 @@ 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'); + // Derived from the PR's own state when no reviewer has touched the + // head (stage_tracker_review_fallback.go): the words are the + // statement itself (hivecommons/hive#16661). + case 'waiting_ci': case 'not_started': case 'not_requested': case 'closed': case 'unverified': return a.caption || count; + default: return count + ' · ' + (newHead ? reReview : total && done ? 'perspectives' : 'queued'); } } @@ -108,6 +141,9 @@ // 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:'; + // Up to this many unfinished check names are spelled out in the CI + // chevron word; beyond it the count speaks (hivecommons/hive#16630). + const STAGE_TRACKER_PENDING_CHECKS_NAMED = 2; 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; @@ -207,7 +243,7 @@ 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; + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state)) && !(typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))) return true; const code = item.code_activity; return !!(code && code.head === item.head && code.state === 'waiting_owner'); } @@ -222,9 +258,23 @@ 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)); + if (a.active || moving.includes(a.state)) return true; + // A CI ring that is not full is a running ring: checks counted on + // the head but not yet passed or failed are still in motion unless + // the track has settled on a word of its own (a finding, a pass, a + // skip, an unreported required check, a person's decision) + // (hivecommons/hive#16631). + if (kind !== 'ci') return false; + // Inferred motion only; a row parked on a person's decision is not + // waiting on checks, whatever its cached counts say. + if ((item.decision_needed && item.decision_needed.question) || item.human_attention) return false; + const total = Number(a.checks_total) || 0, done = (Number(a.checks_passed) || 0) + (Number(a.checks_failed) || 0); + const settledWords = ['passing', 'failing', 'skipped', 'missing', 'human_decision']; + return total > 0 && done < total && !settledWords.includes(a.state); } + // Pure: "12m ago" beside a timestamp; "just now" under a minute. + function stageTrackerAgoWord(atMs, nowMs) { const mins = Math.floor((nowMs - atMs) / 60000); return !Number.isFinite(mins) || mins < 1 ? 'just now' : mins < 60 ? mins + 'm ago' : mins < 1440 ? Math.floor(mins / 60) + 'h ago' : Math.floor(mins / 1440) + 'd ago'; } // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. // The chevron wears its glyph plus the count words from @@ -240,16 +290,27 @@ const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; const matches = a && item.head && a.head === item.head; - let caption = matches ? a.caption || name + ' unknown' : name + ' unknown'; + // No evidence for the head is still a statement with a next step — + // never "activity unknown" (hivecommons/hive#16661). + const noData = name + ' · no data for head ' + (item.head ? String(item.head).slice(0, 7) : 'unknown') + ' yet · refreshing'; + let caption = matches ? a.caption || noData : noData; + // A legacy "CI unknown · reason" caption keeps its reason behind the statement. + caption = caption.replace(/^(CI|Review) unknown(?= ·|$)/, noData); const observed = matches && a.observed_at ? Date.parse(a.observed_at) : NaN; const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - 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; + // A settled verdict on the head stays known as its observation + // ages; only motion needs a fresh observation (hivecommons/hive#16617). + const settledState = ['approved', 'changes_requested', 'human_decision', 'passing', 'failing', 'skipped', 'missing', 'waiting_ci', 'not_started', 'not_requested', 'closed', 'unverified'].includes(state); + const fresh = Number.isFinite(observed) && !stale; + const known = matches && state !== 'unknown' && (settledState || fresh); + const active = known && fresh && a.active; + const perspectives = matches && kind === 'review' && Array.isArray(a.perspectives) ? a.perspectives : []; + const perspectiveMark = v => v === 'approve' ? '✓' : ['changes_requested', 'reject'].includes(v) ? '✗' : v === 'requires_human' ? 'requires human' : String(v || '?'); + const perspectiveLine = p => String(p.name || 'perspective') + ' ' + perspectiveMark(p.verdict) + (p.summary ? ': ' + p.summary : ''); 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'); @@ -272,23 +333,34 @@ 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 freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString() + ' (' + stageTrackerAgoWord(observed, clock) + ')'; const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; - 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 detail = matches && a.detail ? String(a.detail) : ''; + const sinceAgo = matches && a.since && Number.isFinite(Date.parse(a.since)) && settledState ? ' · ' + stageTrackerAgoWord(Date.parse(a.since), clock) : ''; + // Each fact once (hivecommons/hive#16630): the count word, then the + // caption unless the detail sentence already spells it out, then the + // blocker and the ask unless an earlier fact already names them. + const facts = []; + const say = fact => { if (fact && !facts.some(f => f.toLowerCase().includes(fact.toLowerCase()))) facts.push(fact); }; + say(text); + if (!(text && detail)) say(caption); + say(detail); + if (matches && a.blocker) say(String(a.blocker)); + say(ask); + let tip = facts.join(' · ') + sinceAgo + (perspectives.length ? ' · ' + perspectives.map(perspectiveLine).join(' · ') : '') + ' · 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 : ''; if (codeNote) tip += ' · code source ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown') + (code.blocker ? ' · ' + code.blocker : ''); - const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? sg.detour.text : ''; + // The detour's words ride along, minus the code lane's "activity unknown" + // (the Review tooltip states what is observed, hivecommons/hive#16661). + const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? String(sg.detour.text || '').replace(/ · activity unknown$/, ' · no fix work observed yet').replace(/^Code activity unknown$/, 'no code work observed yet') : ''; 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; @@ -310,7 +382,7 @@ const evidenceLink = ownsPR && evidenceURL ? `${icon}${word}` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; - const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + (text ? text + ' · ' : '') + tip + + const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + tip + (matches && a.actor ? ' · actor ' + a.actor : '') + (codeNote || contextWord ? ' · ' + (codeNote || contextWord) : '') + (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + @@ -377,11 +449,15 @@ 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). + // Activation resolution (hivecommons/hive#16643): CI and Review are + // resolved first. If either runs, the PR waits on it and nothing + // else is active — the stage chevron (PR in progress, Merge queue …) + // renders settled-current, icon only, its words in the tooltip, so + // CI + Review is the one pair that can be active together and every + // other row has exactly one active chevron. The stage chevron is the + // ≥ 1 fallback: active only when no track is in motion. const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; - const waitingOnTracks = tracksRunning === 2; + const waitingOnTracks = tracksRunning >= 1; 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 @@ -439,7 +515,7 @@ 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; + if (waitingOnTracks && !sg.cap) tip = (tracksRunning === 2 ? 'Waiting on CI and review, both running' : 'Waiting on ' + (stageTrackerTrackRunning(item, 'ci') ? 'CI' : 'review') + ', running') + ' — ' + tip; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -473,7 +549,9 @@ 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}${text}${actorIco || holderIco}`; + // Deferred to a running track: the icon alone (a decision trigger + // keeps its button, since the popover lives in the word). + const content = waitingOnTracks && !sg.cap && !decision ? stageTrackerIcon(sg.number, 'ham-ico') : `${gateCue}${workIco}${text}${actorIco || holderIco}`; // A decision's dialog is its sole hover/focus detail surface. inner = decision ? `${content}` : `${content}${esc(fullTip)}`; } else if (fixPushed) { @@ -520,13 +598,14 @@ const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { const a = item[kind + '_activity']; const name = kind === 'ci' ? 'CI' : 'Review'; - if (!a || a.head !== item.head) return name + ' unknown'; + const noData = name + ' · no data for head ' + String(item.head).slice(0, 7) + ' yet · refreshing'; + if (!a || a.head !== item.head) return noData; const observed = Date.parse(a.observed_at || ''); const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const fresh = Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - if ((a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state)) && !fresh) return name + ' activity unknown · last observed ' + (a.state || 'unknown'); - return (a.caption || name + ' unknown') + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · stale observation' : ''); + const moving = a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state); + return (a.caption || noData).replace(/^(CI|Review) unknown(?= ·|$)/, noData) + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · last observed ' + stageTrackerAgoWord(observed, clock) + (moving ? ' · refreshing' : '') : ''); }).join(' · ') : ''; return `

    ${esc(text + (tracks ? ' · ' + tracks : ''))}

    `; } @@ -649,7 +728,7 @@ if (item.sentinel_alert && deferred.indexOf(STAGE_TRACKER_SENTINEL_CHIP) < 0) lines.push(stageTrackerSentinelTip(item)); const regressed = stageTrackerRegressionText(item, nowMs); if (regressed) lines.push(regressed.charAt(0).toUpperCase() + regressed.slice(1)); - if (mods.indexOf('unauthorized') >= 0 && item.unauthorized) lines.push('Unauthorized: ' + item.unauthorized); + if (mods.indexOf('unauthorized') >= 0 && item.unauthorized) lines.push('Hive bot lacks permission: ' + item.unauthorized); if (mods.indexOf('hold') >= 0 && typeof stageTrackerHoldPill === 'function' && stageTrackerHoldPill(item)) lines.push(stageTrackerHoldPill(item)); if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); @@ -766,7 +845,7 @@ // The regressed pill (lead or folded into "+1") explains itself on // hover; failing that, a draft pill (lead or folded) does. const regressed = stageTrackerRegressionText(item, Date.now()); - // An unauthorized pill names the missing App permission and the human step; + // A hive-bot-lacks-permission pill names the missing App permission and the human step; // 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; diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index e88ebd5eb4..58eda1f01d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -109,7 +109,9 @@ } const STAGE_TRACKER_MOD_PRIORITY = ['stalled', 'regressed', 'hold', 'unauthorized', 'needs-human', 'needs-decision', 'needs-triage', 'possible-dupe', 'needs-rebase', 'blocked', 'draft']; - const STAGE_TRACKER_MOD_TEXT = { 'needs-decision': 'needs human decision', 'needs-triage': 'triage needed', 'possible-dupe': 'possible dupe' }; + // hive:unauthorized reads "hive bot lacks permission", never "unauthorized": the App + // installation is missing a permission, nobody did anything illegitimate (hivecommons/hive#16639). + const STAGE_TRACKER_MOD_TEXT = { 'needs-decision': 'needs human decision', 'needs-triage': 'triage needed', 'possible-dupe': 'possible dupe', unauthorized: 'hive bot lacks permission' }; // The draft pill and the Draft chevron explain themselves on hover: no // maintainer action is pending, the lanes resume when the author is ready. const STAGE_TRACKER_DRAFT_TIP = 'Draft PR — hive review and merge lanes skip drafts until the author marks it ready for review.'; @@ -290,8 +292,10 @@ if (!sa || (sa.kind !== STAGE_TRACKER_ACTOR_NONE && sa.kind !== 'bot')) return fallback; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; const external = sa.kind === STAGE_TRACKER_ACTOR_NONE && typeof stageTrackerExternalPRWork === 'function' ? stageTrackerExternalPRWork(item) : null; - if (external) return (mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'CI failing') + (external.owner ? ' · owner recorded' : (external.author ? ' · author-owned' : ' · owner unknown')); - const state = mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Red'; + // The red verdict is the CI / Review chevron's word; this lane says + // who owes the fix (hivecommons/hive#16643). + if (external) return (mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Fix owed') + (external.owner ? ' · owner recorded' : (external.author ? ' · author-owned' : ' · owner unknown')); + const state = mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Fix owed'; return state + (sa.kind === 'bot' ? ' · bot PR' : ' · nobody on it'); } 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 fa4bd49384..3034ed248f 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -165,7 +165,7 @@ // progress", "checks unreadable", "soak 30m // remaining"); drawn in CI / Review, since it // can still regress to 070 - // 080 Ready for auto merge — green and approved; waiting for hive's + // 080 Queued for merge — green and approved; waiting for hive's // merge pass: "next pass in 42s" // 095 Soaking — admitted; the soak window runs: "7m left" // 100 Merging — admitted and soaked; the merge is being @@ -175,14 +175,20 @@ // (stageTrackerGateCueHtml) says the same in a tooltip + aria-label. // STAGE_TRACKER_ACTIVE_WORD repeats the words literally (fixtures lift // it alone); stage_tracker_merge_gate_test.go pins the two equal. - const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Ready for auto merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; + // One word for every "nothing left but the merge itself" state + // (hivecommons/hive#16653): 080, a merge-train seat, a recorded + // approval and a retryable refusal all read "Queued for merge · " so three adjacent approved rows do not read three ways. + // Spelled out in each table (tests lift the lines one at a time); + // Go's stageTrackerQueuedForMergeWord is the same string. + const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Queued for merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; // merge_gate.merge_path (the merge call's issuer) in words (#15245). // A merge call (or a sweep's pass on a soaked PR) older than this says // "waiting for GitHub…" rather than spinning without a reason (#15808). const STAGE_TRACKER_MERGING_SLOW_MS = 60000; const STAGE_TRACKER_MERGE_PATH_WORDS = { sweep: 'automerge sweep', dashboard: 'maintainer merge from the dashboard', relay: 'hive-merge relay', forge: 'forge adapter', queue: 'merge queue' }; const STAGE_TRACKER_MERGE_FAILED_SHORT_MAX = 60; - const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Ready for auto merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; + const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Queued for merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; // Whose move it is on each lit chevron: 'author' = the PR's author kind, // 'claimant' = the live claim holder's kind; Open and Actionable carry none. const STAGE_TRACKER_ACTOR = { 15: 'human', 17: 'human', 20: 'claimant', 30: 'author', 40: 'author', 45: 'human', 50: 'hive', 60: 'hive', 70: 'author', 71: 'author', 72: 'author', 74: 'hive', 80: 'hive', 85: 'human', 90: 'human', 95: 'hive', 100: 'hive' }; @@ -240,13 +246,15 @@ return `${esc(label)}${STAGE_TRACKER_TRAIN_ICON_PATH}`; } // Pure: ordinal place words — "1st", "2nd", "3rd", "4th", "11th", - // "21st" (the owner's wording for the queue: "Merge queued · 1st"). + // "21st" (the queue word: "Queued for merge · 1st of 3"). // Every merge_train / merge_gate train state in words. A slug reaches a // chip only through this table (or stageTrackerTrainWord), never raw: // hive's own #15406 once read "front" (hivecommons/hive#15395). - // Both queue states read "Merge queued"; the place ("· 1st", "· 2nd") - // is what tells them apart — the owner could not parse "queued-behind". - const STAGE_TRACKER_TRAIN_STATE_WORD = { front: 'Merge queued', 'queued-behind': 'Merge queued', rebasing: 'Rebasing', 'rebase-exhausted': 'Needs human decision', 'duplicate-of': 'Duplicate of' }; + // Both queue states read "Queued for merge" — the same word as a + // queued PR off a train (hivecommons/hive#16653); the place ("· 1st of + // 3", "· 2nd of 3") is what tells them apart — the owner could not + // parse "queued-behind". + const STAGE_TRACKER_TRAIN_STATE_WORD = { front: 'Queued for merge', 'queued-behind': 'Queued for merge', rebasing: 'Rebasing', 'rebase-exhausted': 'Needs human decision', 'duplicate-of': 'Duplicate of' }; // merge_gate.state of a PR the queue holds because another open PR // fixes the same issue: "duplicate-of:15402" (merge_gate.duplicate_of // / duplicate_issue carry the numbers). @@ -314,9 +322,12 @@ // The blocker headline for a provisional train member, by stage — // the same words the stage column shows (stageTrackerShort in Go), so // the chevron and the caption name one blocker (hive's own #15577 read - // "Merge queued · 1st" while its caption said "check build-and-test + // "Queued for merge · 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: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + // 080 flagged provisional by the server (the slot is held ahead of + // readiness) reads the pre-admission word, never "Queued for merge · + // queued 1st once ready" (hivecommons/hive#16653). + 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', 80: 'Review passed' }; // 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. @@ -448,7 +459,7 @@ return STAGE_TRACKER_TRAIN_STALLED_LEAD + what + (dur ? ' · ' + dur : ''); } // The chevron word for a train member ('' for a row not in a train). - // The queued word is the place with the queue length — "Merge queued + // The queued word is the place with the queue length — "Queued for merge // · 2nd of 3" — so it reads the same with the merge sweep on or off // (#15395); never the state slug, never "front" or "queued-behind", // and never '' for a state this table does not know: an unmapped slug 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 4ac06300e8..a6b21c092b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -259,7 +259,10 @@ } // Pure: the merge-failed pill. A refusal because required checks have // not reported is not a failure — the sweep called too early — so the - // chip reads "Waiting for CI · 4 checks"; a sweep retrying now reads + // chip reads "Queued for merge · after CI" (the check count rides the + // hover, the chip stays ≤ 5 words); a moved head or + // a pending protection rule reads "Queued for merge · needs rebase" / + // "· branch protection pending"; a sweep retrying now reads // "Merge failed · retrying"; otherwise "Merge failed · ". // The chip is a fixed short phrase (≤ 5 words); the tooltip carries the // plain sentence and GitHub's raw text after "Details:". @@ -277,13 +280,21 @@ const details = why ? ' Details: ' + why : ''; if (kind === 'checks-pending') { const tip = 'hive tried to merge this' + when + ' before its required checks had reported — ' + (text || "required checks haven't finished") + '. It merges once they pass' + (mg.sweep_running ? '; hive is on it now' : (nextWords ? ' (' + nextWords + ')' : '')) + '.' + lastSeen + details; - return { state, word: 'Waiting for CI', detail: checks > 0 ? checks + ' check' + (checks === 1 ? '' : 's') : '', tip, cue: mg.sweep_running ? 'running' : 'waiting', until: 0 }; + return { state, word: 'Queued for merge', detail: 'after CI', tip, cue: mg.sweep_running ? 'running' : 'waiting', until: 0 }; } const word = STAGE_TRACKER_MERGE_GATE_WORD[state]; const sentence = 'hive tried to merge this' + when + ' and GitHub refused' + (text ? ' — ' + text : '') + '.'; if (mg.sweep_running) { return { state, word, detail: 'retrying', tip: sentence + ' hive is retrying it now.' + lastSeen + details, cue: 'running', until: 0 }; } + // Refusals the lane clears on its own next pass (the head moved, a + // protection rule still has something pending) are not failures the + // reader must fix: the chip stays "Queued for merge · " + // (hivecommons/hive#16653); the hover still says GitHub refused. + const queuedDetail = { 'head-moved': 'needs rebase', protection: 'branch protection pending' }[kind]; + if (queuedDetail) { + return { state, word: 'Queued for merge', detail: queuedDetail, tip: sentence + ' Still queued: the lane retries it on its next pass' + (nextWords ? ' (' + nextWords + ')' : '') + '.' + lastSeen + details, cue: 'waiting', until: 0 }; + } return { state, word, detail: STAGE_TRACKER_MERGE_REFUSAL_DETAIL[kind] || 'GitHub refused', tip: sentence + ' The lane re-evaluates it on its next pass' + (nextWords ? ' (' + nextWords + ')' : '') + '.' + lastSeen + details, cue: 'waiting', until: 0 }; } // Pure: the hover note for a refusal that belongs to an earlier head @@ -309,7 +320,7 @@ if (!line) return 'GitHub refused the merge'; return line.length > STAGE_TRACKER_MERGE_FAILED_SHORT_MAX ? line.slice(0, STAGE_TRACKER_MERGE_FAILED_SHORT_MAX - 1).trimEnd() + '…' : line; } - // Pure: the pill word with its live detail — "Ready for auto merge · + // Pure: the pill word with its live detail — "Queued for merge · // next pass in 42s". The detail span carries data-ham-until so the // countdown ticks in place. function stageTrackerMergeGateWordHtml(item, nowMs, trains) { 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 2a43790182..da0783efb4 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-stage.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-stage.js @@ -62,7 +62,7 @@ const STAGE_TRACKER_NEEDS_HUMAN_STAGES = [15, 45, 85, 90]; const STAGE_TRACKER_NEEDS_HUMAN_AUTHOR_STAGES = [71, 72]; const STAGE_TRACKER_NEEDS_HUMAN_MODS = ['needs-human', 'needs-decision', 'unauthorized']; - const STAGE_TRACKER_NEEDS_HUMAN_TIP = 'Only a person can move these: triage needed, needs decision, human author must act, human merge, or a needs-human / unauthorized pill'; + const STAGE_TRACKER_NEEDS_HUMAN_TIP = 'Only a person can move these: triage needed, needs decision, human author must act, human merge, or a needs-human / hive-bot-lacks-permission pill'; const STAGE_TRACKER_ON_HOLD_TIP = 'Paused on purpose with a hold label — waiting on nobody; remove the hold to resume'; // Label families a chip row is built from, in display order; other // labels follow when at least two items carry them. diff --git a/src/pkg/dashboard/static-src/js/tracker-words.js b/src/pkg/dashboard/static-src/js/tracker-words.js index d94d7d5f2b..ec9db5498c 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words.js +++ b/src/pkg/dashboard/static-src/js/tracker-words.js @@ -81,6 +81,7 @@ } } // Guarded: the test harnesses load helpers by name. + if (typeof stageTrackerHiveReviewerChipText === 'function' && stageTrackerHiveReviewerChipText(item)) return stageTrackerHiveReviewerChipText(item); const text = 'waiting on ' + (a.author ? '@' + a.author : 'author'); return typeof stageTrackerReworkSuffix === 'function' ? stageTrackerReworkSuffix(text, item) : text; } @@ -202,8 +203,10 @@ // Pill text with the indicator placed just before the @login (or // leading, when the text names nobody): "waiting on [robot ●] @hanthor". function stageTrackerPresenceInPillHtml(item, text) { - const dot = stageTrackerPresenceDotHtml(item, Date.now()); const t = String(text || ''); + // The hive's own turn: no author presence glyph on the pill. + if (typeof stageTrackerReReviewOwedByHive === 'function' && stageTrackerReReviewOwedByHive(item)) return esc(t); + const dot = stageTrackerPresenceDotHtml(item, Date.now()); if (!dot) return esc(t); const i = t.indexOf('@'); if (i < 0) return dot + esc(t); @@ -217,6 +220,8 @@ function stageTrackerPresenceChipText(item) { const p = stageTrackerPresenceOf(item); if (!p) return ''; + // Guarded: the test harnesses load helpers by name. + if (typeof stageTrackerHiveReviewerChipText === 'function' && stageTrackerHiveReviewerChipText(item)) return stageTrackerHiveReviewerChipText(item); const ownPR = item && item.kind === 'pr' && item.author_kind === 'human' && p.kind === 'human' && String(item.author || '').toLowerCase() === String(p.login).toLowerCase(); const text = 'waiting on @' + p.login + (ownPR ? ' to push' : ''); // Guarded: the test harnesses load helpers by name. @@ -340,6 +345,35 @@ if (r.state === 'requested' && r.evidence === 'queued') return 'queued'; return STAGE_TRACKER_REWORK_WORDS[r.state]; } + // "re-review pending" means the HIVE's reviewer owes a pass on the new + // head, not the author (hivecommons/hive#16615: "are we waiting on the + // clanker or are we in CI?"). The backend says so with + // `rework.owed_by: "hive-reviewer"` once the pushed head carries + // nothing the author must fix (red CI, findings, a conflict nobody + // rebases) and "author" while it does; older payloads without the + // field are read the same way from the activities. + const STAGE_TRACKER_REWORK_OWED_BY_HIVE = 'hive-reviewer'; + function stageTrackerReReviewOwedByHive(item) { + const r = stageTrackerReworkOf(item); + if (!r || r.state !== 'pushed') return false; + if (r.owed_by) return r.owed_by === STAGE_TRACKER_REWORK_OWED_BY_HIVE; + const on = k => { const a = item[k + '_activity']; return a && (!a.head || !item.head || a.head === item.head) ? a.state || 'unknown' : 'unknown'; }; + if (on('ci') === 'failing' || on('review') === 'changes_requested') return false; + if (/conflict/i.test(String(item.reason || '')) && !item.rebase) return false; + return true; + } + // "re-review of d88928e" — the owed pass, named by head. + function stageTrackerReReviewWord(item) { + const r = stageTrackerReworkOf(item); + const sha = String((r && r.head) || item.head || '').slice(0, 7); + return 're-review' + (sha ? ' of ' + sha : ' pending'); + } + // "waiting on 🐝 hive reviewer · re-review of d88928e"; '' when the + // author still owes the next move. + function stageTrackerHiveReviewerChipText(item) { + if (!stageTrackerReReviewOwedByHive(item)) return ''; + return 'waiting on 🐝 hive reviewer · ' + stageTrackerReReviewWord(item); + } // "waiting on @x · acknowledged" — the pill text with the pickup word. function stageTrackerReworkSuffix(text, item) { const w = stageTrackerReworkWord(item); @@ -358,7 +392,7 @@ const since = when(r.since); switch (r.state) { case 'pushed': - return who + ' pushed a new head' + (since ? ' ' + since : '') + ' · re-review pending'; + return who + ' pushed a new head' + (since ? ' ' + since : '') + (stageTrackerReReviewOwedByHive(item) ? ' · hive reviewer owes the ' + stageTrackerReReviewWord(item) : ' · re-review pending'); case 'in_progress': return who + "'s clanker picked up the rework" + (since ? ' ' + since : '') + (r.mode ? ' (' + r.mode + ')' : ''); case 'acknowledged': diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index d00e700155..ca979f1c1a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1521,6 +1521,8 @@ .ham-repo-tint-4 { --ham-repo-tint: var(--ham-repo-tint-4); } .ham-repo-tint-5 { --ham-repo-tint: var(--ham-repo-tint-5); } .ham-repo-chip.ham-repo-primary { --ham-repo-tint: var(--text-muted); } + /* The PR's base branch: same height and type as the repo chip it follows, muted border, no tint. */ + .ham-base-pill { flex: 0 0 auto; display: inline-block; font: inherit; font-family: var(--font-mono); font-size: var(--fs-2xs); line-height: 1.5; padding: 0 var(--sp-2); border-radius: var(--r-sm); border: var(--line-width) solid var(--line-subtle); color: var(--text-faint); white-space: nowrap; max-width: 9em; overflow: hidden; text-overflow: ellipsis; vertical-align: baseline; } .ham-pr-line { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; } /* Group-by-repo header row: sticky under the column header while its rows scroll, caret toggle, chip, owner/repo, counts, and a mini @@ -1744,12 +1746,14 @@ .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; } + /* A stalled blocker track (nothing moves; the row waits on a person + or a late check) is ACTIVE like any other text-bearing track: the one + bright amber fill (hivecommons/hive#16643 — "an active chevron has + exactly one fill"). It is still, not pulsing; the person glyph and + the tooltip say why. + Active-track fill invariant: no rule sets a background on + .ham-activity-track.active beyond .ham-seg.active. */ + .ham-seg.ham-activity-track.active.ham-stalled { 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, @@ -2062,6 +2066,7 @@ .merge-banner-ico { color: var(--green); font-weight: var(--fw-bold); } .merge-banner-head { font-weight: var(--fw-semibold); } .merge-banner-head .merge-banner-num { color: var(--amber); font-variant-numeric: tabular-nums; } + .merge-banner-head .merge-banner-by { font-weight: 500; } .merge-banner-text { margin-top: var(--sp-1); color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .merge-banner-links { margin-top: var(--sp-2); display: flex; gap: var(--sp-4); font-size: var(--fs-xs); } .merge-banner-links button, .merge-banner-links a { border: 0; padding: 0; background: transparent; color: var(--accent); cursor: pointer; font: inherit; text-decoration: none; } @@ -8733,7 +8738,7 @@

    Hive activity moni - + @@ -15827,7 +15832,7 @@

    Where to get help

    // "workflow-files" / "untrusted-author" / "branch-protection", falling // back to "policy"); the tooltip carries the payload's one-sentence // human_merge_reason_text (hivecommons/hive#14658). - const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; + const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'hive bot lacks permission', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; // 090 under the breaking-change rule (human_merge_reason // "breaking-change": a ⚠️ title or needs-owner-merge label, // hivecommons/hive#15442): no approval lets the hive merge it, so the @@ -16002,7 +16007,7 @@

    Where to get help

    // progress", "checks unreadable", "soak 30m // remaining"); drawn in CI / Review, since it // can still regress to 070 - // 080 Ready for auto merge — green and approved; waiting for hive's + // 080 Queued for merge — green and approved; waiting for hive's // merge pass: "next pass in 42s" // 095 Soaking — admitted; the soak window runs: "7m left" // 100 Merging — admitted and soaked; the merge is being @@ -16012,14 +16017,20 @@

    Where to get help

    // (stageTrackerGateCueHtml) says the same in a tooltip + aria-label. // STAGE_TRACKER_ACTIVE_WORD repeats the words literally (fixtures lift // it alone); stage_tracker_merge_gate_test.go pins the two equal. - const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Ready for auto merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; + // One word for every "nothing left but the merge itself" state + // (hivecommons/hive#16653): 080, a merge-train seat, a recorded + // approval and a retryable refusal all read "Queued for merge · " so three adjacent approved rows do not read three ways. + // Spelled out in each table (tests lift the lines one at a time); + // Go's stageTrackerQueuedForMergeWord is the same string. + const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Queued for merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; // merge_gate.merge_path (the merge call's issuer) in words (#15245). // A merge call (or a sweep's pass on a soaked PR) older than this says // "waiting for GitHub…" rather than spinning without a reason (#15808). const STAGE_TRACKER_MERGING_SLOW_MS = 60000; const STAGE_TRACKER_MERGE_PATH_WORDS = { sweep: 'automerge sweep', dashboard: 'maintainer merge from the dashboard', relay: 'hive-merge relay', forge: 'forge adapter', queue: 'merge queue' }; const STAGE_TRACKER_MERGE_FAILED_SHORT_MAX = 60; - const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Ready for auto merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; + const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Queued for merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; // Whose move it is on each lit chevron: 'author' = the PR's author kind, // 'claimant' = the live claim holder's kind; Open and Actionable carry none. const STAGE_TRACKER_ACTOR = { 15: 'human', 17: 'human', 20: 'claimant', 30: 'author', 40: 'author', 45: 'human', 50: 'hive', 60: 'hive', 70: 'author', 71: 'author', 72: 'author', 74: 'hive', 80: 'hive', 85: 'human', 90: 'human', 95: 'hive', 100: 'hive' }; @@ -16077,13 +16088,15 @@

    Where to get help

    return `${esc(label)}${STAGE_TRACKER_TRAIN_ICON_PATH}`; } // Pure: ordinal place words — "1st", "2nd", "3rd", "4th", "11th", - // "21st" (the owner's wording for the queue: "Merge queued · 1st"). + // "21st" (the queue word: "Queued for merge · 1st of 3"). // Every merge_train / merge_gate train state in words. A slug reaches a // chip only through this table (or stageTrackerTrainWord), never raw: // hive's own #15406 once read "front" (hivecommons/hive#15395). - // Both queue states read "Merge queued"; the place ("· 1st", "· 2nd") - // is what tells them apart — the owner could not parse "queued-behind". - const STAGE_TRACKER_TRAIN_STATE_WORD = { front: 'Merge queued', 'queued-behind': 'Merge queued', rebasing: 'Rebasing', 'rebase-exhausted': 'Needs human decision', 'duplicate-of': 'Duplicate of' }; + // Both queue states read "Queued for merge" — the same word as a + // queued PR off a train (hivecommons/hive#16653); the place ("· 1st of + // 3", "· 2nd of 3") is what tells them apart — the owner could not + // parse "queued-behind". + const STAGE_TRACKER_TRAIN_STATE_WORD = { front: 'Queued for merge', 'queued-behind': 'Queued for merge', rebasing: 'Rebasing', 'rebase-exhausted': 'Needs human decision', 'duplicate-of': 'Duplicate of' }; // merge_gate.state of a PR the queue holds because another open PR // fixes the same issue: "duplicate-of:15402" (merge_gate.duplicate_of // / duplicate_issue carry the numbers). @@ -16151,9 +16164,12 @@

    Where to get help

    // The blocker headline for a provisional train member, by stage — // the same words the stage column shows (stageTrackerShort in Go), so // the chevron and the caption name one blocker (hive's own #15577 read - // "Merge queued · 1st" while its caption said "check build-and-test + // "Queued for merge · 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: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + // 080 flagged provisional by the server (the slot is held ahead of + // readiness) reads the pre-admission word, never "Queued for merge · + // queued 1st once ready" (hivecommons/hive#16653). + 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', 80: 'Review passed' }; // 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. @@ -16285,7 +16301,7 @@

    Where to get help

    return STAGE_TRACKER_TRAIN_STALLED_LEAD + what + (dur ? ' · ' + dur : ''); } // The chevron word for a train member ('' for a row not in a train). - // The queued word is the place with the queue length — "Merge queued + // The queued word is the place with the queue length — "Queued for merge // · 2nd of 3" — so it reads the same with the merge sweep on or off // (#15395); never the state slug, never "front" or "queued-behind", // and never '' for a state this table does not know: an unmapped slug @@ -16706,7 +16722,7 @@

    Where to get help

    const STAGE_TRACKER_NEEDS_HUMAN_STAGES = [15, 45, 85, 90]; const STAGE_TRACKER_NEEDS_HUMAN_AUTHOR_STAGES = [71, 72]; const STAGE_TRACKER_NEEDS_HUMAN_MODS = ['needs-human', 'needs-decision', 'unauthorized']; - const STAGE_TRACKER_NEEDS_HUMAN_TIP = 'Only a person can move these: triage needed, needs decision, human author must act, human merge, or a needs-human / unauthorized pill'; + const STAGE_TRACKER_NEEDS_HUMAN_TIP = 'Only a person can move these: triage needed, needs decision, human author must act, human merge, or a needs-human / hive-bot-lacks-permission pill'; const STAGE_TRACKER_ON_HOLD_TIP = 'Paused on purpose with a hold label — waiting on nobody; remove the hold to resume'; // Label families a chip row is built from, in display order; other // labels follow when at least two items carry them. @@ -17158,7 +17174,10 @@

    Where to get help

    } // Pure: the merge-failed pill. A refusal because required checks have // not reported is not a failure — the sweep called too early — so the - // chip reads "Waiting for CI · 4 checks"; a sweep retrying now reads + // chip reads "Queued for merge · after CI" (the check count rides the + // hover, the chip stays ≤ 5 words); a moved head or + // a pending protection rule reads "Queued for merge · needs rebase" / + // "· branch protection pending"; a sweep retrying now reads // "Merge failed · retrying"; otherwise "Merge failed · ". // The chip is a fixed short phrase (≤ 5 words); the tooltip carries the // plain sentence and GitHub's raw text after "Details:". @@ -17176,13 +17195,21 @@

    Where to get help

    const details = why ? ' Details: ' + why : ''; if (kind === 'checks-pending') { const tip = 'hive tried to merge this' + when + ' before its required checks had reported — ' + (text || "required checks haven't finished") + '. It merges once they pass' + (mg.sweep_running ? '; hive is on it now' : (nextWords ? ' (' + nextWords + ')' : '')) + '.' + lastSeen + details; - return { state, word: 'Waiting for CI', detail: checks > 0 ? checks + ' check' + (checks === 1 ? '' : 's') : '', tip, cue: mg.sweep_running ? 'running' : 'waiting', until: 0 }; + return { state, word: 'Queued for merge', detail: 'after CI', tip, cue: mg.sweep_running ? 'running' : 'waiting', until: 0 }; } const word = STAGE_TRACKER_MERGE_GATE_WORD[state]; const sentence = 'hive tried to merge this' + when + ' and GitHub refused' + (text ? ' — ' + text : '') + '.'; if (mg.sweep_running) { return { state, word, detail: 'retrying', tip: sentence + ' hive is retrying it now.' + lastSeen + details, cue: 'running', until: 0 }; } + // Refusals the lane clears on its own next pass (the head moved, a + // protection rule still has something pending) are not failures the + // reader must fix: the chip stays "Queued for merge · " + // (hivecommons/hive#16653); the hover still says GitHub refused. + const queuedDetail = { 'head-moved': 'needs rebase', protection: 'branch protection pending' }[kind]; + if (queuedDetail) { + return { state, word: 'Queued for merge', detail: queuedDetail, tip: sentence + ' Still queued: the lane retries it on its next pass' + (nextWords ? ' (' + nextWords + ')' : '') + '.' + lastSeen + details, cue: 'waiting', until: 0 }; + } return { state, word, detail: STAGE_TRACKER_MERGE_REFUSAL_DETAIL[kind] || 'GitHub refused', tip: sentence + ' The lane re-evaluates it on its next pass' + (nextWords ? ' (' + nextWords + ')' : '') + '.' + lastSeen + details, cue: 'waiting', until: 0 }; } // Pure: the hover note for a refusal that belongs to an earlier head @@ -17208,7 +17235,7 @@

    Where to get help

    if (!line) return 'GitHub refused the merge'; return line.length > STAGE_TRACKER_MERGE_FAILED_SHORT_MAX ? line.slice(0, STAGE_TRACKER_MERGE_FAILED_SHORT_MAX - 1).trimEnd() + '…' : line; } - // Pure: the pill word with its live detail — "Ready for auto merge · + // Pure: the pill word with its live detail — "Queued for merge · // next pass in 42s". The detail span carries data-ham-until so the // countdown ticks in place. function stageTrackerMergeGateWordHtml(item, nowMs, trains) { @@ -17443,6 +17470,7 @@

    Where to get help

    } } // Guarded: the test harnesses load helpers by name. + if (typeof stageTrackerHiveReviewerChipText === 'function' && stageTrackerHiveReviewerChipText(item)) return stageTrackerHiveReviewerChipText(item); const text = 'waiting on ' + (a.author ? '@' + a.author : 'author'); return typeof stageTrackerReworkSuffix === 'function' ? stageTrackerReworkSuffix(text, item) : text; } @@ -17564,8 +17592,10 @@

    Where to get help

    // Pill text with the indicator placed just before the @login (or // leading, when the text names nobody): "waiting on [robot ●] @hanthor". function stageTrackerPresenceInPillHtml(item, text) { - const dot = stageTrackerPresenceDotHtml(item, Date.now()); const t = String(text || ''); + // The hive's own turn: no author presence glyph on the pill. + if (typeof stageTrackerReReviewOwedByHive === 'function' && stageTrackerReReviewOwedByHive(item)) return esc(t); + const dot = stageTrackerPresenceDotHtml(item, Date.now()); if (!dot) return esc(t); const i = t.indexOf('@'); if (i < 0) return dot + esc(t); @@ -17579,6 +17609,8 @@

    Where to get help

    function stageTrackerPresenceChipText(item) { const p = stageTrackerPresenceOf(item); if (!p) return ''; + // Guarded: the test harnesses load helpers by name. + if (typeof stageTrackerHiveReviewerChipText === 'function' && stageTrackerHiveReviewerChipText(item)) return stageTrackerHiveReviewerChipText(item); const ownPR = item && item.kind === 'pr' && item.author_kind === 'human' && p.kind === 'human' && String(item.author || '').toLowerCase() === String(p.login).toLowerCase(); const text = 'waiting on @' + p.login + (ownPR ? ' to push' : ''); // Guarded: the test harnesses load helpers by name. @@ -17702,6 +17734,35 @@

    Where to get help

    if (r.state === 'requested' && r.evidence === 'queued') return 'queued'; return STAGE_TRACKER_REWORK_WORDS[r.state]; } + // "re-review pending" means the HIVE's reviewer owes a pass on the new + // head, not the author (hivecommons/hive#16615: "are we waiting on the + // clanker or are we in CI?"). The backend says so with + // `rework.owed_by: "hive-reviewer"` once the pushed head carries + // nothing the author must fix (red CI, findings, a conflict nobody + // rebases) and "author" while it does; older payloads without the + // field are read the same way from the activities. + const STAGE_TRACKER_REWORK_OWED_BY_HIVE = 'hive-reviewer'; + function stageTrackerReReviewOwedByHive(item) { + const r = stageTrackerReworkOf(item); + if (!r || r.state !== 'pushed') return false; + if (r.owed_by) return r.owed_by === STAGE_TRACKER_REWORK_OWED_BY_HIVE; + const on = k => { const a = item[k + '_activity']; return a && (!a.head || !item.head || a.head === item.head) ? a.state || 'unknown' : 'unknown'; }; + if (on('ci') === 'failing' || on('review') === 'changes_requested') return false; + if (/conflict/i.test(String(item.reason || '')) && !item.rebase) return false; + return true; + } + // "re-review of d88928e" — the owed pass, named by head. + function stageTrackerReReviewWord(item) { + const r = stageTrackerReworkOf(item); + const sha = String((r && r.head) || item.head || '').slice(0, 7); + return 're-review' + (sha ? ' of ' + sha : ' pending'); + } + // "waiting on 🐝 hive reviewer · re-review of d88928e"; '' when the + // author still owes the next move. + function stageTrackerHiveReviewerChipText(item) { + if (!stageTrackerReReviewOwedByHive(item)) return ''; + return 'waiting on 🐝 hive reviewer · ' + stageTrackerReReviewWord(item); + } // "waiting on @x · acknowledged" — the pill text with the pickup word. function stageTrackerReworkSuffix(text, item) { const w = stageTrackerReworkWord(item); @@ -17720,7 +17781,7 @@

    Where to get help

    const since = when(r.since); switch (r.state) { case 'pushed': - return who + ' pushed a new head' + (since ? ' ' + since : '') + ' · re-review pending'; + return who + ' pushed a new head' + (since ? ' ' + since : '') + (stageTrackerReReviewOwedByHive(item) ? ' · hive reviewer owes the ' + stageTrackerReReviewWord(item) : ' · re-review pending'); case 'in_progress': return who + "'s clanker picked up the rework" + (since ? ' ' + since : '') + (r.mode ? ' (' + r.mode + ')' : ''); case 'acknowledged': @@ -18063,7 +18124,9 @@

    Where to get help

    } const STAGE_TRACKER_MOD_PRIORITY = ['stalled', 'regressed', 'hold', 'unauthorized', 'needs-human', 'needs-decision', 'needs-triage', 'possible-dupe', 'needs-rebase', 'blocked', 'draft']; - const STAGE_TRACKER_MOD_TEXT = { 'needs-decision': 'needs human decision', 'needs-triage': 'triage needed', 'possible-dupe': 'possible dupe' }; + // hive:unauthorized reads "hive bot lacks permission", never "unauthorized": the App + // installation is missing a permission, nobody did anything illegitimate (hivecommons/hive#16639). + const STAGE_TRACKER_MOD_TEXT = { 'needs-decision': 'needs human decision', 'needs-triage': 'triage needed', 'possible-dupe': 'possible dupe', unauthorized: 'hive bot lacks permission' }; // The draft pill and the Draft chevron explain themselves on hover: no // maintainer action is pending, the lanes resume when the author is ready. const STAGE_TRACKER_DRAFT_TIP = 'Draft PR — hive review and merge lanes skip drafts until the author marks it ready for review.'; @@ -18244,8 +18307,10 @@

    Where to get help

    if (!sa || (sa.kind !== STAGE_TRACKER_ACTOR_NONE && sa.kind !== 'bot')) return fallback; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; const external = sa.kind === STAGE_TRACKER_ACTOR_NONE && typeof stageTrackerExternalPRWork === 'function' ? stageTrackerExternalPRWork(item) : null; - if (external) return (mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'CI failing') + (external.owner ? ' · owner recorded' : (external.author ? ' · author-owned' : ' · owner unknown')); - const state = mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Red'; + // The red verdict is the CI / Review chevron's word; this lane says + // who owes the fix (hivecommons/hive#16643). + if (external) return (mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Fix owed') + (external.owner ? ' · owner recorded' : (external.author ? ' · author-owned' : ' · owner unknown')); + const state = mods.indexOf('needs-rebase') >= 0 ? 'Conflicting' : 'Fix owed'; return state + (sa.kind === 'bot' ? ' · bot PR' : ' · nobody on it'); } @@ -18337,6 +18402,15 @@

    Where to get help

    return ``; } + // The backend's word that the pushed head waits on the hive's own + // reviewer, not the author (`rework.owed_by`, hivecommons/hive#16615): + // the re-review is the hive's move, so the row is not parked on a + // person and the Review track reads "re-review of ". + function stageTrackerHiveOwesReReview(item) { + const r = item && item.rework; + return !!(r && r.state === 'pushed' && r.owed_by === 'hive-reviewer' && (!r.head || !item.head || r.head === item.head)); + } + // 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 @@ -18350,7 +18424,7 @@

    Where to get help

    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)); + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head) || (typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))); 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; @@ -18362,7 +18436,7 @@

    Where to get help

    // 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 + // re-review of d88928e", "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. @@ -18370,7 +18444,7 @@

    Where to get help

    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 ''; + if (state === 'unknown' && !current && !stageTrackerTrackRunning(item, kind)) return ''; const n = k => matches ? Number(a[k]) || 0 : 0; if (kind === 'ci') { const total = n('checks_total'); @@ -18378,19 +18452,36 @@

    Where to get help

    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 ? ', …' : '') + ')' : '') : ''; + // A check name inside the words wears single quotes ('test' not + // reported) so it stands apart from the words around it. + const q = n => "'" + n + "'"; + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).map(q).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; const blocker = matches && a.blocker ? String(a.blocker) : ''; + // The unfinished count carries information; "no verdict yet" or a + // bare "running" beside 12/66 did not (hivecommons/hive#16630). The + // last one or two unfinished names are spelled out. + const pendingNames = matches && Array.isArray(a.checks_pending) ? a.checks_pending.map(String).filter(Boolean) : []; + const pendingCount = total ? Math.max(total - passed - failed, pendingNames.length) : pendingNames.length; + const pending = verb => !pendingCount ? verb : pendingNames.length && pendingNames.length <= STAGE_TRACKER_PENDING_CHECKS_NAMED ? pendingNames.map(q).join(', ') + ' ' + verb : pendingCount + ' ' + verb; 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 'failing': return count + ' · ' + (failing || 'failing' + (blocker ? ' (' + q(blocker) + ')' : '')); + case 'running': return count + ' · ' + pending('running') + (failing ? ' · ' + failing : ''); + case 'queued': return count + ' · ' + pending('queued') + (failing ? ' · ' + failing : ''); + case 'skipped': return count + ' · ' + (blocker ? q(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 : ''); + return count + ' · ' + (passed ? (blocker ? q(blocker) + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } + default: { + if (!total) return count + ' · no checks reported yet'; + if (failing) return count + ' · ' + failing + (pendingCount ? ' · ' + pending('running') : ''); + // A blocker here is a phrase ("commit statuses not observed") or + // the one check whose result cannot be read. + if (blocker) return count + ' · ' + (/\s/.test(blocker) ? blocker : q(blocker) + ' unclear'); + if (pendingCount) return count + ' · ' + pending('running'); + return count + ' · required set unknown'; } - default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } const total = n('perspectives_total'); @@ -18399,7 +18490,10 @@

    Where to get help

    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)); + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head) || (typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))); + // "re-review of d88928e": the hive reviewer's owed pass, named by + // head so it never reads as the author's turn (hivecommons/hive#16615). + const reReview = 're-review of ' + String(item.head || '').slice(0, 7); switch (state) { case 'approved': return count + ' approved'; case 'changes_requested': return count + ' · changes requested'; @@ -18420,7 +18514,11 @@

    Where to get help

    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'); + // Derived from the PR's own state when no reviewer has touched the + // head (stage_tracker_review_fallback.go): the words are the + // statement itself (hivecommons/hive#16661). + case 'waiting_ci': case 'not_started': case 'not_requested': case 'closed': case 'unverified': return a.caption || count; + default: return count + ' · ' + (newHead ? reReview : total && done ? 'perspectives' : 'queued'); } } @@ -18430,6 +18528,9 @@

    Where to get help

    // 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:'; + // Up to this many unfinished check names are spelled out in the CI + // chevron word; beyond it the count speaks (hivecommons/hive#16630). + const STAGE_TRACKER_PENDING_CHECKS_NAMED = 2; 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; @@ -18529,7 +18630,7 @@

    Where to get help

    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; + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state)) && !(typeof stageTrackerHiveOwesReReview === 'function' && stageTrackerHiveOwesReReview(item))) return true; const code = item.code_activity; return !!(code && code.head === item.head && code.state === 'waiting_owner'); } @@ -18544,9 +18645,23 @@

    Where to get help

    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)); - } - + if (a.active || moving.includes(a.state)) return true; + // A CI ring that is not full is a running ring: checks counted on + // the head but not yet passed or failed are still in motion unless + // the track has settled on a word of its own (a finding, a pass, a + // skip, an unreported required check, a person's decision) + // (hivecommons/hive#16631). + if (kind !== 'ci') return false; + // Inferred motion only; a row parked on a person's decision is not + // waiting on checks, whatever its cached counts say. + if ((item.decision_needed && item.decision_needed.question) || item.human_attention) return false; + const total = Number(a.checks_total) || 0, done = (Number(a.checks_passed) || 0) + (Number(a.checks_failed) || 0); + const settledWords = ['passing', 'failing', 'skipped', 'missing', 'human_decision']; + return total > 0 && done < total && !settledWords.includes(a.state); + } + + // Pure: "12m ago" beside a timestamp; "just now" under a minute. + function stageTrackerAgoWord(atMs, nowMs) { const mins = Math.floor((nowMs - atMs) / 60000); return !Number.isFinite(mins) || mins < 1 ? 'just now' : mins < 60 ? mins + 'm ago' : mins < 1440 ? Math.floor(mins / 60) + 'h ago' : Math.floor(mins / 1440) + 'd ago'; } // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. // The chevron wears its glyph plus the count words from @@ -18562,16 +18677,27 @@

    Where to get help

    const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; const matches = a && item.head && a.head === item.head; - let caption = matches ? a.caption || name + ' unknown' : name + ' unknown'; + // No evidence for the head is still a statement with a next step — + // never "activity unknown" (hivecommons/hive#16661). + const noData = name + ' · no data for head ' + (item.head ? String(item.head).slice(0, 7) : 'unknown') + ' yet · refreshing'; + let caption = matches ? a.caption || noData : noData; + // A legacy "CI unknown · reason" caption keeps its reason behind the statement. + caption = caption.replace(/^(CI|Review) unknown(?= ·|$)/, noData); const observed = matches && a.observed_at ? Date.parse(a.observed_at) : NaN; const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - 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; + // A settled verdict on the head stays known as its observation + // ages; only motion needs a fresh observation (hivecommons/hive#16617). + const settledState = ['approved', 'changes_requested', 'human_decision', 'passing', 'failing', 'skipped', 'missing', 'waiting_ci', 'not_started', 'not_requested', 'closed', 'unverified'].includes(state); + const fresh = Number.isFinite(observed) && !stale; + const known = matches && state !== 'unknown' && (settledState || fresh); + const active = known && fresh && a.active; + const perspectives = matches && kind === 'review' && Array.isArray(a.perspectives) ? a.perspectives : []; + const perspectiveMark = v => v === 'approve' ? '✓' : ['changes_requested', 'reject'].includes(v) ? '✗' : v === 'requires_human' ? 'requires human' : String(v || '?'); + const perspectiveLine = p => String(p.name || 'perspective') + ' ' + perspectiveMark(p.verdict) + (p.summary ? ': ' + p.summary : ''); 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'); @@ -18594,23 +18720,34 @@

    Where to get help

    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 freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString() + ' (' + stageTrackerAgoWord(observed, clock) + ')'; const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; - 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 detail = matches && a.detail ? String(a.detail) : ''; + const sinceAgo = matches && a.since && Number.isFinite(Date.parse(a.since)) && settledState ? ' · ' + stageTrackerAgoWord(Date.parse(a.since), clock) : ''; + // Each fact once (hivecommons/hive#16630): the count word, then the + // caption unless the detail sentence already spells it out, then the + // blocker and the ask unless an earlier fact already names them. + const facts = []; + const say = fact => { if (fact && !facts.some(f => f.toLowerCase().includes(fact.toLowerCase()))) facts.push(fact); }; + say(text); + if (!(text && detail)) say(caption); + say(detail); + if (matches && a.blocker) say(String(a.blocker)); + say(ask); + let tip = facts.join(' · ') + sinceAgo + (perspectives.length ? ' · ' + perspectives.map(perspectiveLine).join(' · ') : '') + ' · 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 : ''; if (codeNote) tip += ' · code source ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown') + (code.blocker ? ' · ' + code.blocker : ''); - const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? sg.detour.text : ''; + // The detour's words ride along, minus the code lane's "activity unknown" + // (the Review tooltip states what is observed, hivecommons/hive#16661). + const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? String(sg.detour.text || '').replace(/ · activity unknown$/, ' · no fix work observed yet').replace(/^Code activity unknown$/, 'no code work observed yet') : ''; 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; @@ -18632,7 +18769,7 @@

    Where to get help

    const evidenceLink = ownsPR && evidenceURL ? `${icon}${word}` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; - const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + (text ? text + ' · ' : '') + tip + + const fullTip = (current ? 'Current pipeline phase · ' : '') + name + ': ' + tip + (matches && a.actor ? ' · actor ' + a.actor : '') + (codeNote || contextWord ? ' · ' + (codeNote || contextWord) : '') + (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + @@ -18699,11 +18836,15 @@

    Where to get help

    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). + // Activation resolution (hivecommons/hive#16643): CI and Review are + // resolved first. If either runs, the PR waits on it and nothing + // else is active — the stage chevron (PR in progress, Merge queue …) + // renders settled-current, icon only, its words in the tooltip, so + // CI + Review is the one pair that can be active together and every + // other row has exactly one active chevron. The stage chevron is the + // ≥ 1 fallback: active only when no track is in motion. const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; - const waitingOnTracks = tracksRunning === 2; + const waitingOnTracks = tracksRunning >= 1; 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 @@ -18761,7 +18902,7 @@

    Where to get help

    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; + if (waitingOnTracks && !sg.cap) tip = (tracksRunning === 2 ? 'Waiting on CI and review, both running' : 'Waiting on ' + (stageTrackerTrackRunning(item, 'ci') ? 'CI' : 'review') + ', running') + ' — ' + tip; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -18795,7 +18936,9 @@

    Where to get help

    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}${text}${actorIco || holderIco}`; + // Deferred to a running track: the icon alone (a decision trigger + // keeps its button, since the popover lives in the word). + const content = waitingOnTracks && !sg.cap && !decision ? stageTrackerIcon(sg.number, 'ham-ico') : `${gateCue}${workIco}${text}${actorIco || holderIco}`; // A decision's dialog is its sole hover/focus detail surface. inner = decision ? `${content}` : `${content}${esc(fullTip)}`; } else if (fixPushed) { @@ -18842,13 +18985,14 @@

    Where to get help

    const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { const a = item[kind + '_activity']; const name = kind === 'ci' ? 'CI' : 'Review'; - if (!a || a.head !== item.head) return name + ' unknown'; + const noData = name + ' · no data for head ' + String(item.head).slice(0, 7) + ' yet · refreshing'; + if (!a || a.head !== item.head) return noData; const observed = Date.parse(a.observed_at || ''); const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const fresh = Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - if ((a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state)) && !fresh) return name + ' activity unknown · last observed ' + (a.state || 'unknown'); - return (a.caption || name + ' unknown') + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · stale observation' : ''); + const moving = a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state); + return (a.caption || noData).replace(/^(CI|Review) unknown(?= ·|$)/, noData) + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · last observed ' + stageTrackerAgoWord(observed, clock) + (moving ? ' · refreshing' : '') : ''); }).join(' · ') : ''; return `

    ${esc(text + (tracks ? ' · ' + tracks : ''))}

    `; } @@ -18971,7 +19115,7 @@

    Where to get help

    if (item.sentinel_alert && deferred.indexOf(STAGE_TRACKER_SENTINEL_CHIP) < 0) lines.push(stageTrackerSentinelTip(item)); const regressed = stageTrackerRegressionText(item, nowMs); if (regressed) lines.push(regressed.charAt(0).toUpperCase() + regressed.slice(1)); - if (mods.indexOf('unauthorized') >= 0 && item.unauthorized) lines.push('Unauthorized: ' + item.unauthorized); + if (mods.indexOf('unauthorized') >= 0 && item.unauthorized) lines.push('Hive bot lacks permission: ' + item.unauthorized); if (mods.indexOf('hold') >= 0 && typeof stageTrackerHoldPill === 'function' && stageTrackerHoldPill(item)) lines.push(stageTrackerHoldPill(item)); if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); @@ -19088,7 +19232,7 @@

    Where to get help

    // The regressed pill (lead or folded into "+1") explains itself on // hover; failing that, a draft pill (lead or folded) does. const regressed = stageTrackerRegressionText(item, Date.now()); - // An unauthorized pill names the missing App permission and the human step; + // A hive-bot-lacks-permission pill names the missing App permission and the human step; // 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; @@ -19214,7 +19358,7 @@

    Where to get help

    case 'applied': return 'done' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'no-op': return 'nothing changed' + (action.detail ? ': ' + stageTrackerActedPlain(action.detail) : ''); case 'failed': return 'failed' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); - case 'pending': return action.action === 'merge-now' ? 'rebasing, then merging…' : (action.action === 'queue-merge' ? 'approved — hive will merge on the next tick once CI is green' : 'the hive is deciding…'); + case 'pending': return action.action === 'merge-now' ? 'rebasing, then merging…' : (action.action === 'queue-merge' ? 'queued for merge — hive merges it on its next pass once CI is green' : 'the hive is deciding…'); case 'executing': return (action.detail ? stageTrackerActedPlain(action.detail) : 'decided — the hive is carrying it out…'); case 'no-effect': return "hasn't taken effect" + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'blocked': return 'blocked' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); @@ -19830,9 +19974,18 @@

    Where to get help

    ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; return stageTrackerLeadActionHtml(item, ctx, subRows); } - // PR link, then the lineage chip (null = none), then the base pill. - function stageTrackerPRPillsHtml(ref, lineage, baseRef) { - return ref + (lineage == null ? '' : ' ' + lineage) + (baseRef ? ` ${esc(baseRef)}` : ''); + // PR link, then the lineage chip (null = none). The base pill sits by + // the repo chip at the row's head (stageTrackerBasePillHtml), not here. + function stageTrackerPRPillsHtml(ref, lineage) { + return ref + (lineage == null ? '' : ' ' + lineage); + } + // Pure: the PR's base branch as a quiet sibling of the repo chip — + // `[hive][v5] #16603 …` — so the target reads with the repo, not in the + // right-hand modifier cluster. '' when the row has no PR (or no base). + function stageTrackerBasePillHtml(baseRef, prNumber) { + if (!baseRef) return ''; + const tip = (Number(prNumber) ? 'PR #' + Number(prNumber) + ' targets ' : 'Targets ') + baseRef; + return `${esc(baseRef)}`; } function stageTrackerSubRowHtml(lp, issue, stages, nowMs, ctx) { const pr = stageTrackerLinkedPRItem(issue, lp); @@ -19844,9 +19997,9 @@

    Where to get help

    // 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) : ''; + const chip = (ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : '') + stageTrackerBasePillHtml(lp.base_ref, pr.number); if (chip) ref = `${chip}${ref}`; - ref = stageTrackerPRPillsHtml(ref, !superseded && typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref); + ref = stageTrackerPRPillsHtml(ref, !superseded && typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null)); ref = STAGE_TRACKER_LINKED_GLYPH + ref; if (superseded) { // The adopted original: one muted line, no chevron track, no row @@ -20103,9 +20256,11 @@

    Where to get help

    const nowMs = Number(ctx.nowMs) || Date.now(); const isIssue = item.kind === 'issue'; const title = item.title || ''; - let prRefs = [], shown = item, range = null, subs = '', subRows = null, prTargetKey = ''; + let prRefs = [], shown = item, range = null, subs = '', subRows = null, prTargetKey = '', basePill = ''; if (isIssue) { const linked = stageTrackerLinkedSorted(item, stages); + // The primary (first-sorted) PR's base; an issue with no PR shows none. + if (linked.length) basePill = stageTrackerBasePillHtml(linked[0].base_ref, linked[0].number); if (linked.length === 1) { // One covering PR: a single entry whose strip the PR's stage drives. const lp = linked[0]; @@ -20113,7 +20268,7 @@

    Where to get help

    prTargetKey = stageTrackerItemKey(pr); const who = (lp.author_kind || 'hive') + (lp.author ? ' · @' + lp.author : ''); const lineage = (lp.lineage && typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(lp, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(lp, nowMs) : ''); - prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref)]; + prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null))]; const fin = lp.finisher ? lp : item; 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, @@ -20141,8 +20296,10 @@

    Where to get help

    // as one (hivecommons/hive#15232) — and the PR stays in the PR column // rather than taking the issue slot. A not-planned close adds a chip // saying the PR may be moot. - // The repo chip (when on) leads the row, before the issue slot's #N. - const chip = ctx.repoChips ? stageTrackerRepoChipHtml(item.repo, ctx) : ''; + // The repo chip (when on) leads the row, before the issue slot's #N; + // the PR's base pill follows it as a quieter sibling. + if (!isIssue) basePill = stageTrackerBasePillHtml(item.base_ref, item.number); + const chip = (ctx.repoChips ? stageTrackerRepoChipHtml(item.repo, ctx) : '') + basePill; let leadHtml; if (isIssue) { leadHtml = `
    @@ -24745,7 +24902,7 @@

    All labels

    }; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', - merged: 'merged', 'queued-for-merge': 'approved — hive will merge on the next tick once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', + merged: 'merged', 'queued-for-merge': 'queued for merge — hive merges it on its next pass once CI is green', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: 'no effect yet', }; @@ -25401,7 +25558,11 @@

    All labels

    // no count — instead of letting the row vanish in silence. const closed = stageTrackerNewlyClosed(d, _stageTrackerMergeState, next, _stageTrackerPRItems, _stageTrackerClosedNoted); const closedItems = closed.map(k => prevItems[k] || _stageTrackerPRLast[k]); - closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete next[k]; delete _stageTrackerPRLast[k]; }); + // The closed key stays comparable (false), not deleted: a close the + // server later corrects to a merge — a bot's comment on a just-merged + // PR read as "closed" before the merge fact landed — still flips + // false → true and celebrates (hivecommons/hive#16658). + closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete _stageTrackerPRLast[k]; }); _stageTrackerMergeState = next; // A merged PR is no longer in this payload, so its last host survives. if (typeof stageTrackerPRHosts === 'function') Object.assign(_stageTrackerPRHost, stageTrackerPRHosts(d)); @@ -25769,6 +25930,30 @@

    All labels

    if (!by) return ''; return by === 'hive' ? 'by hive' : 'by @' + by; } + // Pure: the merger as the merge toast's head names them — "🐝 hive" + // for the hive's own merge, "@login" for anyone else, '' unknown. + function stageTrackerMergerText(by) { + by = String(by || '').trim(); + if (!by) return ''; + return by === 'hive' ? '🐝 hive' : '@' + by; + } + // Pure: who merged the PR at key, from the payload's terminal facts — + // recently_merged (audit + ledger, any merger) and the ledger's recent + // list — then the terminal fact this tab already holds. '' unknown. + function stageTrackerMergedByOf(key, d) { + const n = Number(String(key || '').slice(String(key || '').lastIndexOf('/pr#') + 4)) || 0; + const repo = String(key || '').slice(0, String(key || '').lastIndexOf('/pr#')).toLowerCase(); + if (!n || !repo) return ''; + const short = repo.slice(repo.lastIndexOf('/') + 1); + const ledger = d && d.merged && Array.isArray(d.merged.recent) ? d.merged.recent : []; + for (const m of (d && Array.isArray(d.recently_merged) ? d.recently_merged : []).concat(ledger)) { + if (!m || Number(m.number) !== n || !m.merged_by) continue; + const r = String(m.repo || '').toLowerCase(); + if (r === repo || (r.indexOf('/') < 0 && r === short)) return String(m.merged_by).trim(); + } + const fact = typeof _stageTrackerTerminalFacts !== 'undefined' && _stageTrackerTerminalFacts ? _stageTrackerTerminalFacts[key] : null; + return fact && fact.merged_by ? String(fact.merged_by).trim() : ''; + } // Pure: the popover's inner HTML. function stageTrackerMergedPopHtml(txt, nowMs) { const fmtAt = at => { if (!at) return ''; const d = new Date(at); const sameDay = stageTrackerLocalMidnight(at) === stageTrackerLocalMidnight(nowMs); const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; return sameDay ? hm : `${typeof formatDashboardDate === 'function' ? formatDashboardDate(d, { month: 'short', day: 'numeric' }) : d.toISOString().slice(5, 10)} ${hm}`; }; @@ -26281,7 +26466,7 @@

    All labels

    const banner = stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); setTimeout(() => { const row = rowKey && el ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; - if (row) celebrateRow(row, { kind: 'merged', key, number, merged_by: fact && fact.merged_by }); + if (row) celebrateRow(row, { kind: 'merged', key, number, merged_by: (fact && fact.merged_by) || stageTrackerMergedByOf(key, typeof _stageTracker !== 'undefined' ? _stageTracker : null) }); else celebrateDetached(key, banner); }, i * STAGE_TRACKER_CELEBRATE_STAGGER_MS); }); @@ -26433,13 +26618,17 @@

    All labels

    const url = String(b.url || (b.pr && b.pr.url) || '').match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/\d+(?:[?#].*)?$/); return url ? url[1] : repo; } + // The head names the merger whoever they are — "#16644 merged by + // @clubanderson", "#16645 merged by 🐝 hive" — a merge by hand is + // celebrated exactly like the hive's own (hivecommons/hive#16658). function stageTrackerMergeBannerText(b, nowMs) { const d = new Date(b.at || nowMs); const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; const who = stageTrackerMergedByText(b.merged_by); + const merger = stageTrackerMergerText(b.merged_by); const paren = [b.lane || '', who, hm].filter(Boolean).join(', '); const num = stageTrackerMergeBannerNumber(b); - return { number: num, head: `${num ? '#' + num + ' ' : ''}merged${b.preview ? ' (test)' : ''}`, text: `${b.title || b.repo || ''}${paren ? ' (' + paren + ')' : ''}`.trim() }; + return { number: num, merger, head: `${num ? '#' + num + ' ' : ''}merged${merger ? ' by ' + merger : ''}${b.preview ? ' (test)' : ''}`, text: `${b.title || b.repo || ''}${paren ? ' (' + paren + ')' : ''}`.trim() }; } // Stateful: a persistent banner, bottom right, for one merge — stays // until dismissed or stageTrackerMergeBannerMs() (twice the info toast @@ -26455,6 +26644,7 @@

    All labels

    const repo = stageTrackerMergeBannerRepo(b); const recent = repo ? ((_stageTrackerMerged.server && _stageTrackerMerged.server.recent) || []).find(e => stageTrackerMergeBannerRepo(e).toLowerCase() === repo.toLowerCase() && stageTrackerMergeBannerNumber(e) === stageTrackerMergeBannerNumber(b)) : null; const info = Object.assign({ title: _stageTrackerPRTitle[b.key] || '', merged_by: '', lane: '', url: '' }, recent || {}, b, { repo }); + if (!info.merged_by && !b.preview) info.merged_by = stageTrackerMergedByOf(b.key, typeof _stageTracker !== 'undefined' ? _stageTracker : null); const num = stageTrackerMergeBannerNumber(info); const repoChip = stageTrackerRepoChipHtml(repo, { repoChips: { primary: stageTrackerPrimaryRepo(), active: _stageTrackerFilter.repo } }); // A live merge the ledger has not listed yet still links: the key carries owner/name. @@ -26464,7 +26654,7 @@

    All labels

    el.className = 'merge-banner'; el.setAttribute('role', 'status'); if (b.rowKey) el.setAttribute('data-ham-row', b.rowKey); - el.innerHTML = `
    ${repoChip ? repoChip + ' ' : ''}${num ? `#${esc(num)} ` : ''}merged${info.preview ? ' (test)' : ''}
    ${esc(t.text)}
    `; + el.innerHTML = `
    ${repoChip ? repoChip + ' ' : ''}${num ? `#${esc(num)} ` : ''}merged${t.merger ? ` by ${esc(t.merger)}` : ''}${info.preview ? ' (test)' : ''}
    ${esc(t.text)}
    `; box.appendChild(el); while (box.children.length > STAGE_TRACKER_MERGE_BANNER_MAX) { toastCountdownCancel(box.children[0]); box.children[0].remove(); } toastCountdownBar(el, stageTrackerMergeBannerMs(), () => stageTrackerMergeBannerDismiss(el)); diff --git a/src/pkg/dashboard/webhook_tracker_refresh.go b/src/pkg/dashboard/webhook_tracker_refresh.go index c7a6e4db62..45be82106a 100644 --- a/src/pkg/dashboard/webhook_tracker_refresh.go +++ b/src/pkg/dashboard/webhook_tracker_refresh.go @@ -397,6 +397,7 @@ func (s *Server) applyWebhookItemSnapshots(snaps []github.WebhookItemSnapshot) i return 0 } s.recordMergedSnapshots(snaps) + s.forgetClosedSnapshots(snaps) s.noteClosedSnapshots(snaps) s.notePushedSnapshots(snaps) if s.deps != nil && s.deps.ApplyWebhookItems != nil { diff --git a/src/pkg/fleetreport/fleetreport.go b/src/pkg/fleetreport/fleetreport.go index 605dace3ff..d3c0cce7b4 100644 --- a/src/pkg/fleetreport/fleetreport.go +++ b/src/pkg/fleetreport/fleetreport.go @@ -900,7 +900,7 @@ func IsBenignMessage(msg string) bool { } // A sentinel finding flags a PR for a human: the sweep working as designed, // not a runtime defect (#16112). Match only the finding notice; "sentinel - // sweep failed" and "sentinel sweep: PR skipped" stay reportable. + // sweep failed" and non-pacing "sentinel sweep: PR skipped" remain reportable. if strings.TrimSpace(m) == "sentinel alert" { return true } diff --git a/src/pkg/fleetreport/slogfeed/slogfeed.go b/src/pkg/fleetreport/slogfeed/slogfeed.go index 594dc8fdc8..46af39966e 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) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) || automergeMergeGuardSkip(r) { + if expectedKickHold(r) || rateLimitedError(r) || sentinelPacingSkip(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) || automergeMergeGuardSkip(r) { return } class := fleetreport.ClassUnclassifiedRepeated @@ -173,6 +173,23 @@ func rateLimitedError(r slog.Record) bool { return limited } +// sentinelPacingSkip handles the sentinel's per-item errors, which are logged +// as detail rather than error. Other skipped PRs remain reportable. +func sentinelPacingSkip(r slog.Record) bool { + if r.Message != "sentinel sweep: PR skipped" { + return false + } + limited := false + r.Attrs(func(a slog.Attr) bool { + if a.Key == "detail" && fleetreport.IsGitHubRateLimited(a.Value.String()) { + limited = true + return false + } + return true + }) + return limited +} + // upstreamUnavailableError reports whether the record's error attribute is a // GitHub 502/503/504 (fleetreport.IsGitHubUpstreamUnavailable). Callers such // as the self-authored automerge sweep ("fetch-pr") log a per-site message and diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index 6254db65ae..545da059b6 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -894,6 +894,25 @@ func TestSentinelAlertLogsWithoutFleetReport(t *testing.T) { } } +func TestSentinelPacingSkipLogsWithoutFleetReport(t *testing.T) { + logger, seen, out := newFeed(t) + const detail = `website: list PRs: listing open PRs for supersession sweep in projectbluefin/website: Get "https://api.github.com/repos/projectbluefin/website/pulls?per_page=100&state=open": github pacing: slot would miss request deadline: context deadline exceeded` + for range 16 { + logger.Warn("sentinel sweep: PR skipped", "detail", detail) + } + if len(*seen) != 0 { + t.Fatalf("pacing skips produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 16 { + t.Fatalf("wrapped handler saw %d records, want 16", n) + } + logger.Warn("sentinel sweep: PR skipped", "detail", "website: permission denied") + logger.Warn("another warning", "detail", detail) + if len(*seen) != 2 { + t.Fatalf("other failures must remain reportable: %+v", *seen) + } +} + // #15906: the per-head review cap suppressing a duplicate comment is expected. func TestReviewCommentCappedLogsWithoutFleetReport(t *testing.T) { logger, seen, out := newFeed(t) diff --git a/src/pkg/github/automerge/automerge_adoption_escape_test.go b/src/pkg/github/automerge/automerge_adoption_escape_test.go index f261d4ce53..e8219090c3 100644 --- a/src/pkg/github/automerge/automerge_adoption_escape_test.go +++ b/src/pkg/github/automerge/automerge_adoption_escape_test.go @@ -11,7 +11,6 @@ import ( "time" gh "github.com/google/go-github/v72/github" - "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -803,6 +802,55 @@ func TestAdoptionStalledNotePerReasonOnSameHead(t *testing.T) { } } +// hivecommons/hive#16619: the hive's own clanker (project.ai_author) opened +// the PR from its fork; the hive's fixer pushed a commit signed as the App. +// The squash attributes that commit to the hive's own author, so there is +// nothing to re-home: the PR keeps its number, approval and CI, and the +// adoption stays in place. No superseder, no stall note. +func TestAdoptedInPlaceHiveAuthoredSquashUnsafeCommitStaysInPlace(t *testing.T) { + p := adoptPolicy() + p.AdoptInPlace = true + p.DCORequired = func(string) (bool, bool) { return true, true } + p.HiveAuthor = func(login string) bool { return strings.EqualFold(login, "thatguywob") } + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, p) + defer done() + h.api.commitDetails = map[int][]stageCommitFixture{7: { + {message: "fix: preserve verdicts\n\nSigned-off-by: thatguywob ", authorLogin: "thatguywob", authorName: "thatguywob", authorEmail: "thatguywob@users.noreply.github.com"}, + {message: "fix: escape tooltip lines\n\nSigned-off-by: hive[bot] <12345+hive[bot]@users.noreply.github.com>", authorLogin: testHiveAppBotLogin, authorName: "scanner", authorEmail: "12345+hive[bot]@users.noreply.github.com"}, + }} + own := func(head string, labels ...string) *gh.PullRequest { + pr := adoptPR(7, head, labels...) + pr.User = &gh.User{Login: gh.Ptr("thatguywob")} + pr.Head.Repo = &gh.Repository{FullName: gh.Ptr("thatguywob/widget")} + return pr + } + h.adopt.allowMaintainerEdits(7, true) + h.observe(own("5980996"), contributorLaneReasonNoVerdict) + key := stageKey("acme", "widget", 7) + h.e.stageStoreOrShared().MarkAdoptedInPlace(key, "5980996", AdoptReasonGrace, h.clock.at) + h.adopt.setCommitAuthor("5980996", testHiveAppBotLogin) + h.api.reset() + + for _, advance := range []time.Duration{time.Minute, adoptedDwell + time.Hour} { + h.clock.advance(advance) + h.observe(own("5980996", adoptedLabels...), contributorLaneReasonNoVerdict) + // Past the dwell the idle head may escalate to a person (085); + // that is a note on the same PR, never a copy of it. + if len(h.adopt.pulls) != 0 || len(adoptionComments(h.api)) != 0 || h.adopt.refs["refs/heads/hive/adopt-7"] != "" { + t.Fatalf("hive-authored PR superseded for sign-off: pulls=%v refs=%v comments=%v", h.adopt.pulls, h.adopt.refs, h.api.comments) + } + rec, _ := h.e.stageStoreOrShared().Get(key) + if !rec.AdoptedInPlace() || rec.AdoptedBy != 0 || rec.AdoptReason == AdoptReasonSignoffRehome || rec.DCOSquashUnsafeHive != 0 { + t.Fatalf("record after %v: %+v", advance, rec) + } + for _, c := range stalledComments(h.api) { + if strings.Contains(c, stagelabels.LaneReasonHiveSignoffAttribution) { + t.Fatalf("hive-authored PR parked on sign-off attribution: %s", c) + } + } + } +} + // A record from before the noted reasons were kept: escalated and noted on // the head, no reasons. It reads as noted for every reason on that head, so // an upgrade does not repost on every parked PR. @@ -944,3 +992,67 @@ func TestAdoptionStaleWaitsForFixerQueue(t *testing.T) { }) } } + +// The same head on an external contributor's fork keeps the existing +// behaviour: the App-signed commit is squash-unsafe under mallory's name, +// so the adoption re-homes onto hive/adopt-7 at once +// (TestAdoptedInPlaceSquashUnsafeHiveCommitSupersedes covers the full +// path; this pins the decision with the hive-author hook present). +func TestAdoptedInPlaceExternalForkSquashUnsafeStillSupersedes(t *testing.T) { + policy := adoptPolicy() + policy.AdoptInPlace = true + policy.HiveAuthor = func(login string) bool { return strings.EqualFold(login, "thatguywob") } + now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) + inPlace := stagelabels.Record{AdoptedHead: "aaa", AdoptMode: stagelabels.AdoptModeInPlace, AdoptedAt: now, AdoptedHeadAt: now} + external := stageObservation{HeadSHA: "aaa", Author: "mallory", HeadRepo: "mallory/widget", Reason: stagelabels.LaneReasonHiveSignoffAttribution, Detail: stageDetail{DCOSquashUnsafeHive: 1}} + if got := inPlaceRehomeReason(external, inPlace, policy, now.Add(time.Minute), false); got != AdoptReasonSignoffRehome { + t.Fatalf("external fork: inPlaceRehomeReason=%q, want %q", got, AdoptReasonSignoffRehome) + } + if got := adoptionStalledReason(external, inPlace, policy, now.Add(time.Minute)); got != "adoption-stalled:hive-signoff-attribution" { + t.Fatalf("external fork stall reason=%q", got) + } + own := external + own.Author, own.HeadRepo = "thatguywob", "thatguywob/widget" + if got := inPlaceRehomeReason(own, inPlace, policy, now.Add(time.Minute), false); got != "" { + t.Fatalf("hive-authored: inPlaceRehomeReason=%q, want none", got) + } + if got := adoptionStalledReason(own, inPlace, policy, now.Add(time.Minute)); got != "" { + t.Fatalf("hive-authored stall reason=%q, want none", got) + } +} + +// An operator's approval on the adopted head is never thrown away for a +// copy: neither the sign-off, the rebase nor the stalled-finding re-home +// fires while the approval stands on that head. A new head starts over. +func TestAdoptedInPlaceApprovedHeadIsNotSuperseded(t *testing.T) { + policy := adoptPolicy() + policy.AdoptInPlace = true + now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) + inPlace := stagelabels.Record{AdoptedHead: "aaa", AdoptMode: stagelabels.AdoptModeInPlace, AdoptedAt: now, AdoptedHeadAt: now} + late := now.Add(adoptedDwell + time.Hour) + approved := stageDetail{HumanApprover: "clubanderson", HumanApprovalHead: "aaa"} + cases := []struct { + name string + obs stageObservation + }{ + {"squash-unsafe sign-off", stageObservation{HeadSHA: "aaa", Author: "mallory", Reason: stagelabels.LaneReasonHiveSignoffAttribution, Detail: stageDetail{DCOSquashUnsafeHive: 1}}}, + {"needs-rebase past dwell", stageObservation{HeadSHA: "aaa", Author: "mallory", Labels: []string{"needs-rebase"}, Reason: "conflicting"}}, + {"finding past dwell", stageObservation{HeadSHA: "aaa", Author: "mallory", LaneReason: contributorLaneReasonChangesRequested, Detail: stageDetail{VerdictKnown: true, Verdict: ContributorLaneVerdict{Configured: true, Verdict: "changes_requested"}}}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := inPlaceRehomeReason(tc.obs, inPlace, policy, late, true); got == "" { + t.Fatalf("precondition: unapproved head must re-home") + } + obs := tc.obs + obs.Detail.HumanApprover, obs.Detail.HumanApprovalHead = approved.HumanApprover, approved.HumanApprovalHead + if got := inPlaceRehomeReason(obs, inPlace, policy, late, true); got != "" { + t.Fatalf("approved head re-homed: %q", got) + } + obs.Detail.HumanApprovalHead = "older" + if got := inPlaceRehomeReason(obs, inPlace, policy, late, true); got == "" { + t.Fatalf("an approval on an older head must not pin the new one") + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 13a36110c4..faaf2b3b18 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -315,8 +315,8 @@ func adoptionCloses(body string) []string { return out } -func adoptionNeedsDCORehome(obs stageObservation, canPushInPlace bool) bool { - return adoptionDCORepairMode(obs, canPushInPlace) == stagelabels.AdoptModeSupersede +func adoptionNeedsDCORehome(obs stageObservation, canPushInPlace, hiveAuthored bool) bool { + return adoptionDCORepairMode(obs, canPushInPlace, hiveAuthored) == stagelabels.AdoptModeSupersede } // adoptionDCORepairMode decides how a DCO-red head gets its sign-off: @@ -325,16 +325,34 @@ func adoptionNeedsDCORehome(obs stageObservation, canPushInPlace bool) bool { // base repository — a fork branch is pushable by an agent's git but not by // the App's REST token, so a fork head re-homes (AdoptModeSupersede) even // when every unsigned commit is the hive's (hivecommons/hive#14666). -func adoptionDCORepairMode(obs stageObservation, canPushInPlace bool) string { +// +// A hive-authored PR (hiveAuthored: the App bot or project.ai_author opened +// it) is never re-homed: every commit on it is the hive's to sign, so a +// pushable base-repo head is amended in place and any other head keeps its +// PR number, approvals and CI history and waits for a person (""), +// rather than restarting as a copy (hivecommons/hive#16619). +func adoptionDCORepairMode(obs stageObservation, canPushInPlace, hiveAuthored bool) string { if obs.Detail.DCO != stagelabels.DCONo || obs.Detail.DCOUnsigned <= 0 { return "" } - if canPushInPlace && headInBaseRepo(obs) && obs.Detail.DCOUnsignedHive == obs.Detail.DCOUnsigned && obs.Detail.DCOUnsignedOther == 0 { + if canPushInPlace && headInBaseRepo(obs) && (hiveAuthored || (obs.Detail.DCOUnsignedHive == obs.Detail.DCOUnsigned && obs.Detail.DCOUnsignedOther == 0)) { return stagelabels.AdoptModeInPlace } + if hiveAuthored { + return "" + } return stagelabels.AdoptModeSupersede } +// adoptionHeadApproved reports whether a trusted human's APPROVED review +// stands on the observed head. Such a head is never re-homed onto a copy: +// the copy would restart CI and drop the approval (hivecommons/hive#16619). +// The one exception is a fork branch the hive cannot push to +// (AdoptReasonPushRehome), which the caller decides. +func adoptionHeadApproved(obs stageObservation) bool { + return obs.HeadSHA != "" && strings.TrimSpace(obs.Detail.HumanApprover) != "" && strings.TrimSpace(obs.Detail.HumanApprovalHead) == obs.HeadSHA +} + // headInBaseRepo reports whether the PR head lives in the base repository // (not a fork), where the App's git-data API can rewrite it. func headInBaseRepo(obs stageObservation) bool { @@ -344,8 +362,8 @@ func headInBaseRepo(obs stageObservation) bool { // adoptedHeadNeedsDCORepair decides, for an in-place-adopted PR, whether the // unsigned commits are the hive's own on a base-repo branch it rewrites in // place with its sign-off. -func adoptedHeadNeedsDCORepair(obs stageObservation, rec stagelabels.Record, canPushInPlace bool) bool { - return adoptedHeadDCORed(obs, rec) && adoptionDCORepairMode(obs, canPushInPlace) == stagelabels.AdoptModeInPlace +func adoptedHeadNeedsDCORepair(obs stageObservation, rec stagelabels.Record, canPushInPlace, hiveAuthored bool) bool { + return adoptedHeadDCORed(obs, rec) && adoptionDCORepairMode(obs, canPushInPlace, hiveAuthored) == stagelabels.AdoptModeInPlace } // adoptedHeadDCORed reports whether an in-place-adopted PR's head carries @@ -357,8 +375,8 @@ func adoptedHeadDCORed(obs stageObservation, rec stagelabels.Record) bool { // adoptedHeadNeedsDCORehome decides, for an in-place-adopted PR, whether the // unsigned commits can be rewritten on the contributor branch (all App-linked // and the branch still pushable) or the work must be re-homed. -func adoptedHeadNeedsDCORehome(obs stageObservation, rec stagelabels.Record, canPushInPlace bool) bool { - return adoptedHeadDCORed(obs, rec) && adoptionDCORepairMode(obs, canPushInPlace) == stagelabels.AdoptModeSupersede +func adoptedHeadNeedsDCORehome(obs stageObservation, rec stagelabels.Record, canPushInPlace, hiveAuthored bool) bool { + return adoptedHeadDCORed(obs, rec) && adoptionDCORepairMode(obs, canPushInPlace, hiveAuthored) == stagelabels.AdoptModeSupersede } func adoptionRehomeCommitMessage(obs stageObservation) string { @@ -844,7 +862,7 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor if policy.AdoptInPlace && !requested && !forced { canPushInPlace = c.canPushToPRBranch(ctx, obs) } - dcoRehome := adoptionNeedsDCORehome(obs, canPushInPlace) + dcoRehome := adoptionNeedsDCORehome(obs, canPushInPlace, hiveAuthoredPR(obs, policy, appLogin)) if !requested && adoptionFromFork(obs) && !(policy.AdoptInPlace && canPushInPlace && !dcoRehome) { // The only adoption a fork PR can have is in place: superseding it // would move fork code into this repository (supersedeAdoptedPR). @@ -1511,10 +1529,17 @@ func (c *Engine) settleAdoption(ctx context.Context, store *stagelabels.Store, k } if adoptedHeadDCORed(obs, rec) { canPushInPlace := c.canPushToPRBranch(ctx, obs) - if adoptedHeadNeedsDCORepair(obs, rec, canPushInPlace) { + hiveAuthored := hiveAuthoredPR(obs, policy, c.transport.AppBotLogin()) + if adoptedHeadNeedsDCORepair(obs, rec, canPushInPlace, hiveAuthored) { return c.repairAdoptedDCOInPlace(ctx, store, key, obs, rec) } - if adoptedHeadNeedsDCORehome(obs, rec, canPushInPlace) { + if hiveAuthored && !adoptionHeadApproved(obs) && obs.Detail.DCOUnsigned > 0 { + // The hive's own PR on a head it cannot rewrite over REST: + // it keeps its number, approvals and CI; the unsigned head + // is the hive's agent's to re-sign on the same branch. + c.info("stage labels: hive-authored adopted PR has unsigned commits on a head the sweep cannot rewrite; keeping it in place", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "head_repo", obs.HeadRepo, "can_push", canPushInPlace) + } + if adoptedHeadNeedsDCORehome(obs, rec, canPushInPlace, hiveAuthored) { fence, err := c.adoptionDiffRefusal(ctx, obs) if fence != "" && (err != nil || adoptionFenceDefers(fence)) { // Not a verdict: the head moved, or its file list is @@ -2161,7 +2186,18 @@ func inPlaceRehomeReason(obs stageObservation, rec stagelabels.Record, policy St if !rec.AdoptedInPlace() || obs.HeadSHA == "" || obs.HeadSHA != rec.AdoptedHead || adoptedHeadDCORed(obs, rec) || adoptionBlocked(obs.Labels) != "" || verdictNeedsHuman(obs.Detail) { return "" } + if adoptionHeadApproved(obs) { + // A copy restarts CI and drops the approval; the head stays where + // the approval is. Only a fork the hive cannot push to re-homes + // (AdoptReasonPushRehome, decided by the caller). + return "" + } if adoptedHeadSignoffUnfixable(obs, rec) { + if hiveAuthoredPR(obs, policy, "") { + // The squash attributes the hive's commits to the hive's own + // author: nothing to re-home (hivecommons/hive#16619). + return "" + } return AdoptReasonSignoffRehome } if humanConflictReasons[obs.Reason] || humanConflictReasons[obs.LaneReason] || hasLabelFold(obs.Labels, "needs-rebase") { @@ -2202,7 +2238,7 @@ func adoptionStalledReasonWith(obs stageObservation, rec stagelabels.Record, pol if rec.AdoptionAttemptedNothingOpened(obs.HeadSHA) { return stagelabels.LaneReasonAdoptionStalledPrefix + "supersede-failed:" + nonEmpty(rec.AdoptReason, obs.Reason) } - if adoptedHeadSignoffUnfixable(obs, rec) { + if adoptedHeadSignoffUnfixable(obs, rec) && !hiveAuthoredPR(obs, policy, "") { return stagelabels.LaneReasonAdoptionStalledPrefix + stagelabels.LaneReasonHiveSignoffAttribution } if adoptionOptionalCheckOnly(obs) || !adoptionStale(obs, rec, policy, now) { @@ -2231,6 +2267,15 @@ func (c *Engine) escapeStalledAdoption(ctx context.Context, store *stagelabels.S rec, _ = store.Get(key) } rehomeReason := inPlaceRehomeReason(obs, rec, policy, now, c.inPlaceRebaseExhausted(obs, rec)) + if rehomeReason == AdoptReasonSignoffRehome && hiveAuthoredPR(obs, policy, c.transport.AppBotLogin()) { + rehomeReason = "" + } + if rehomeReason != "" && c.operatorAdmission(ctx, obs.Owner, obs.Repo, obs.Number, obs.HeadSHA) != "" { + // An operator admitted this head: a copy would drop that and + // restart CI. Only a fork the hive cannot push to re-homes. + c.info("stage labels: in-place adoption keeps its approved head; not superseding", "repo", obs.Display, "pr", obs.Number, "head", obs.HeadSHA, "would_rehome", rehomeReason) + rehomeReason = "" + } if rehomeReason == "" && rec.AdoptedInPlace() && obs.HeadSHA == rec.AdoptedHead && !adoptedHeadDCORed(obs, rec) && adoptionBlocked(obs.Labels) == "" && !verdictNeedsHuman(obs.Detail) && c.pushAccessLost(ctx, obs) { rehomeReason = AdoptReasonPushRehome } diff --git a/src/pkg/github/automerge/automerge_contributor_adopt_test.go b/src/pkg/github/automerge/automerge_contributor_adopt_test.go index 37f67defdc..46afc6500f 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt_test.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt_test.go @@ -596,45 +596,61 @@ func TestAdoptionDCORehomeDecisionAndRendering(t *testing.T) { Body: "Implements widgets.\n\nHive-Run: acme/widget#44\n", Detail: stageDetail{DCO: stagelabels.DCONo, DCOTotal: 3, DCOUnsigned: 2}, } - if !adoptionNeedsDCORehome(obs, false) { + if !adoptionNeedsDCORehome(obs, false, false) { t.Fatal("unsigned commits without branch push permission must re-home") } - if !adoptionNeedsDCORehome(obs, true) { + if !adoptionNeedsDCORehome(obs, true, false) { t.Fatal("unknown unsigned commit ownership must re-home") } obs.Detail.DCOUnsignedHive = 2 - if !adoptionNeedsDCORehome(obs, true) { + if !adoptionNeedsDCORehome(obs, true, false) { t.Fatal("a fork head must re-home even when only hive-authored commits are unsigned: the engine cannot rewrite a fork branch") } obs.Owner, obs.Repo, obs.HeadRepo = "acme", "widget", "acme/widget" - if adoptionNeedsDCORehome(obs, true) { + if adoptionNeedsDCORehome(obs, true, false) { t.Fatal("branch push permission with only hive-authored unsigned commits on a base-repo head allows in-place repair") } - if !adoptionNeedsDCORehome(obs, false) { + if !adoptionNeedsDCORehome(obs, false, false) { t.Fatal("hive-authored unsigned commits without branch push permission must still re-home") } inPlace := stagelabels.Record{AdoptedHead: "aaa", AdoptMode: stagelabels.AdoptModeInPlace} - if adoptedHeadNeedsDCORehome(obs, inPlace, true) { + if adoptedHeadNeedsDCORehome(obs, inPlace, true, false) { t.Fatal("already adopted in place with App-owned unsigned commits and push access stays in place") } - if !adoptedHeadNeedsDCORepair(obs, inPlace, true) { + if !adoptedHeadNeedsDCORepair(obs, inPlace, true, false) { t.Fatal("that head is the in-place repair's job") } obs.HeadRepo = "" - if !adoptedHeadNeedsDCORehome(obs, inPlace, true) { + if !adoptedHeadNeedsDCORehome(obs, inPlace, true, false) { t.Fatal("already adopted in place on a fork must re-home") } - if !adoptedHeadNeedsDCORehome(obs, inPlace, false) { + if !adoptedHeadNeedsDCORehome(obs, inPlace, false, false) { t.Fatal("already adopted in place without push access must re-home") } - if adoptedHeadNeedsDCORehome(obs, stagelabels.Record{AdoptedHead: "aaa", AdoptedBy: 90, AdoptMode: stagelabels.AdoptModeSupersede}, false) { + if adoptedHeadNeedsDCORehome(obs, stagelabels.Record{AdoptedHead: "aaa", AdoptedBy: 90, AdoptMode: stagelabels.AdoptModeSupersede}, false, false) { t.Fatal("a superseded adoption is never re-homed again") } obs.Detail.DCOUnsignedHive = 0 obs.Detail.DCOUnsigned = 0 - if adoptionNeedsDCORehome(obs, false) { + if adoptionNeedsDCORehome(obs, false, false) { t.Fatal("signed head does not need DCO re-home") } + // A hive-authored PR (hivecommons/hive#16619) is never re-homed for + // sign-off: a pushable base-repo head is amended in place whoever the + // unsigned commits are linked to; a fork head keeps its PR and waits. + own := obs + own.Author, own.Detail.DCOUnsigned, own.Detail.DCOUnsignedOther = "thatguywob", 2, 2 + own.Owner, own.Repo, own.HeadRepo = "acme", "widget", "acme/widget" + if got := adoptionDCORepairMode(own, true, true); got != stagelabels.AdoptModeInPlace { + t.Fatalf("hive-authored base-repo head: mode=%q, want in-place amend", got) + } + own.HeadRepo = "thatguywob/widget" + if got := adoptionDCORepairMode(own, false, true); got != "" { + t.Fatalf("hive-authored fork head: mode=%q, want no re-home", got) + } + if adoptionNeedsDCORehome(own, false, true) || adoptedHeadNeedsDCORehome(own, inPlace, false, true) { + t.Fatal("a hive-authored PR must never be superseded for sign-off") + } obs.Detail.DCOUnsigned = 2 body := AdoptionPRBody(obs, stagelabels.Record{Reason: "check-failing:dco"}, true, "") for _, want := range []string{ diff --git a/src/pkg/github/automerge/automerge_stage_dco.go b/src/pkg/github/automerge/automerge_stage_dco.go index 9729023de2..ec17c37b1b 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" + "github.com/hivecommons/hive/pkg/authorkind" hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -51,6 +52,16 @@ func dcoCommitStatsDetailed(commits []*gh.RepositoryCommit, appLogin string) dco } func dcoCommitStatsDetailedForAuthor(commits []*gh.RepositoryCommit, appLogin, prAuthor string) dcoStats { + return dcoCommitStatsForSquashAuthor(commits, appLogin, prAuthor, botSquashAuthor(prAuthor)) +} + +// dcoCommitStatsForSquashAuthor is dcoCommitStatsDetailedForAuthor with the +// squash-attribution verdict on the PR author made explicit: selfSquash means +// a squash under prAuthor attributes the hive's commits to the hive itself +// (a bot author, or one of this hive's own identities: project.ai_author, +// the App bot), so no signed hive commit is squash-unsafe. Unsigned commits +// are still counted and rejected. +func dcoCommitStatsForSquashAuthor(commits []*gh.RepositoryCommit, appLogin, prAuthor string, selfSquash bool) dcoStats { var stats dcoStats for _, rc := range commits { if rc == nil || len(rc.Parents) > 1 { @@ -65,7 +76,7 @@ func dcoCommitStatsDetailedForAuthor(commits []*gh.RepositoryCommit, appLogin, p } else { stats.unsignedOther++ } - } else if !botSquashAuthor(prAuthor) && dcoCommitByHive(rc, appLogin) && !messageHasPRAuthorSignoff(msg, prAuthor) { + } else if !selfSquash && dcoCommitByHive(rc, appLogin) && !messageHasPRAuthorSignoff(msg, prAuthor) { stats.squashUnsafeHive++ } } @@ -87,10 +98,12 @@ func dcoCommitByHive(commit *gh.RepositoryCommit, appLogin string) bool { // with Store.NoteDCO once the record exists). A read // failure leaves the state unknown (labels untouched, stage unchanged) and // is reported, never fatal. -func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation) (dcoStats, error) { +func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, policy StageLabelPolicy) (dcoStats, error) { if obs.HeadSHA == "" { return dcoStats{}, nil } + appLogin := c.transport.AppBotLogin() + selfSquash := botSquashAuthor(obs.Author) || hiveAuthoredPR(obs, policy, appLogin) if rec, ok := store.Get(key); ok { if t, u, cached := rec.DCOFor(obs.HeadSHA); cached { // Records cached before the ownership split existed carry @@ -98,7 +111,7 @@ func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key str // so read the commits once more for that case only. if (u > 0 || rec.DCOSquashUnsafeKnown) && (u == 0 || rec.DCOSplitKnown(obs.HeadSHA) || !rec.AdoptedInPlace()) { unsafe := rec.DCOSquashUnsafeHive - if botSquashAuthor(obs.Author) { + if selfSquash { unsafe = 0 } return dcoStats{total: t, unsigned: u, unsignedHive: rec.DCOUnsignedHive, unsignedOther: u - rec.DCOUnsignedHive, squashUnsafeHive: unsafe}, nil @@ -110,7 +123,27 @@ func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key str if err != nil { return dcoStats{}, err } - return dcoCommitStatsDetailedForAuthor(all, c.transport.AppBotLogin(), obs.Author), nil + return dcoCommitStatsForSquashAuthor(all, appLogin, obs.Author, selfSquash), nil +} + +// hiveAuthoredPR reports whether the PR is the hive's own: author/hive by +// kind, observed under the self-authored lane, authored by the App bot, or +// authored by one of the identities the policy names as this hive's +// (project.ai_author — the clanker login the hive's agents open PRs as). +// Such a PR is never re-homed for sign-off attribution: a squash under its +// author attributes the hive's commits to the hive (hivecommons/hive#16619). +func hiveAuthoredPR(obs stageObservation, policy StageLabelPolicy, appLogin string) bool { + if obs.AuthorKind == authorkind.Hive || obs.Lane == stageLaneSelf { + return true + } + author := strings.TrimSpace(obs.Author) + if author == "" { + return false + } + if appLogin != "" && strings.EqualFold(author, appLogin) { + return true + } + return policy.HiveAuthor != nil && policy.HiveAuthor(author) } // Matches the bot-PR policy in check-squash-signoff-attribution.sh: a squash diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 85abb954ba..e53d3a1cae 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -142,6 +142,12 @@ type StageLabelPolicy struct { // (dashboard.authorized_users). Their PRs, like author/human ones, are // never adopted (hivecommons/hive#15202). nil = unknown. OwnerAuthor func(login string) bool + // HiveAuthor reports whether login is one of this hive's own PR-authoring + // identities (project.ai_author, the App bot: hgithub.HiveIdentity). A + // squash of such a PR attributes the hive's commits to the hive itself, + // so a sign-off re-home never applies to it (hivecommons/hive#16619: + // the hive superseded its own clanker's approved PR). nil = unknown. + HiveAuthor func(login string) bool // SharedCIIncident returns the open [shared-ci] incident the PR // (repo "owner/name", number, head SHA) is deferred to, or 0. A red PR // deferred to one is kept out of 070/072 and never nudged @@ -1069,7 +1075,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) // zero record for the head would be served back if the // same head later stopped matching. var err error - stats, err = c.stageDCO(ctx, store, key, obs) + stats, err = c.stageDCO(ctx, store, key, obs, policy) if err != nil { c.warn("stage labels: dco commit check failed", "repo", obs.Display, "pr", obs.Number, "error", err) if firstErr == nil { diff --git a/src/pkg/github/automerge/shared_ci_attribution_test.go b/src/pkg/github/automerge/shared_ci_attribution_test.go index d3d5e83a99..1e20a6a6d3 100644 --- a/src/pkg/github/automerge/shared_ci_attribution_test.go +++ b/src/pkg/github/automerge/shared_ci_attribution_test.go @@ -45,7 +45,7 @@ func TestStageDCONormalizesCachedBotAttributionWithoutChangingSignoffs(t *testin store.NoteDCO(key, "aaa", 3, 0, 0, 1) got, err := e.stageDCO(context.Background(), store, key, stageObservation{ Owner: "acme", Repo: "widget", Number: 42, HeadSHA: "aaa", Author: "dependabot[bot]", - }) + }, StageLabelPolicy{}) if err != nil || got.total != 3 || got.unsigned != 0 || got.squashUnsafeHive != 0 { t.Fatalf("cached bot attribution: %+v, %v", got, err) } diff --git a/src/pkg/github/pr_batch_graphql.go b/src/pkg/github/pr_batch_graphql.go index a44d0c6cf3..29153d0b7a 100644 --- a/src/pkg/github/pr_batch_graphql.go +++ b/src/pkg/github/pr_batch_graphql.go @@ -34,7 +34,8 @@ query($owner: String!, $name: String!, $first: Int!, $cursor: String) { oid statusCheckRollup { state - contexts(first: 50) { + contexts(first: 100) { + totalCount nodes { __typename ... on CheckRun { id databaseId name conclusion status detailsUrl startedAt completedAt checkSuite { app { databaseId } commit { oid } } } @@ -102,7 +103,8 @@ type graphQLPRBatchNode struct { StatusCheckRollup *struct { State string `json:"state"` Contexts struct { - Nodes []graphQLPRBatchContext `json:"nodes"` + TotalCount int `json:"totalCount"` + Nodes []graphQLPRBatchContext `json:"nodes"` } `json:"contexts"` } `json:"statusCheckRollup"` } `json:"commit"` @@ -304,10 +306,21 @@ func graphQLMergeable(raw string) *bool { } } +// graphQLCheckRuns converts a PR node's statusCheckRollup into check runs. It +// reports ok=false when the rollup is absent OR when GitHub truncated the +// contexts page: a head with more contexts than one page holds (a 70-job +// matrix plus statuses) would otherwise be cached as a partial listing, and +// enrichPRCI would read the missing required checks as "never reported" +// (hivecommons/hive#16615 showed `CI 7/11 · required check "test" hasn't +// reported` while every check was green). The caller falls back to the +// paginated REST listing instead. func graphQLCheckRuns(n graphQLPRBatchNode) ([]*gh.CheckRun, bool) { if len(n.Commits.Nodes) == 0 || n.Commits.Nodes[0].Commit.StatusCheckRollup == nil { return nil, false } + if graphQLContextsTruncated(n) { + return nil, false + } var out []*gh.CheckRun for _, ctx := range n.Commits.Nodes[0].Commit.StatusCheckRollup.Contexts.Nodes { name, status, conclusion, url := "", "", "", "" @@ -356,6 +369,16 @@ func graphQLCheckRuns(n graphQLPRBatchNode) ([]*gh.CheckRun, bool) { return out, true } +// graphQLContextsTruncated reports whether the rollup's contexts connection +// holds fewer nodes than GitHub says exist for the head. +func graphQLContextsTruncated(n graphQLPRBatchNode) bool { + if len(n.Commits.Nodes) == 0 || n.Commits.Nodes[0].Commit.StatusCheckRollup == nil { + return false + } + contexts := n.Commits.Nodes[0].Commit.StatusCheckRollup.Contexts + return contexts.TotalCount > len(contexts.Nodes) +} + func statusFromStatusContext(state string) string { switch strings.ToUpper(strings.TrimSpace(state)) { case "SUCCESS", "FAILURE", "ERROR": diff --git a/src/pkg/github/pr_batch_graphql_status_test.go b/src/pkg/github/pr_batch_graphql_status_test.go index c0f5dd628e..ac7bdc0856 100644 --- a/src/pkg/github/pr_batch_graphql_status_test.go +++ b/src/pkg/github/pr_batch_graphql_status_test.go @@ -338,3 +338,33 @@ func TestGraphQLPRBatchRefetchClearsStaleRepoEntries(t *testing.T) { t.Fatalf("GraphQL calls = %d, want 2 (none while disabled)", got) } } + +// hivecommons/hive#16615: a head with more contexts than one GraphQL page +// (70 matrix jobs + statuses) was cached as a partial listing, so the +// required `test` aggregate fell off the page and the dashboard reported +// `CI 7/11 · required check "test" hasn't reported` on an all-green head. +func TestGraphQLCheckRunsTruncatedContextsReportsNotOK(t *testing.T) { + node := `{"number":16615,"headRefOid":"d88928e","commits":{"nodes":[{"commit":{"oid":"d88928e","statusCheckRollup":{"state":"SUCCESS","contexts":{"totalCount":73,"nodes":[` + + `{"__typename":"CheckRun","id":"CR_1","databaseId":1,"name":"test (agent 1/5)","status":"COMPLETED","conclusion":"SUCCESS"},` + + `{"__typename":"CheckRun","id":"CR_2","databaseId":2,"name":"coverage","status":"COMPLETED","conclusion":"SUCCESS"}` + + `]}}}}]}}` + n := decodeGQLPRNode(t, node) + if !graphQLContextsTruncated(n) { + t.Fatalf("totalCount 73 with 2 nodes should be truncated") + } + if checks, ok := graphQLCheckRuns(n); ok || checks != nil { + t.Fatalf("truncated rollup: got ok=%v checks=%d, want ok=false nil so enrichPRCI falls back to paginated REST", ok, len(checks)) + } + + complete := decodeGQLPRNode(t, strings.Replace(node, `"totalCount":73`, `"totalCount":2`, 1)) + if graphQLContextsTruncated(complete) { + t.Fatalf("totalCount == len(nodes) must not be truncated") + } + if checks, ok := graphQLCheckRuns(complete); !ok || len(checks) != 2 { + t.Fatalf("complete rollup: got ok=%v checks=%d, want ok=true 2", ok, len(checks)) + } + legacy := decodeGQLPRNode(t, strings.Replace(node, `"totalCount":73,`, ``, 1)) + if checks, ok := graphQLCheckRuns(legacy); !ok || len(checks) != 2 { + t.Fatalf("rollup without totalCount (older fixtures): got ok=%v checks=%d, want ok=true 2", ok, len(checks)) + } +} diff --git a/src/pkg/github/pr_request_signed.go b/src/pkg/github/pr_request_signed.go index 345884abb6..b46ab34604 100644 --- a/src/pkg/github/pr_request_signed.go +++ b/src/pkg/github/pr_request_signed.go @@ -150,6 +150,7 @@ func (c *Client) signBranch(ctx context.Context, owner, repo, base, head string) return "", 0, err } headline, body := signedCommitMessage(comparison.Commits) + body = ensureSignedOffBy(body, c.appBotLogin) // Scratch ref at the merge base. Delete a leftover from a crashed run // first: CreateRef 422s on an existing ref. @@ -384,6 +385,22 @@ func BotSignedOffByTrailer(login string) string { return "Signed-off-by: " + login + " <" + signedTrailerEmail(login+"@"+signedTrailerNoreplyDomain) + ">" } +// ensureSignedOffBy appends the App's own DCO trailer to a signed commit's +// body when none of the folded agent commits carried one. The commit is +// authored by the App bot, so an unsigned body would publish a hive-authored +// commit without sign-off (hivecommons/hive#16619); the trailer is the one +// BotSignedOffByTrailer derives, or nothing when the App login is unknown. +func ensureSignedOffBy(body, appLogin string) string { + if strings.TrimSpace(appLogin) == "" || signedTrailerLineRE.MatchString(body) { + return body + } + trailer := BotSignedOffByTrailer(appLogin) + if strings.TrimSpace(body) == "" { + return trailer + } + return strings.TrimRight(body, "\n") + "\n\n" + trailer +} + // signedTrailersBracketFree rewrites every Signed-off-by line in msg through // signedTrailerEmail, leaving the rest of the message byte-for-byte intact. func signedTrailersBracketFree(msg string) string { diff --git a/src/pkg/github/pr_request_signed_test.go b/src/pkg/github/pr_request_signed_test.go index ca82d8a6fc..f0fd9e42cc 100644 --- a/src/pkg/github/pr_request_signed_test.go +++ b/src/pkg/github/pr_request_signed_test.go @@ -536,6 +536,27 @@ func TestSignedCommitMessage(t *testing.T) { } } +// A signed re-author whose agent commits carried no trailer still publishes +// a signed-off commit (hivecommons/hive#16619); one that already has a +// trailer, or an unknown App login, is left as folded. +func TestEnsureSignedOffBy(t *testing.T) { + t.Setenv(signedTrailerDomainEnv, "") + want := "Signed-off-by: acme-hive[bot] " + if got := ensureSignedOffBy("body one\n\nsecond", "acme-hive[bot]"); got != "body one\n\nsecond\n\n"+want { + t.Errorf("unsigned body: got %q", got) + } + if got := ensureSignedOffBy("", "acme-hive[bot]"); got != want { + t.Errorf("empty body: got %q", got) + } + signed := "body\n\nSigned-off-by: a " + if got := ensureSignedOffBy(signed, "acme-hive[bot]"); got != signed { + t.Errorf("signed body must not gain a second trailer: got %q", got) + } + if got := ensureSignedOffBy("body", ""); got != "body" { + t.Errorf("unknown App login must not invent a trailer: got %q", got) + } +} + func TestGraphQLEndpoint(t *testing.T) { cases := map[string]string{ "https://api.github.com/": "https://api.github.com/graphql", diff --git a/src/pkg/github/push_branch_request_watcher.go b/src/pkg/github/push_branch_request_watcher.go index dd509f6929..73ec561179 100644 --- a/src/pkg/github/push_branch_request_watcher.go +++ b/src/pkg/github/push_branch_request_watcher.go @@ -405,6 +405,18 @@ func (c *Client) handleOnePushBranchRequest(ctx context.Context, path string, no } sha = strings.TrimSpace(sha) + // Every commit a hive identity authors must carry its sign-off before it + // leaves the checkout. An unsigned hive commit on a published branch is + // what later makes the automerge DCO stage re-author the PR + // (hivecommons/hive#16619); refusing it here keeps the fix at the source. + // Hooks are neutralised by pushBranchGitEnv, so the relay checks itself. + if log, err := pushBranchExec(ctx, req.Dir, env, "git", "log", "--no-merges", "--format="+unsignedHiveCommitFormat, sha, "--not", "--remotes"); err == nil { + if bad := unsignedHiveCommits(log, c.pushHiveIdentities()); len(bad) > 0 { + c.denyPushBranchRequest(path, req, fmt.Sprintf("commit %s is authored by hive identity %q without a Signed-off-by trailer; hive-authored commits must be signed off at creation (git commit -s)", bad[0].SHA, bad[0].Author), nowFn) + return + } + } + args := []string{"push"} if req.ForceWithLease { args = append(args, "--force-with-lease") @@ -493,3 +505,79 @@ func WritePushBranchRequest(dir string, req PushBranchRequest) (string, error) { } return path, nil } + +// unsignedHiveCommitFormat is the git log format unsignedHiveCommits parses: +// one record per commit, fields split by US (0x1f), records by RS (0x1e). +const unsignedHiveCommitFormat = "%H%x1f%an%x1f%ae%x1f%B%x1e" + +// unsignedHiveCommit names a commit the push relay refuses. +type unsignedHiveCommit struct { + SHA string + Author string +} + +// pushHiveIdentities lists the logins whose commits must be signed off: the +// App bot and the configured hive identity (ai_author + App login). +func (c *Client) pushHiveIdentities() []string { + var ids []string + if c.appBotLogin != "" { + ids = append(ids, c.appBotLogin) + } + id := c.getHiveIdentity() + ids = append(ids, id.AIAuthor, id.AppLogin) + return ids +} + +// unsignedHiveCommits parses `git log --format=unsignedHiveCommitFormat` +// output and returns the commits authored by one of logins (by name, or by a +// GitHub noreply / App-slug address) whose message has no Signed-off-by +// trailer. Commits by anyone else are not the relay's concern; the DCO check +// on the PR handles those. +func unsignedHiveCommits(log string, logins []string) []unsignedHiveCommit { + var bad []unsignedHiveCommit + for _, rec := range strings.Split(log, "\x1e") { + rec = strings.TrimSpace(rec) + if rec == "" { + continue + } + f := strings.SplitN(rec, "\x1f", 4) + if len(f) < 4 { + continue + } + sha, name, email, msg := strings.TrimSpace(f[0]), strings.TrimSpace(f[1]), strings.TrimSpace(f[2]), f[3] + login := hiveIdentityForCommitter(name, email, logins) + if login == "" || signedTrailerLineRE.MatchString(msg) { + continue + } + bad = append(bad, unsignedHiveCommit{SHA: sha, Author: login}) + } + return bad +} + +// hiveIdentityForCommitter returns the login in logins that name/email +// belongs to, or "" when the committer is not a hive identity. A login +// matches its own name, "@users.noreply.github.com", +// "+@users.noreply.github.com", and (for "[bot]") the +// bracket-free "@…" address signedTrailerEmail derives. +func hiveIdentityForCommitter(name, email string, logins []string) string { + email = strings.ToLower(email) + local := email + if i := strings.IndexByte(email, '@'); i >= 0 { + local = email[:i] + } + if i := strings.IndexByte(local, '+'); i >= 0 { + local = local[i+1:] + } + for _, login := range logins { + login = strings.TrimSpace(login) + if login == "" { + continue + } + slug := strings.TrimSuffix(login, "[bot]") + if strings.EqualFold(name, login) || strings.EqualFold(name, slug) || + strings.EqualFold(local, login) || strings.EqualFold(local, slug) { + return login + } + } + return "" +} diff --git a/src/pkg/github/push_branch_request_watcher_test.go b/src/pkg/github/push_branch_request_watcher_test.go index d8d2bd8898..2ca68f8ff8 100644 --- a/src/pkg/github/push_branch_request_watcher_test.go +++ b/src/pkg/github/push_branch_request_watcher_test.go @@ -99,10 +99,10 @@ func TestPushBranchRequestWatcher_PushesAndConsumes(t *testing.T) { if !resp.OK || resp.Branch != "scanner/fix-1" || resp.SHA != "cafe1234" { t.Errorf("result = %+v, want ok with branch and sha", resp) } - if len(*calls) != 2 { - t.Fatalf("git calls = %d, want rev-parse + push", len(*calls)) + if len(*calls) != 3 { + t.Fatalf("git calls = %d, want rev-parse + sign-off log + push", len(*calls)) } - push := (*calls)[1] + push := (*calls)[2] joined := strings.Join(push.args, " ") if push.dir != checkout || !strings.Contains(joined, "https://github.com/o/r.git") || @@ -136,10 +136,10 @@ func TestPushBranchRequestWatcher_ForceWithLease(t *testing.T) { } c.ProcessPushBranchRequestsOnce(context.Background()) - if len(*calls) != 2 { - t.Fatalf("git calls = %d, want 2", len(*calls)) + if len(*calls) != 3 { + t.Fatalf("git calls = %d, want 3", len(*calls)) } - if joined := strings.Join((*calls)[1].args, " "); !strings.Contains(joined, "--force-with-lease") || strings.Contains(joined, " --force ") { + if joined := strings.Join((*calls)[2].args, " "); !strings.Contains(joined, "--force-with-lease") || strings.Contains(joined, " --force ") { t.Errorf("push args = %q, want --force-with-lease and never a plain --force", joined) } } @@ -392,3 +392,60 @@ func TestPushBranchGitEnv_NoHeader(t *testing.T) { t.Errorf("env missing core.hooksPath override: %q", joined) } } + +// A branch carrying a hive-authored commit without a Signed-off-by trailer +// is refused before anything reaches GitHub (hivecommons/hive#16619); the +// same commit by an outside contributor is the PR DCO check's business. +func TestPushBranchRequestWatcher_RefusesUnsignedHiveCommit(t *testing.T) { + c := pushTestClient(t, "http://127.0.0.1:1") + c.SetHiveIdentity(HiveIdentity{AIAuthor: "thatguywob", AppLogin: "hivecommons-hive[bot]"}) + dir := withPushDir(t) + var calls []pushExecCall + old := pushBranchExec + pushBranchExec = func(_ context.Context, _ string, _ []string, name string, args ...string) (string, error) { + calls = append(calls, pushExecCall{args: append([]string{name}, args...)}) + switch args[0] { + case "rev-parse": + return "cafe1234\n", nil + case "log": + return "cafe1234\x1fthatguywob\x1fthatguywob@users.noreply.github.com\x1ffix: thing\n\nbody\n\x1e" + + "beef5678\x1fscanner\x1f280983584+hivecommons-hive[bot]@users.noreply.github.com\x1ffix: other\n\nSigned-off-by: scanner \n\x1e", nil + } + return "", nil + } + t.Cleanup(func() { pushBranchExec = old }) + + reqPath, err := WritePushBranchRequest(dir, PushBranchRequest{Repo: "o/r", Branch: "scanner/fix-3", Dir: t.TempDir(), Agent: "scanner"}) + if err != nil { + t.Fatal(err) + } + c.ProcessPushBranchRequestsOnce(context.Background()) + + resp := readPushBranchResult(t, reqPath) + if resp.OK || !strings.Contains(resp.Error, "cafe1234") || !strings.Contains(resp.Error, "thatguywob") || !strings.Contains(resp.Error, "Signed-off-by") { + t.Errorf("result = %+v, want a denial naming the unsigned hive commit", resp) + } + for _, call := range calls { + if call.args[1] == "push" { + t.Fatalf("unsigned hive commit was pushed: %v", call.args) + } + } + if _, err := os.Stat(reqPath + ".denied"); err != nil { + t.Errorf("denied request not parked: %v", err) + } +} + +func TestUnsignedHiveCommits(t *testing.T) { + logins := []string{"hivecommons-hive[bot]", "thatguywob"} + log := "a1\x1fthatguywob\x1fthatguywob@users.noreply.github.com\x1fsubject\n\x1e" + + "a2\x1fscanner\x1f280983584+hivecommons-hive[bot]@users.noreply.github.com\x1fsubject\n\x1e" + + "a3\x1fhivecommons-hive[bot]\x1fhivecommons-hive@hive.kubestellar.io\x1fsubject\n\nSigned-off-by: hivecommons-hive[bot] \n\x1e" + + "a4\x1fMallory\x1fmallory@example.com\x1fsubject\n\x1e" + got := unsignedHiveCommits(log, logins) + if len(got) != 2 || got[0].SHA != "a1" || got[0].Author != "thatguywob" || got[1].SHA != "a2" || got[1].Author != "hivecommons-hive[bot]" { + t.Errorf("unsignedHiveCommits = %+v, want a1 (ai_author) and a2 (App by noreply address) only", got) + } + if got := unsignedHiveCommits("", logins); len(got) != 0 { + t.Errorf("empty log flagged %+v", got) + } +} diff --git a/src/pkg/github/webhook_cache.go b/src/pkg/github/webhook_cache.go index 0c8d18ae94..5835d8137d 100644 --- a/src/pkg/github/webhook_cache.go +++ b/src/pkg/github/webhook_cache.go @@ -704,6 +704,25 @@ func webhookIssueDirtyTarget(event string, p webhookEventPayload) (int, bool) { return 0, false } +// webhookIssuePullRequestMerged reads the merge instant the `issue` object +// of an `issues` / `issue_comment` delivery carries for a pull request +// (`issue.pull_request.merged_at`). A bot's comment on a PR that just +// merged used to produce a closed-but-not-merged snapshot — the tracker +// then listed the merged PR in recently_closed and the SPA said "closed", +// forfeiting the merge celebration (hivecommons/hive#16658). +func webhookIssuePullRequestMerged(raw *json.RawMessage) bool { + if raw == nil || len(*raw) == 0 { + return false + } + var pr struct { + MergedAt *time.Time `json:"merged_at"` + } + if err := json.Unmarshal(*raw, &pr); err != nil { + return false + } + return pr.MergedAt != nil && !pr.MergedAt.IsZero() +} + // webhookItemHint is the payload's state for the issue or pull request an // `issues`, `issue_comment` or `pull_request*` delivery embeds; nil when the // event carries neither object. @@ -723,7 +742,8 @@ func webhookItemHint(event string, p webhookEventPayload) *WebhookItemHint { if p.Issue == nil || p.Issue.Number <= 0 { return nil } - h := &WebhookItemHint{Number: p.Issue.Number, IsPR: p.Issue.PullRequest != nil, State: p.Issue.State} + h := &WebhookItemHint{Number: p.Issue.Number, IsPR: p.Issue.PullRequest != nil, State: p.Issue.State, + Merged: webhookIssuePullRequestMerged(p.Issue.PullRequest)} if p.Issue.UpdatedAt != nil { h.UpdatedAt = *p.Issue.UpdatedAt } diff --git a/src/pkg/github/webhook_issue_pr_merged_test.go b/src/pkg/github/webhook_issue_pr_merged_test.go new file mode 100644 index 0000000000..660e4a9dfa --- /dev/null +++ b/src/pkg/github/webhook_issue_pr_merged_test.go @@ -0,0 +1,42 @@ +package github + +import ( + "encoding/json" + "testing" + "time" +) + +// TestWebhookItemHintIssueCommentOnMergedPR (hivecommons/hive#16658): +// an issues / issue_comment delivery on a pull request reads the merge +// from issue.pull_request.merged_at, so a bot's comment on a PR that just +// merged is a merged hint, not a closed-unmerged one; an open PR's null +// merged_at and a plain issue stay unmerged. +func TestWebhookItemHintIssueCommentOnMergedPR(t *testing.T) { + at := time.Date(2026, 10, 20, 19, 35, 26, 0, time.UTC) + for _, tc := range []struct { + name string + body string + isPR bool + merged bool + }{ + {"merged PR", `{"issue":{"number":16644,"state":"closed","pull_request":{"url":"u","merged_at":"2026-10-20T19:35:26Z"}}}`, true, true}, + {"open PR", `{"issue":{"number":16644,"state":"open","pull_request":{"url":"u","merged_at":null}}}`, true, false}, + {"closed unmerged PR", `{"issue":{"number":16644,"state":"closed","pull_request":{"url":"u"}}}`, true, false}, + {"issue", `{"issue":{"number":16644,"state":"closed"}}`, false, false}, + } { + var p webhookEventPayload + if err := json.Unmarshal([]byte(tc.body), &p); err != nil { + t.Fatal(err) + } + for _, event := range []string{"issue_comment", "issues"} { + h := webhookItemHint(event, p) + if h == nil || h.Number != 16644 || h.IsPR != tc.isPR || h.Merged != tc.merged { + t.Errorf("%s/%s: hint = %+v, want is_pr=%v merged=%v", tc.name, event, h, tc.isPR, tc.merged) + } + } + } + raw := json.RawMessage(`{"merged_at":"` + at.Format(time.RFC3339) + `"}`) + if !webhookIssuePullRequestMerged(&raw) || webhookIssuePullRequestMerged(nil) { + t.Fatal("webhookIssuePullRequestMerged: want true for a merge instant, false for no object") + } +} diff --git a/src/pkg/hub/assets/dashboard.html b/src/pkg/hub/assets/dashboard.html index 9b9cfce82e..47c19648f8 100644 --- a/src/pkg/hub/assets/dashboard.html +++ b/src/pkg/hub/assets/dashboard.html @@ -260,7 +260,8 @@ .hive-group-head:hover td { color: var(--text) !important; } .hive-group-caret { display: inline-block; width: 12px; font-size: 0.7rem; } .table-wrap { overflow: visible; margin: 0 auto; position: relative; } - .hive-menu-cell:hover .hive-menu-dropdown { display: block !important; } + .hive-menu-cell:hover .hive-menu-dropdown, + .hive-menu-cell:focus-within .hive-menu-dropdown { display: block !important; } .hive-menu-item { display: block; padding: var(--sp-3) var(--sp-5); color: var(--text); text-decoration: none; font-size: var(--fs-sm); cursor: pointer; } .hive-menu-dropdown a:hover, .hive-menu-dropdown div[onclick]:hover { background: color-mix(in srgb,var(--hub-dashboard-accent) 8%,transparent); border-radius: var(--r-sm); } .table-wrap::-webkit-scrollbar { height: 10px; display: block; } @@ -613,6 +614,40 @@ .repo-link { color: var(--blue); font-size: 0.8rem; } .hive-name-link { color: #58a6ff; font-weight: 700; text-decoration: none; } .hive-name-link:hover { color: #79c0ff; text-decoration: underline; } + /* "Open hive ↗" affordance on the hive-name link. A new owner reads the + bold name as a label, not a door: the glyph says it leaves the hub. Kept + faint at rest and lifted on hover so dense rows stay quiet. */ + .hive-name-link .open-glyph { display: inline-block; opacity: 0.55; font-size: var(--fs-xs); margin-left: 4px; transform: translateY(-2px); transition: opacity var(--duration-fast), transform var(--duration-fast); } + .hive-name-link:hover .open-glyph { opacity: 1; transform: translate(1px, -3px); } + + /* ── Spoke pointer ── + The hub LISTS hives; a hive's own dashboard, Guide, settings and GitHub + App install live inside the hive (the spoke). New owners miss that and + hunt the hub for a Guide that is not here, so this callout names their + hive, links it with the SAME href the row uses, and says where the ⋯ row + menu is. Rendered by renderSpokePointer(); dismissal is per user + hive + in localStorage and re-arms when a NEW attention kind appears. */ + #spoke-pointer { margin-bottom: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-4); } + #spoke-pointer[hidden] { display: none; } + .spoke-callout { position: relative; border: 1px solid color-mix(in srgb, var(--hub-dashboard-accent) 45%, transparent); border-left: 4px solid var(--hub-dashboard-accent); border-radius: var(--r-lg); background: color-mix(in srgb, var(--hub-dashboard-accent) 9%, var(--surface)); padding: var(--sp-5) calc(var(--sp-9) + var(--sp-5)) var(--sp-5) var(--sp-6); display: grid; gap: var(--sp-3); } + .spoke-callout-title { font-size: var(--fs-md); font-weight: 700; display: flex; align-items: center; gap: var(--sp-4); flex-wrap: wrap; } + .spoke-callout-title .hive-name-link { font-size: var(--fs-lg); } + .spoke-open-btn { display: inline-flex; align-items: center; gap: var(--sp-3); background: var(--brand); color: var(--surface-0); font-weight: 700; font-size: var(--fs-sm); padding: var(--sp-2) var(--sp-5); border-radius: var(--r-pill); text-decoration: none !important; } + .spoke-callout-line { font-size: var(--fs-base); color: var(--muted); line-height: 1.5; } + .spoke-callout-line b { color: var(--text); font-weight: 600; } + .spoke-callout-fix { font-size: var(--fs-base); color: var(--text); display: flex; align-items: center; gap: var(--sp-3); flex-wrap: wrap; } + .spoke-callout-fix .spoke-warnmark { color: var(--status-warn); } + .spoke-callout-crumb { display: inline-flex; align-items: center; gap: var(--sp-3); } + .spoke-callout-crumb span { background: color-mix(in srgb, var(--text) 6%, transparent); border: 1px solid var(--border); border-radius: var(--r-sm); padding: var(--sp-1) var(--sp-3); font-size: var(--fs-xs); font-weight: 600; } + .spoke-callout-dismiss { position: absolute; top: var(--sp-4); right: var(--sp-4); background: none; border: 1px solid transparent; color: var(--muted); font-size: var(--fs-lg); line-height: 1; width: var(--sp-8); height: var(--sp-8); border-radius: var(--r-sm); cursor: pointer; font-family: inherit; } + .spoke-callout-dismiss:hover { border-color: var(--border); color: var(--text); background: color-mix(in srgb, var(--text) 5%, transparent); } + .spoke-kbd-dots { display: inline-grid; place-items: center; min-width: var(--sp-7); height: var(--sp-6); padding: var(--sp-0) var(--sp-2); border: 1px solid var(--border); border-radius: var(--r-sm); background: color-mix(in srgb, var(--text) 5%, transparent); font-size: var(--fs-base); line-height: 1; color: var(--text); vertical-align: -3px; } + /* Spotlight on the row link the callout points at: the same blue the + "Attention needed" jump uses (.hive-row-targeted), pulsing briefly so + the eye lands on the link and then rests. */ + .spoke-spot { border-radius: var(--r-sm); animation: spokeSpotPulse 1.3s ease-out 3; } + @keyframes spokeSpotPulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--hub-dashboard-accent) 65%, transparent); } 70% { box-shadow: 0 0 0 var(--sp-5) transparent; } 100% { box-shadow: 0 0 0 0 transparent; } } + @media (prefers-reduced-motion: reduce) { .spoke-spot { animation: none; box-shadow: 0 0 0 2px color-mix(in srgb, var(--hub-dashboard-accent) 65%, transparent); } } .hive-sub-link { color: #6b7280; font-weight: 400; text-decoration: none; } /* Inline action inside the restart-storms pill: inherits the pill's font/colour so it never inflates the pill. */ .reset-agent-restarts { all: unset; cursor: pointer; margin-left: var(--sp-2); padding-left: var(--sp-2); border-left: 1px solid; border-color: inherit; font: inherit; color: inherit; text-decoration: underline; text-underline-offset: 2px; } @@ -796,6 +831,10 @@

    + + @@ -4479,8 +4518,15 @@

    ' + + '' + esc(labels.join(', ')) + ' needs fixing inside your hive: ' + + 'Open it → 🧭 Guide → Install the Forge App

  • '; + } + + var SPOKE_POINTER_LIST_LINE = '
    The hub only lists hives. Your hive’s own dashboard, 🧭 Guide, settings and the GitHub App install live inside the hive.
    '; + var SPOKE_POINTER_MENU_LINE = '
    Use ⋮ on your hive’s row to manage permissions, pause, funding or delete.
    '; + + function spokeDismissButton(idsCsv) { + return ''; + } + + function spokeCalloutFull(h) { + var name = hiveLabel(h).line1 || h.name || h.id; + return '
    ' + + '
    Your hive' + spokeOpenLink(h, name, 'hive-name-link') + + 'is ready→' + spokeOpenLink(h, 'Open your hive ↗', 'spoke-open-btn') + '
    ' + + SPOKE_POINTER_LIST_LINE + spokePointerFixLine(h) + SPOKE_POINTER_MENU_LINE + + spokeDismissButton(String(h.id)) + '
    '; + } + + function spokeCalloutCompact(hives) { + var links = hives.map(function(h) { return spokeOpenLink(h, hiveLabel(h).line1 || h.name || h.id, 'hive-name-link'); }).join(' · '); + var needFix = hives.filter(function(h) { return spokeAttentionKinds(h).length > 0; }); + var fix = needFix.length + ? '
    ' + + esc(needFix.map(function(h) { return hiveLabel(h).line1 || h.name || h.id; }).join(', ')) + ' ' + + (needFix.length === 1 ? 'needs' : 'need') + ' fixing inside the hive: ' + + 'Open it → 🧭 Guide → Install the Forge App
    ' + : ''; + var ids = hives.map(function(h) { return String(h.id); }).join(','); + return '
    ' + + '
    Your hives are ready→' + links + '
    ' + + SPOKE_POINTER_LIST_LINE + fix + SPOKE_POINTER_MENU_LINE + spokeDismissButton(ids) + '
    '; + } + + /* renderSpokePointer draws the callout(s) for the viewer's own hives: + assigned (non-placeholder) hives with a usable link, owners first and + hives with attention before quiet ones, minus the ones dismissed. */ + function renderSpokePointer(assignedHives) { + var el = document.getElementById('spoke-pointer'); + if (!el) return; + _spokePointerHives = (assignedHives || []).filter(function(h) { return h && h.id && !isPlaceholderHive(h) && spokeOpenLink(h, 'x', 'hive-name-link'); }); + if (_isAdmin || !_spokePointerHives.length) { el.hidden = true; el.innerHTML = ''; return; } + var show = _spokePointerHives.filter(function(h) { return !spokePointerDismissed(h); }); + if (!show.length) { el.hidden = true; el.innerHTML = ''; return; } + show.sort(function(a, b) { + var ao = a.role === 'owner' ? 0 : 1, bo = b.role === 'owner' ? 0 : 1; + if (ao !== bo) return ao - bo; + var aa = spokeAttentionKinds(a).length ? 0 : 1, ba = spokeAttentionKinds(b).length ? 0 : 1; + if (aa !== ba) return aa - ba; + return String(a.name || a.id).localeCompare(String(b.name || b.id)); + }); + el.innerHTML = show.length <= SPOKE_POINTER_MAX_FULL + ? show.map(spokeCalloutFull).join('') + : spokeCalloutCompact(show); + el.hidden = false; + /* Spotlight the row link the callout points at, once per hive per page + load. Deferred: renderHives draws the table AFTER this callout. */ + setTimeout(function() { + show.forEach(function(h) { + if (_spokeSpotDone[h.id]) return; + var row = document.getElementById(hiveRowDomId(h.id)); + var link = row ? row.querySelector('.hive-name-link') : null; + if (!link) return; + _spokeSpotDone[h.id] = true; + link.classList.add('spoke-spot'); + }); + }, 0); + } + function renderHives(allHives, force) { allHives = allHives || []; /* Defer the whole render while a branch/channel menu is open. Skipping @@ -8614,6 +8843,9 @@

    ' + bulkCheckboxCell(h, section || 'all') + - '' + ('⋮' + pendingBadge + '') + '' + + '' + ('⋮' + pendingBadge + '') + '' + '' + (function() { var isHostedRow = h.hiveType === 'hosted' || (h.id && (h.id.startsWith('hosted-') || h.id.startsWith('saas-'))); var dh = isHostedRow && h.id ? ('/api/saas/hives/' + encodeURIComponent(h.id) + '/open') : (rb ? esc(rb) : ''); /* Label derived from the PROJECT (org + primary repo), not by splitting h.name — see hiveLabel. */ var label = hiveLabel(h); var orgName = label.line1; var repoName = label.line2; /* rp is the repo path shown in the GitHub-icon tooltip; use the same doubling-safe path the label shows (repoDisplayLine / hiveLabel), never org + '/' + primaryRepo which doubles the owner on a github.io/GHE hive whose primaryRepo is already 'owner/repo'. */ var rp = repoName || ''; /* The icon href must resolve to a real GitHub path. When primaryRepo already carries 'owner/repo', that pair IS the owner/repo the URL needs (not org, which may be a mis-parsed host); otherwise fall back to org + primaryRepo. */ var hasRepoPath = h.primaryRepo && h.primaryRepo.indexOf('/') !== -1; var rpOwner = hasRepoPath ? h.primaryRepo.split('/')[0] : h.org; var rpName = hasRepoPath ? h.primaryRepo.split('/').slice(1).join('/') : h.primaryRepo; var rpHref = ghRepoURL(hiveForgeHost(h), rpOwner, rpName); var ghIcon = (rp && rpHref) ? '' : (rp ? '' : ''); /* vanityDisplay is the friendly host shown in the status bar on hover. rb is resolvedBase(h), which the hub has already overlaid with the claimed vanity_url; it is only a DISPLAY url here, never the click target — see ssoDisplayLink. Empty for a row with no vanity host, which falls back to today's /open href. Only meaningful on hosted rows: a non-hosted row's dh IS rb already. */ var vanityDisplay = isHostedRow && rb ? rb : ''; var link = function(text, bold) { if (dh) { return ssoDisplayLink(dh, vanityDisplay, text, bold ? 'hive-name-link' : 'hive-sub-link'); } var s = bold ? 'font-weight:700;color:inherit' : 'color:#6b7280;font-weight:400'; return '' + esc(text) + ''; }; /* repoLink wraps the second line (the org/repo) in a link to the ACTUAL FORGE REPO (github.com / GHE host), NOT the spoke dashboard: the top line already opens the dashboard, so the repo path should take an operator to the code. rpHref is the same doubling-safe forge URL the GitHub icon uses (ghRepoURL(hiveForgeHost(h), rpOwner, rpName)); when it is empty (BYO/mis-parsed host) fall back to plain non-link text, never to the dashboard. */ var repoLink = function(text) { if (rpHref) { return '' + esc(text) + ''; } return '' + esc(text) + ''; }; var line1 = dot + ' ' + link(orgName, true) + heartbeatHeart(h) + nameEditAffordance(h); var fcPill = h.online ? failingCheckSummary(h) : ''; /* Advisory-staleness pill sits right beside the failing-check pill: both are "something is quietly wrong with this working hive" signals, and advisoryStaleSummary already self-suppresses (empty string) unless the hub flagged the digest stale, so unaffected rows are pixel-identical. */ var advPill = h.online ? advisoryStaleSummary(h) : ''; /* Advisory finding-count pill rides beside the staleness pill and carries the "(top N)" marker when the spoke capped its digest. */ var advCountPill = h.online ? advisoryFindingsSummary(h) : ''; /* Dead-link pill is deliberately NOT gated on h.online: the entire point is a hive that IS online and heartbeating while its public URL is broken, so gating it the way the other pills are gated would hide exactly the case it exists to surface. */ var dlPill = deadLinkSummary(h); var privatePill = privateURLSummary(h); /* Inference-auth pill: like the dead-link pill it is NOT gated on h.online, because the hive being online while every inference call 401s is exactly the case it surfaces. */ var iaPill = inferenceAuthSummary(h); var rsPill = restartStormSummary(h); /* Inline access faces sit on the name cell's second line, immediately after this row's own role badge: the badge already answers "what am I on this hive", so the co-members read as the natural continuation of the same thought, in the one cell that is left-aligned and has room to grow. It also keeps them out of the 16 dense metric columns, none of which is about people. Empty string when the viewer is the only member, so those rows are pixel-identical to today. */ var accessFaces = hiveAccessAvatars(h); /* Keyed off repoName, not orgName: line 1 now always carries SOME identity, so the presence of a second line is decided purely by whether there is a repo to put on it. Without a repo the row still shows the GitHub icon, role badge, faces and failing-check pill on the compact variant. */ var line2 = repoName ? '
    ' + repoLink(repoName) + ' ' + ghIcon + ' ' + roleBadge(h.role) + accessFaces + fcPill + advPill + advCountPill + dlPill + privatePill + iaPill + rsPill + '
    ' : '
    ' + ghIcon + ' ' + roleBadge(h.role) + accessFaces + fcPill + advPill + advCountPill + dlPill + privatePill + iaPill + rsPill + '
    '; var line3 = pendingPill ? '
    ' + pendingPill + '
    ' : ''; return line1 + line2 + line3; })() + '' + '' + locationCell + '' + '' + uptimeCell(h) + '' + diff --git a/src/pkg/hub/github_warn_dedupe.go b/src/pkg/hub/github_warn_dedupe.go index fe06dbee26..88d52cd5cd 100644 --- a/src/pkg/hub/github_warn_dedupe.go +++ b/src/pkg/hub/github_warn_dedupe.go @@ -40,21 +40,33 @@ func warnGitHubFetchOnce(logger *slog.Logger, key, msg string, args ...any) { logger.Debug(msg, args...) } -// commitMsgBackoff is how long a SHA whose commit-message fetch failed (e.g. -// 403 rate limit) is left alone before it is fetched again; callers carry on -// with the SHA alone meanwhile. -const commitMsgBackoff = 10 * time.Minute +// commitMsgBackoff is how long a SHA whose commit-message fetch failed is left +// alone before it is fetched again; callers carry on with the SHA alone +// meanwhile. It is also the fallback global back-off for a 403/429 that carries +// no reset hint. A 403/429 is a client-wide condition (rate limit or a token +// without access), so it additionally parks every SHA until +// commitMsgGlobalBackoffUntil, capped at commitMsgGlobalBackoffMax. +const ( + commitMsgBackoff = 10 * time.Minute + commitMsgGlobalBackoffMax = time.Hour +) var ( commitMsgBackoffMu sync.Mutex commitMsgBackoffUntil = map[string]time.Time{} + + commitMsgGlobalBackoffUntil time.Time ) func commitMsgBackedOff(sha string) bool { commitMsgBackoffMu.Lock() defer commitMsgBackoffMu.Unlock() + now := githubWarnNow() + if now.Before(commitMsgGlobalBackoffUntil) { + return true + } until, ok := commitMsgBackoffUntil[sha] - return ok && githubWarnNow().Before(until) + return ok && now.Before(until) } func markCommitMsgBackoff(sha string) { @@ -65,3 +77,10 @@ func markCommitMsgBackoff(sha string) { } commitMsgBackoffUntil[sha] = githubWarnNow().Add(commitMsgBackoff) } + +// markCommitMsgGlobalBackoff parks every commit-message fetch for d. +func markCommitMsgGlobalBackoff(d time.Duration) { + commitMsgBackoffMu.Lock() + defer commitMsgBackoffMu.Unlock() + commitMsgGlobalBackoffUntil = githubWarnNow().Add(d) +} diff --git a/src/pkg/hub/saas_dashboard_myhives_ux_test.go b/src/pkg/hub/saas_dashboard_myhives_ux_test.go index a790c68242..296f8c7559 100644 --- a/src/pkg/hub/saas_dashboard_myhives_ux_test.go +++ b/src/pkg/hub/saas_dashboard_myhives_ux_test.go @@ -220,3 +220,53 @@ func TestAssignHiveStillAdminOnlyForUserFirstFlow(t *testing.T) { t.Fatalf("admin assign did not claim the placeholder: %+v", h) } } + +// TestDashboardSpokePointer guards the "your hive is not the hub" callout and +// the two row affordances it points at. The incident it exists for: a new +// owner read "Open your hive dashboard → Guide (top navbar)" on My Hives and +// replied "I do not see any guide or setting option" — because the hub lists +// hives and the Guide lives inside the hive. The callout, the ↗ glyph on the +// hive-name link and the ⋮ hint are all string-built markup, so this is the +// only place their wiring is asserted. +func TestDashboardSpokePointer(t *testing.T) { + html := dashScript(t) + for _, fn := range []string{ + "renderSpokePointer", + "dismissSpokePointer", + "spokeAttentionKinds", + "spokePointerDismissed", + "spokeOpenLink", + } { + if !strings.Contains(html, "function "+fn+"(") { + t.Errorf("dashboardHTML is missing a definition for %s()", fn) + } + } + for _, want := range []string{ + // Container the renderer writes into, above the usage/attention strip. + `id="spoke-pointer"`, + // Drawn from the same render pass as the alerts panel it reads. + "renderAlertsPanel();", + "renderSpokePointer(assignedAll);", + // Dismissal is per viewer + hive and re-arms on a new attention kind. + "LS_SPOKE_POINTER_PREFIX", + "localStorage.setItem(spokePointerKey(", + // The callout's hive link reuses the row's href decision (SSO /open). + "ssoDisplayLink(dh, isHostedRow && rb ? rb : '', text, cls)", + // Row affordances: the ↗ glyph on the bold hive-name link, and the + // ⋮ hint naming what the row menu manages. + `class="open-glyph"`, + "Manage: permissions, pause, funding, delete…", + `title="' + HIVE_MENU_HINT + '"`, + // Copy the incident turned on: where the Guide actually is. + "live inside the hive", + "Install the Forge App", + } { + if !strings.Contains(html, want) { + t.Errorf("dashboardHTML is missing %q", want) + } + } + // Admin viewers never see the callout: their My Hives is the fleet. + if !strings.Contains(html, "if (_isAdmin || !_spokePointerHives.length)") { + t.Error("renderSpokePointer must short-circuit for hub admins") + } +} diff --git a/src/pkg/hub/saas_sha_poller.go b/src/pkg/hub/saas_sha_poller.go index 7277ba16e1..6c04fc0e9f 100644 --- a/src/pkg/hub/saas_sha_poller.go +++ b/src/pkg/hub/saas_sha_poller.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path/filepath" + "strconv" "strings" "sync" "time" @@ -1057,6 +1058,9 @@ func fetchImageBuildState(client *http.Client, fullSHA string, logger *slog.Logg // non-200 parks the SHA for commitMsgBackoff. The back-off is keyed on the // short SHA so the poll path (full SHA) and the backfill path (short SHA) share // one entry per commit. +// A 403/429 is a client-wide throttle, not a per-SHA failure: it parks every +// SHA until the rate limit resets and warns once per window, otherwise N +// branches with distinct SHAs would emit N warns and trip the fleet report. func fetchCommitMessage(client *http.Client, fullSHA string, logger *slog.Logger) string { backoffKey := shortSHA(fullSHA) if commitMsgBackedOff(backoffKey) { @@ -1075,6 +1079,12 @@ func fetchCommitMessage(client *http.Client, fullSHA string, logger *slog.Logger defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { markCommitMsgBackoff(backoffKey) + if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests { + wait := commitMsgThrottleWait(resp.Header, githubWarnNow()) + markCommitMsgGlobalBackoff(wait) + warnGitHubFetchOnce(logger, fmt.Sprintf("sha-msg:throttled:%d", resp.StatusCode), "SHA poll: commit message fetch non-200", "sha", fullSHA[:7], "status", resp.StatusCode, "retry_in", wait.String()) + return "" + } warnGitHubFetchOnce(logger, fmt.Sprintf("sha-msg:%s:%d", fullSHA[:7], resp.StatusCode), "SHA poll: commit message fetch non-200", "sha", fullSHA[:7], "status", resp.StatusCode) return "" } @@ -1093,6 +1103,25 @@ func fetchCommitMessage(client *http.Client, fullSHA string, logger *slog.Logger return msg } +// commitMsgThrottleWait derives the global back-off from Retry-After first, +// then X-RateLimit-Reset, falling back to commitMsgBackoff; capped at +// commitMsgGlobalBackoffMax. Retry-After wins because GitHub sends +// X-RateLimit-Reset on every response, so a secondary-rate-limit 403 with +// Retry-After: 60 must park fetches for ~60s, not until the primary window +// resets. +func commitMsgThrottleWait(h http.Header, now time.Time) time.Duration { + wait := commitMsgBackoff + if secs, err := strconv.Atoi(h.Get("Retry-After")); err == nil && secs > 0 { + wait = time.Duration(secs) * time.Second + } else if reset, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil && time.Unix(reset, 0).After(now) { + wait = time.Unix(reset, 0).Sub(now) + } + if wait > commitMsgGlobalBackoffMax { + wait = commitMsgGlobalBackoffMax + } + return wait +} + // backfillCommitMessage fills in a missing commit message for an already-cached SHA. // Called when the branches API is rate-limited but we have the SHA from a prior poll. func backfillCommitMessage(client *http.Client, branch string, logger *slog.Logger) { diff --git a/src/pkg/hub/sha_fetch_coverage_test.go b/src/pkg/hub/sha_fetch_coverage_test.go index 4185a204f4..1cbc6fc219 100644 --- a/src/pkg/hub/sha_fetch_coverage_test.go +++ b/src/pkg/hub/sha_fetch_coverage_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "strconv" "strings" "testing" "time" @@ -298,6 +299,7 @@ func resetSHACaches(t *testing.T) { // -shuffle=on. commitMsgBackoffMu.Lock() commitMsgBackoffUntil = map[string]time.Time{} + commitMsgGlobalBackoffUntil = time.Time{} commitMsgBackoffMu.Unlock() } @@ -345,7 +347,8 @@ func TestFetchCommitMessageBacksOffPerSHA(t *testing.T) { // TestFetchCommitMessageWarnsOncePerDistinctSHA pins the contract the // sha_poll_commit_message_unavailable fleet-report class relies on -// (src/docs/fleet-report.md): the WARN is deduped per (SHA, status), so the +// (src/docs/fleet-report.md): the WARN is deduped per (SHA, status) for +// per-SHA failures such as 404 (403/429 are client-wide, see below), so the // class's 5-in-10-min threshold is only reachable when five distinct commits // fail, never by one commit failing repeatedly. func TestFetchCommitMessageWarnsOncePerDistinctSHA(t *testing.T) { @@ -358,7 +361,7 @@ func TestFetchCommitMessageWarnsOncePerDistinctSHA(t *testing.T) { t.Cleanup(func() { githubWarnNow = time.Now }) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusNotFound) })) defer srv.Close() var buf bytes.Buffer @@ -382,3 +385,99 @@ func TestFetchCommitMessageWarnsOncePerDistinctSHA(t *testing.T) { t.Fatalf("warns for 5 distinct SHAs = %d, want 5", n) } } + +func TestFetchCommitMessageThrottleBacksOffAllSHAs(t *testing.T) { + resetSHACaches(t) + githubWarnMu.Lock() + githubWarnLast = map[string]time.Time{} + githubWarnMu.Unlock() + now := time.Now() + githubWarnNow = func() time.Time { return now } + t.Cleanup(func() { githubWarnNow = time.Now }) + + hits := 0 + reset := now.Add(20 * time.Minute) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits++ + w.Header().Set("X-RateLimit-Reset", strconv.FormatInt(reset.Unix(), 10)) + w.WriteHeader(http.StatusForbidden) + })) + defer srv.Close() + var buf bytes.Buffer + logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})) + c := clientTo(t, srv) + + for _, sha := range []string{"1111111aaaa", "2222222bbbb", "3333333cccc"} { + fetchCommitMessage(c, sha, logger) + } + if hits != 1 { + t.Errorf("server hits across distinct SHAs = %d, want 1", hits) + } + if n := strings.Count(buf.String(), "level=WARN"); n != 1 { + t.Errorf("warns across distinct SHAs = %d, want 1", n) + } + + // Past the per-SHA back-off but before X-RateLimit-Reset: still parked. + now = now.Add(commitMsgBackoff + time.Second) + fetchCommitMessage(c, "4444444dddd", logger) + if hits != 1 { + t.Errorf("server hits before reset = %d, want 1", hits) + } + + now = reset.Add(time.Second) + fetchCommitMessage(c, "4444444dddd", logger) + if hits != 2 { + t.Errorf("server hits after reset = %d, want 2", hits) + } +} + +func TestCommitMsgThrottleWaitPrefersRetryAfter(t *testing.T) { + // X-RateLimit-Reset is whole epoch seconds, so keep now second-aligned. + now := time.Now().Truncate(time.Second) + h := http.Header{} + h.Set("X-RateLimit-Reset", strconv.FormatInt(now.Add(50*time.Minute).Unix(), 10)) + h.Set("Retry-After", "60") + if got := commitMsgThrottleWait(h, now); got != 60*time.Second { + t.Errorf("wait with Retry-After and X-RateLimit-Reset = %v, want 60s", got) + } + + h.Del("Retry-After") + if got := commitMsgThrottleWait(h, now); got != 50*time.Minute { + t.Errorf("wait with only X-RateLimit-Reset = %v, want 50m", got) + } + + h.Set("X-RateLimit-Reset", strconv.FormatInt(now.Add(-time.Minute).Unix(), 10)) + if got := commitMsgThrottleWait(h, now); got != commitMsgBackoff { + t.Errorf("wait with stale reset = %v, want %v", got, commitMsgBackoff) + } + + h.Set("Retry-After", strconv.Itoa(int((commitMsgGlobalBackoffMax+time.Hour)/time.Second))) + if got := commitMsgThrottleWait(h, now); got != commitMsgGlobalBackoffMax { + t.Errorf("wait above cap = %v, want %v", got, commitMsgGlobalBackoffMax) + } +} + +func TestFetchCommitMessage404DoesNotParkOtherSHAs(t *testing.T) { + resetSHACaches(t) + githubWarnMu.Lock() + githubWarnLast = map[string]time.Time{} + githubWarnMu.Unlock() + now := time.Now() + githubWarnNow = func() time.Time { return now } + t.Cleanup(func() { githubWarnNow = time.Now }) + + hits := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits++ + w.WriteHeader(http.StatusNotFound) + })) + defer srv.Close() + logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)) + c := clientTo(t, srv) + + fetchCommitMessage(c, "1111111aaaa", logger) + fetchCommitMessage(c, "2222222bbbb", logger) + if hits != 2 { + t.Errorf("server hits for two SHAs on 404 = %d, want 2", hits) + } +} diff --git a/src/pkg/review/decision_question_class.go b/src/pkg/review/decision_question_class.go index 3abfd5c968..f945614b3d 100644 --- a/src/pkg/review/decision_question_class.go +++ b/src/pkg/review/decision_question_class.go @@ -20,7 +20,7 @@ type DecisionQuestionClass string const ( // DecisionQuestionPolicySignOff: the ask stays a person's. The PR edits - // workflows from a fork, touches secrets / permissions / OWNERS / + // workflows, 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" @@ -75,8 +75,8 @@ var decisionPolicyPaths = []string{ "**/.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). +// decisionWorkflowPaths are CI-automation paths whose edits require a +// person's sign-off, regardless of where the PR originates. var decisionWorkflowPaths = []string{".github/workflows/**", "**/.github/workflows/**", ".github/actions/**"} // decisionPolicyConfigKeys are hive config keys whose change in a patch is @@ -115,8 +115,8 @@ func ClassifyDecisionQuestion(in DecisionQuestionInput) (DecisionQuestionClass, if p == "" { continue } - if in.FromFork && intent.PathMatchesAny(p, decisionWorkflowPaths) { - return DecisionQuestionPolicySignOff, "fork PR edits workflow path " + p + if intent.PathMatchesAny(p, decisionWorkflowPaths) { + return DecisionQuestionPolicySignOff, "PR edits workflow path " + p } if intent.PathMatchesAny(p, decisionPolicyPaths) { return DecisionQuestionPolicySignOff, "PR touches policy path " + p diff --git a/src/pkg/review/decision_question_class_test.go b/src/pkg/review/decision_question_class_test.go index aa88efd1da..7083b1ebec 100644 --- a/src/pkg/review/decision_question_class_test.go +++ b/src/pkg/review/decision_question_class_test.go @@ -46,12 +46,17 @@ func TestClassifyDecisionQuestion(t *testing.T) { 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", + want: DecisionQuestionPolicySignOff, reason: "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: "same-repo hive PR editing a workflow requires sign-off", + in: green("Should permissions: contents be write?", DecisionQuestionFile{Path: ".github/workflows/ci.yml", Patch: "+permissions:\n+ contents: write\n"}), + want: DecisionQuestionPolicySignOff, reason: "PR edits workflow path", + }, + { + name: "same-repo hive PR editing an action requires sign-off", + in: green("Should this merge ahead of the docs refresh?", DecisionQuestionFile{Path: ".github/actions/build/action.yml"}), + want: DecisionQuestionPolicySignOff, reason: "PR edits workflow path", }, { name: "OWNERS edit is a sign-off however it is phrased", diff --git a/src/pkg/review/hive_superseding_test.go b/src/pkg/review/hive_superseding_test.go index 13bd8d76d9..dc7068d4ae 100644 --- a/src/pkg/review/hive_superseding_test.go +++ b/src/pkg/review/hive_superseding_test.go @@ -3,12 +3,17 @@ package review import ( "strings" "testing" + + "github.com/hivecommons/hive/pkg/outputschema" ) // hiveSupersederSecurityReport is a security-sensitive requires_human on a -// PR the hive created to supersede another PR. +// PR the hive created to supersede another PR, with a finding the fixer +// can act on. func hiveSupersederSecurityReport() PerspectiveReport { - r := baseReport(PerspectiveSecurity, VerdictRequiresHuman) + r := baseReport(PerspectiveSecurity, VerdictRequiresHuman, outputschema.Finding{ + Title: "token logged at debug level", Severity: outputschema.SeverityMedium, File: "auth.go", Line: 12, + }) r.HiveAuthored = true r.HiveSuperseding = true r.DecisionRequested = true @@ -16,6 +21,80 @@ func hiveSupersederSecurityReport() PerspectiveReport { return r } +// hiveSupersederSignOffReport is the hivecommons/hive#16607 shape: every +// perspective requires_human, each only asking an approver to confirm a +// trust-boundary change, with at most an informational finding. +func hiveSupersederSignOffReport(p Perspective) PerspectiveReport { + r := baseReport(p, VerdictRequiresHuman) + r.HiveAuthored = true + r.HiveSuperseding = true + r.DecisionRequested = true + r.DecisionRiskHigh = true + r.DecisionQuestion = "@hanthor should confirm that the relay may now App-merge trusted-author pin-only PRs." + if p == PerspectiveSecurity { + r.Findings = []outputschema.Finding{{ + Title: "relay now lifts the human-merge-path hold", Severity: outputschema.SeverityInfo, + Summary: "Needs approver sign-off, not a code fix.", File: "src/pkg/github/human_merge_paths.go", Line: 269, + }} + } + return r +} + +// TestAggregateHiveSupersedingSignOffOnlyParksForDecision: when every +// perspective's requires_human is a pure approver question with nothing +// above an informational finding, the superseder rule has no fix to route. +// The aggregate keeps the decision request so the stage engine parks the PR +// at 085 needs-decision instead of kicking a fixer that has nothing to fix +// until the cycle is exhausted and the PR is re-authored (#16398 → #16456 +// → #16607). +func TestAggregateHiveSupersedingSignOffOnlyParksForDecision(t *testing.T) { + reports := []PerspectiveReport{ + hiveSupersederSignOffReport(PerspectiveCorrectness), + hiveSupersederSignOffReport(PerspectiveSecurity), + hiveSupersederSignOffReport(PerspectiveStyle), + } + got := AggregateReports(reports, AggregateOptions{}) + + if got.Verdict != VerdictRequiresHuman || !got.RequiresHuman || got.FixCycle || got.MergeEligible { + t.Fatalf("aggregate = %+v, want requires_human park", got) + } + if !got.DecisionRequested || got.DecisionQuestion == "" { + t.Fatalf("aggregate = %+v, want the decision question preserved", got) + } + if hasReason(got.Reasons, HiveSupersedingFixRouteReason) { + t.Fatalf("reasons = %v, must not carry the fix-route reason", got.Reasons) + } + for p, v := range got.Perspectives { + if v != VerdictRequiresHuman { + t.Fatalf("perspective %s = %s, want requires_human kept", p, v) + } + } + if got.Normalize().Verdict != VerdictRequiresHuman { + t.Fatalf("Normalize() = %+v, must not re-route a decision request to the fixer", got.Normalize()) + } +} + +// TestAggregateHiveSupersedingSignOffWithActionableFindingRoutesToFixer: +// a sibling perspective that found code to change keeps the owner's fixer +// route; the sign-off park is only for a swarm with nothing to fix. +func TestAggregateHiveSupersedingSignOffWithActionableFindingRoutesToFixer(t *testing.T) { + for name, extra := range map[string]PerspectiveReport{ + "changes_requested sibling": func() PerspectiveReport { + r := baseReport(PerspectiveCorrectness, VerdictChangesRequested) + r.HiveAuthored, r.HiveSuperseding = true, true + return r + }(), + "requires_human with medium finding": hiveSupersederSecurityReport(), + } { + t.Run(name, func(t *testing.T) { + got := AggregateReports([]PerspectiveReport{hiveSupersederSignOffReport(PerspectiveStyle), extra}, AggregateOptions{}) + if got.Verdict != VerdictChangesRequested || !got.FixCycle || got.DecisionRequested { + t.Fatalf("aggregate = %+v, want changes_requested fixer route", got) + } + }) + } +} + // TestAggregateHiveSupersedingRiskRequiresHumanRoutesToFixer: the owner's // rule — a security/risk requires_human on the hive's superseding PR is a // fix request, not an 085 park. diff --git a/src/pkg/review/review.go b/src/pkg/review/review.go index a6d1ec8933..213694d026 100644 --- a/src/pkg/review/review.go +++ b/src/pkg/review/review.go @@ -481,6 +481,7 @@ func aggregateReports(reports []PerspectiveReport, opts AggregateOptions) Aggreg var decisionQuestions []string var hasReject, hasChanges, unresolvedRequiresHuman, riskEscalation bool var selfAuthoredHumanWithConcreteRemediation, selfAuthoredHumanWithoutRemediation bool + var signOffAsk, requiresHumanBeyondSignOff bool for i, r := range reports { effective := effectiveReports[i] if agg.Repo == "" { @@ -517,6 +518,11 @@ func aggregateReports(reports []PerspectiveReport, opts AggregateOptions) Aggreg case VerdictChangesRequested: hasChanges = true case VerdictRequiresHuman: + if reportAsksForSignOff(r) { + signOffAsk = true + } else { + requiresHumanBeyondSignOff = true + } if selfAuthoredRequiresHumanReportIsResolvable(r, opts) { if reportHasConcreteRemediation(r) { selfAuthoredHumanWithConcreteRemediation = true @@ -557,7 +563,8 @@ func aggregateReports(reports []PerspectiveReport, opts AggregateOptions) Aggreg sortReasons(agg.Reasons) sort.Strings(agg.HumanSummaries) - if hiveSupersedingFixRoute(agg, opts, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman) { + signOffOnly := signOffAsk && !requiresHumanBeyondSignOff && !hasReject && !hasChanges + if hiveSupersedingFixRoute(agg, opts, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman, signOffOnly) { // Owner rule: a PR the hive created to supersede another PR auto- // merges with no operator decision. A reviewer's requires_human — // a risk-class question, a security-sensitive finding — is a @@ -1027,8 +1034,17 @@ const HiveSupersedingFixRouteReason = "hive-authored superseding PR: reviewer re // reject stays a reject: it is an emergent problem with the PR, not a // finding to fix. Everything the self-authored path already resolves on // its own (non-risk questions, concrete remediation) keeps that path. -func hiveSupersedingFixRoute(agg Aggregate, opts AggregateOptions, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman bool) bool { - if !agg.HiveSuperseding || !agg.HiveAuthored || opts.HiveSupersedingAutoMergeOff || hasReject { +// +// signOffOnly is the one requires_human the fixer cannot answer: every +// perspective explicitly deferred a maintainer decision and none raised a +// finding above informational severity (reportAsksForSignOff). Routing that +// to the fixer dispatched six no-op fix kicks, exhausted the cycle, and +// re-authored the same change three times (#16398 → #16456 → #16607) while +// the approver who was asked never saw a decision pill. It stays a +// decision-requested requires_human, which the stage engine parks at 085 +// needs-decision with approve / request-changes options. +func hiveSupersedingFixRoute(agg Aggregate, opts AggregateOptions, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman, signOffOnly bool) bool { + if !agg.HiveSuperseding || !agg.HiveAuthored || opts.HiveSupersedingAutoMergeOff || hasReject || signOffOnly { return false } if strings.EqualFold(strings.TrimSpace(opts.SelfAuthoredDecisionPolicy), "escalate") { @@ -1037,6 +1053,23 @@ func hiveSupersedingFixRoute(agg Aggregate, opts AggregateOptions, hasReject, de return unresolvedRequiresHuman || (decisionRequested && riskEscalation) } +// reportAsksForSignOff reports whether a requires_human report (the caller +// has already established the effective verdict) is a pure approver +// question: it explicitly requested a maintainer decision and carries no +// in-scope finding above informational severity, so there is no code change +// an agent could make to clear it. +func reportAsksForSignOff(r PerspectiveReport) bool { + if !r.DecisionRequested { + return false + } + for _, f := range r.Findings { + if InScopeFinding(f) && severityRank(f.Severity) > severityRank(outputschema.SeverityInfo) { + return false + } + } + return true +} + func reportsHiveSuperseding(reports []PerspectiveReport) bool { for _, r := range reports { if r.HiveSuperseding { diff --git a/src/pkg/stagelabels/hive_superseder_test.go b/src/pkg/stagelabels/hive_superseder_test.go index d71717f9e2..7f46dc11bb 100644 --- a/src/pkg/stagelabels/hive_superseder_test.go +++ b/src/pkg/stagelabels/hive_superseder_test.go @@ -81,3 +81,23 @@ func TestHiveSupersederHardStopReasonRejectsOtherReasons(t *testing.T) { t.Fatal("unknown token must have no prose") } } + +// TestRouteHumanHiveSupersederSignOffQuestionParksAt085: a requires_human +// that still carries its decision question is the aggregate's pure +// approver sign-off (nothing for the fixer, hivecommons/hive#16607). It is +// a decision with approve / request-changes actions, not a 070 row nobody +// is working. +func TestRouteHumanHiveSupersederSignOffQuestionParksAt085(t *testing.T) { + e := hiveSupersederEvidence() + e.DecisionQuestion = "@hanthor should confirm the relay may App-merge trusted pin-only PRs." + r := RouteHuman(e) + if r.Stage != NeedsDecision || r.LaneReason == LaneReasonHiveSupersederFix { + t.Fatalf("route = %+v, want 085 decision", r) + } + if !strings.Contains(strings.Join(r.Reasons, "\n"), "reviewer question: "+e.DecisionQuestion) { + t.Fatalf("reasons = %v, want the reviewer question", r.Reasons) + } + if DecisionActions(r) == "" { + t.Fatalf("route = %+v, want approve / request-changes actions", r) + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 675390fc8e..167f89023f 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -445,11 +445,16 @@ func RouteHuman(e Evidence) Route { } return Route{Stage: NeedsDecision, Reasons: reasons, LaneReason: LaneReasonHiveSupersederHardStopPrefix + token, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, HumanApprover: strings.TrimSpace(e.HumanApprover), Hold: e.Hold} } - if e.Verdict == VerdictRequiresHuman && strings.TrimSpace(e.HumanApprover) == "" { + if e.Verdict == VerdictRequiresHuman && strings.TrimSpace(e.HumanApprover) == "" && strings.TrimSpace(e.DecisionQuestion) == "" { // Owner rule: the reviewer's finding — security-sensitive // included — is the fixer's to address, not a person's to rule // on. The aggregate routes it as changes_requested; the stage - // says so rather than "needs your decision". + // says so rather than "needs your decision". A verdict that + // still carries its decision question is the one case the + // aggregate left for a person (a pure approver sign-off with + // nothing to fix, hivecommons/hive#16607): no fixer is + // dispatched for it, so captioning it "goes to the fixer" + // parked it on 070 with nobody on it; it falls through to 085. note(HiveSupersederAutoMergeCaption+": the reviewer's finding @"+ShortSHA(e.Head)+" goes to the fixer", LaneReasonHiveSupersederFix) } }